├── .github └── FUNDING.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── example.env ├── main.py ├── memory.py ├── process_plugins.py ├── requirements.txt └── roles.json /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | 2 | # These are supported funding model platforms 3 | 4 | github: [HexyeDEV] 5 | patreon: # Replace with a single Patreon username 6 | open_collective: # Replace with a single Open Collective username 7 | ko_fi: # Replace with a single Ko-fi username 8 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 9 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 10 | liberapay: # Replace with a single Liberapay username 11 | issuehunt: # Replace with a single IssueHunt username 12 | otechie: # Replace with a single Otechie username 13 | custom: ["https://buymeacoffee.com/hexye"] 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | .vscode/ 162 | 163 | *.db 164 | *.faiss 165 | *.session 166 | *.session-journal 167 | persist/ -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Citizen Code of Conduct 2 | 3 | ## 1. Purpose 4 | 5 | A primary goal of Telegram Chatbot Gpt4 Free is to be inclusive to the largest number of contributors, with the most varied and diverse backgrounds possible. As such, we are committed to providing a friendly, safe and welcoming environment for all, regardless of gender, sexual orientation, ability, ethnicity, socioeconomic status, and religion (or lack thereof). 6 | 7 | This code of conduct outlines our expectations for all those who participate in our community, as well as the consequences for unacceptable behavior. 8 | 9 | We invite all those who participate in Telegram Chatbot Gpt4 Free to help us create safe and positive experiences for everyone. 10 | 11 | ## 2. Open [Source/Culture/Tech] Citizenship 12 | 13 | A supplemental goal of this Code of Conduct is to increase open [source/culture/tech] citizenship by encouraging participants to recognize and strengthen the relationships between our actions and their effects on our community. 14 | 15 | Communities mirror the societies in which they exist and positive action is essential to counteract the many forms of inequality and abuses of power that exist in society. 16 | 17 | If you see someone who is making an extra effort to ensure our community is welcoming, friendly, and encourages all participants to contribute to the fullest extent, we want to know. 18 | 19 | ## 3. Expected Behavior 20 | 21 | The following behaviors are expected and requested of all community members: 22 | 23 | * Participate in an authentic and active way. In doing so, you contribute to the health and longevity of this community. 24 | * Exercise consideration and respect in your speech and actions. 25 | * Attempt collaboration before conflict. 26 | * Refrain from demeaning, discriminatory, or harassing behavior and speech. 27 | * Be mindful of your surroundings and of your fellow participants. Alert community leaders if you notice a dangerous situation, someone in distress, or violations of this Code of Conduct, even if they seem inconsequential. 28 | * Remember that community event venues may be shared with members of the public; please be respectful to all patrons of these locations. 29 | 30 | ## 4. Unacceptable Behavior 31 | 32 | The following behaviors are considered harassment and are unacceptable within our community: 33 | 34 | * Violence, threats of violence or violent language directed against another person. 35 | * Sexist, racist, homophobic, transphobic, ableist or otherwise discriminatory jokes and language. 36 | * Posting or displaying sexually explicit or violent material. 37 | * Posting or threatening to post other people's personally identifying information ("doxing"). 38 | * Personal insults, particularly those related to gender, sexual orientation, race, religion, or disability. 39 | * Inappropriate photography or recording. 40 | * Inappropriate physical contact. You should have someone's consent before touching them. 41 | * Unwelcome sexual attention. This includes, sexualized comments or jokes; inappropriate touching, groping, and unwelcomed sexual advances. 42 | * Deliberate intimidation, stalking or following (online or in person). 43 | * Advocating for, or encouraging, any of the above behavior. 44 | * Sustained disruption of community events, including talks and presentations. 45 | 46 | ## 5. Weapons Policy 47 | 48 | No weapons will be allowed at Telegram Chatbot Gpt4 Free events, community spaces, or in other spaces covered by the scope of this Code of Conduct. Weapons include but are not limited to guns, explosives (including fireworks), and large knives such as those used for hunting or display, as well as any other item used for the purpose of causing injury or harm to others. Anyone seen in possession of one of these items will be asked to leave immediately, and will only be allowed to return without the weapon. Community members are further expected to comply with all state and local laws on this matter. 49 | 50 | ## 6. Consequences of Unacceptable Behavior 51 | 52 | Unacceptable behavior from any community member, including sponsors and those with decision-making authority, will not be tolerated. 53 | 54 | Anyone asked to stop unacceptable behavior is expected to comply immediately. 55 | 56 | If a community member engages in unacceptable behavior, the community organizers may take any action they deem appropriate, up to and including a temporary ban or permanent expulsion from the community without warning (and without refund in the case of a paid event). 57 | 58 | ## 7. Reporting Guidelines 59 | 60 | If you are subject to or witness unacceptable behavior, or have any other concerns, please notify a community organizer as soon as possible. . 61 | 62 | 63 | 64 | Additionally, community organizers are available to help community members engage with local law enforcement or to otherwise help those experiencing unacceptable behavior feel safe. In the context of in-person events, organizers will also provide escorts as desired by the person experiencing distress. 65 | 66 | ## 8. Addressing Grievances 67 | 68 | If you feel you have been falsely or unfairly accused of violating this Code of Conduct, you should notify with a concise description of your grievance. Your grievance will be handled in accordance with our existing governing policies. 69 | 70 | 71 | 72 | ## 9. Scope 73 | 74 | We expect all community participants (contributors, paid or otherwise; sponsors; and other guests) to abide by this Code of Conduct in all community venues--online and in-person--as well as in all one-on-one communications pertaining to community business. 75 | 76 | This code of conduct and its related procedures also applies to unacceptable behavior occurring outside the scope of community activities when such behavior has the potential to adversely affect the safety and well-being of community members. 77 | 78 | ## 10. Contact info 79 | 80 | 81 | 82 | ## 11. License and attribution 83 | 84 | The Citizen Code of Conduct is distributed by [Stumptown Syndicate](http://stumptownsyndicate.org) under a [Creative Commons Attribution-ShareAlike license](http://creativecommons.org/licenses/by-sa/3.0/). 85 | 86 | Portions of text derived from the [Django Code of Conduct](https://www.djangoproject.com/conduct/) and the [Geek Feminism Anti-Harassment Policy](http://geekfeminism.wikia.com/wiki/Conference_anti-harassment/Policy). 87 | 88 | _Revision 2.3. Posted 6 March 2017._ 89 | 90 | _Revision 2.2. Posted 4 February 2016._ 91 | 92 | _Revision 2.1. Posted 23 June 2014._ 93 | 94 | _Revision 2.0, adopted by the [Stumptown Syndicate](http://stumptownsyndicate.org) board on 10 January 2013. Posted 17 March 2013._ 95 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Hexye 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Telegram-Chatbot-Gpt4Free 2 | This is a Python-based Telegram bot using the telethon library. The bot responds to messages using the GPT4FREE repo. This bot also supports plugins, roles, dan jailbreak and long term memory via vector database 3 | 4 | # Installation 5 | Clone the repo 6 | 7 | ```git clone https://github.com/HexyeDEV/Telegram-Chatbot-Gpt4Free.git``` 8 | After that go to the cloned repo directory. 9 | 10 | Edit the example.env file with: 11 | 12 | API_ID is your api id from https://my.telegram.org 13 | 14 | API_HASH is your api hash from https://my.telegram.org 15 | 16 | BOT_TOKEN is your bot token from Bot Father 17 | 18 | If you want to use WalframAlpha plugin, you will need to create an app at https://products.wolframalpha.com/api/ and set WOLFRAMALPHA_APP_ID in the example.env to the APP_ID of your Wolfram apllication. 19 | 20 | After that, rename example.env into .env. 21 | 22 | Install all the packages running ```pip install -r requirements.txt```(may change based on your python version, settings and os.) 23 | 24 | Now run main.py with ```python3 main.py```(may change based on your python version, settings and os.) 25 | 26 | Enjoy! 27 | 28 | # Commands: 29 | 30 | /help - see a command list 31 | 32 | /plugins toggle - enable/disable plugins 33 | 34 | /plugins list - list all plugins 35 | 36 | /newrole - create a new role 37 | 38 | /roles - list all the roles 39 | 40 | /role - enable a role 41 | 42 | /role disable - disable roles 43 | 44 | /memory - enable/disable memory 45 | 46 | /addmemory - add something to the memory without receiving AI response. 47 | 48 | # Provider Used 49 | 50 | This project is using [GPT4FREE](https://github.com/xtekky/gpt4free) 51 | -------------------------------------------------------------------------------- /example.env: -------------------------------------------------------------------------------- 1 | API_ID=1234 2 | API_HASH=abcde123456 3 | BOT_TOKEN=1klFJ0f099JFJalf0jAPFE- 4 | WOLFRAMALPHA_APP_ID=TEST-APP -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | from telethon import TelegramClient 2 | from telethon.events import NewMessage 3 | from dotenv import load_dotenv 4 | from os import getenv 5 | import json 6 | from memory import Memory 7 | from uuid import uuid4 8 | from g4f import AsyncClient 9 | from g4f.Provider import RetryProvider, ChatGptEs, DDG, Jmuz, Liaobots, OIVSCode, Pizzagpt, PollinationsAI 10 | from process_plugins import process_plugins 11 | 12 | load_dotenv() 13 | 14 | memory = Memory('BotMemories') 15 | 16 | api_id = getenv('API_ID') 17 | api_hash = getenv('API_HASH') 18 | bot_token = getenv('BOT_TOKEN') 19 | wolframalpha_app_id = getenv('WOLFRAMALPHA_APP_ID') 20 | 21 | if not api_id or not api_hash or not bot_token: 22 | raise Exception('API_ID, API_HASH and BOT_TOKEN must be set in .env file') 23 | 24 | client = TelegramClient('bot', api_id, api_hash) 25 | GPTClient = AsyncClient( 26 | provider=RetryProvider([ChatGptEs, DDG, Jmuz, Liaobots, OIVSCode, Pizzagpt, PollinationsAI], shuffle=True) 27 | ) 28 | 29 | PLUGINS = False 30 | MEMORY = False 31 | ROLE = "" 32 | plugins_dict = { 33 | "wolframalpha": "Wolframalpha plugin lets you perform math operations. If appropriate to use it, answer exactly with: \"[WOLFRAMALPHA END]\" where query is the operation you need to solve. Examples: Input: Solve for x: 2x+3=5 Output: [WOLFRAMALPHA solve (2x+3=5) for x END] Input: A*2=B solve for B Output: [WOLFRAMALPHA solve (A*2=B) for B END]. Even if you got the input in a different language, always use english in the wolframalpha query.", 34 | } 35 | plugins_string = "" 36 | for plugin in plugins_dict: 37 | plugins_string += f"\n{plugin}: {plugins_dict[plugin]}" 38 | 39 | PLUGIN_PROMPT = f"You will be given a list of plugins with description. Based on what the plugin's description says, if you think a plugin is appropriate to use, answer with the instructions to use it. If no plugin is needed, do not mention them. The available plugins are: {plugins_string}" 40 | 41 | def _format_text(text): 42 | text = text.replace("[[Login to OpenAI ChatGPT]]()", "") 43 | text = text.replace("\\[\n", "") 44 | text = text.replace("\\]", "") 45 | text = text.replace("\\n", "\n") 46 | text = text.replace("\\(", "(") 47 | text = text.replace("\\)", ")") 48 | return text 49 | 50 | async def AiAgent(prompt, system_prompt=""): 51 | req = await GPTClient.chat.completions.create(model="gpt-4o-mini", messages=[{"content": system_prompt, "role": "system"},{"content": prompt, "role": "user"}]) 52 | full_text = req.choices[0].message.content 53 | return _format_text(full_text) 54 | 55 | @client.on(NewMessage(pattern='/start')) 56 | async def start(event): 57 | await event.respond('Hey! Write something and I will answer you using the gpt-4o-mini model or add me to a group and I will answer you when you mention me.') 58 | 59 | @client.on(NewMessage(pattern='/help')) 60 | async def help(event): 61 | await event.respond('Hey! Write something and I will answer you using the gpt-4o-mini model or add me to a group and I will answer you when you mention me.\nCommands:\n\n/plugins toggle - enable/disable plugins\n\n/plugins list - list all plugins\n\n/newrole - add a new role\n\n/roles - list all roles\n\n/role enable a role\n\n/role disable - disable roles\n\n/memory - enable/disable memory\n\n/addmemory - add something to the memory without receiving AI response.') 62 | 63 | @client.on(NewMessage(pattern='/plugins list')) 64 | async def pls(event): 65 | pls = [] 66 | for plugin in plugins_dict: 67 | pls.append(plugin) 68 | await event.respond("Available plugins are:\n{}".format("\n".join(pls))) 69 | 70 | @client.on(NewMessage(pattern='/plugins toggle')) 71 | async def pls_toggle(event): 72 | global PLUGINS 73 | PLUGINS = not PLUGINS 74 | if PLUGINS == True and not wolframalpha_app_id or PLUGINS == True and wolframalpha_app_id == "TEST-APP": 75 | await event.respond("You need to set a wolframalpha app id in the .env file to use plugins.") 76 | PLUGINS = False 77 | return 78 | await event.respond("Plugins enabled" if PLUGINS == True else "Plugins disabled") 79 | 80 | @client.on(NewMessage(pattern='/newrole')) 81 | async def newrole(event): 82 | with open("roles.json", "r") as f: 83 | roles = f.read() 84 | roles = json.loads(roles) 85 | try: 86 | role_name = event.text.split(" ")[1] 87 | role = event.text.split(" ", 2)[2] 88 | except IndexError: 89 | await event.respond("You need to specify a role name and a role.") 90 | return 91 | roles[role_name] = role 92 | with open("roles.json", "w") as f: 93 | f.write(json.dumps(roles)) 94 | await event.respond("Role added") 95 | 96 | @client.on(NewMessage(pattern='/roles')) 97 | async def roles(event): 98 | with open("roles.json", "r") as f: 99 | roles = f.read() 100 | roles = json.loads(roles) 101 | await event.respond("Available roles:\n{}".format("\n".join(roles.keys()))) 102 | 103 | @client.on(NewMessage(pattern='/role')) 104 | async def role(event): 105 | global ROLE 106 | with open("roles.json", "r") as f: 107 | roles = f.read() 108 | roles = json.loads(roles) 109 | try: 110 | role = event.text.split(" ")[1] 111 | except IndexError: 112 | await event.respond("You need to specify a role.") 113 | return 114 | if role not in roles: 115 | await event.respond("Role not found.") 116 | return 117 | ROLE = role 118 | await event.respond("Role enabled") 119 | 120 | @client.on(NewMessage(pattern='/memory')) 121 | async def memory_command(event): 122 | global MEMORY 123 | MEMORY = not MEMORY 124 | await event.respond("Memory enabled" if MEMORY == True else "Memory disabled") 125 | 126 | @client.on(NewMessage(pattern='/addmemory')) 127 | async def addmemory(event): 128 | global memory 129 | text = event.text.split(' ', 1)[1] 130 | memory.insert(text, str(uuid4())) 131 | await event.respond("Memory added") 132 | 133 | @client.on(NewMessage()) 134 | async def message(event): 135 | global PLUGINS 136 | global MEMORY 137 | global ROLE 138 | my_id = await client.get_me() 139 | my_id = my_id.id 140 | my_username = await client.get_me() 141 | my_username = my_username.username 142 | if event.text.startswith("/"): 143 | return 144 | if not event.is_private: 145 | if not event.text.startswith(f'@{my_username}'): 146 | return 147 | prompt = event.text.replace(f'@{my_username}', '') 148 | if ROLE and PLUGINS: 149 | await event.respond("You can't use roles and plugins at the same time.") 150 | return 151 | msg = await event.respond("Thinking...") 152 | got_end_result = False 153 | if ROLE: 154 | with open("roles.json", "r") as f: 155 | roles = f.read() 156 | roles = json.loads(roles) 157 | if ROLE not in roles: 158 | ROLE = "" 159 | system_prompt = "" 160 | if ROLE: 161 | system_prompt = roles[ROLE] 162 | if MEMORY: 163 | res = memory.find(prompt, 1) 164 | if len(res) > 0 and res != []: 165 | system_prompt = system_prompt + "To answer the next question these data may be relevant: " + res[0][0] 166 | if PLUGINS: 167 | result = await AiAgent(prompt, system_prompt) 168 | should_query, query = process_plugins(result) 169 | if should_query: 170 | result = await AiAgent(query, system_prompt) 171 | got_end_result = True 172 | if not got_end_result: 173 | result = await AiAgent(prompt, system_prompt) 174 | if MEMORY: 175 | memory.insert(prompt, str(uuid4)) 176 | memory.insert(result, str(uuid4)) 177 | await msg.edit(result) 178 | 179 | 180 | client.start(bot_token=bot_token) 181 | client.run_until_disconnected() -------------------------------------------------------------------------------- /memory.py: -------------------------------------------------------------------------------- 1 | import faiss 2 | import pickle 3 | import os 4 | import numpy as np 5 | 6 | 7 | class Memory: 8 | def __init__(self, name, dim=512): 9 | self.name = name 10 | self.dim = dim 11 | self.index_path = f"./persist/{name}.faiss" 12 | self.data_path = f"./persist/{name}_data.pkl" 13 | self.index = faiss.IndexFlatL2(dim) 14 | self.data = {} 15 | 16 | if not os.path.exists("./persist"): 17 | os.makedirs("./persist") 18 | 19 | self._load_index() 20 | 21 | def _load_index(self): 22 | if os.path.exists(self.index_path): 23 | self.index = faiss.read_index(self.index_path) 24 | if os.path.exists(self.data_path): 25 | with open(self.data_path, "rb") as f: 26 | self.data = pickle.load(f) 27 | 28 | def _save_index(self): 29 | faiss.write_index(self.index, self.index_path) 30 | with open(self.data_path, "wb") as f: 31 | pickle.dump(self.data, f) 32 | 33 | def insert(self, data, uuid): 34 | if uuid in self.data: 35 | return # Avoid duplicate entries 36 | 37 | self.data[uuid] = data 38 | vector = np.random.rand(512) 39 | vector = np.array([vector], dtype=np.float32) 40 | if self.index.is_trained: 41 | self.index.add(vector) 42 | else: 43 | self.index.train(vector) 44 | self.index.add(vector) 45 | self._save_index() 46 | 47 | def find(self, query_vector, n_results=2): 48 | if self.index.ntotal == 0: 49 | return [] 50 | 51 | query_vector = np.array([query_vector], dtype=np.float32) 52 | distances, indices = self.index.search(query_vector, n_results) 53 | results = [] 54 | for i, distance in zip(indices[0], distances[0]): 55 | if i in self.data: 56 | results.append((self.data[i], distance)) 57 | return results 58 | -------------------------------------------------------------------------------- /process_plugins.py: -------------------------------------------------------------------------------- 1 | import wolframalpha 2 | from os import getenv 3 | 4 | plugins_second_question = { 5 | "wolframalpha": "Explain the following wolframalpha results in a comprehensive way considering the user input was: \n\nwolframalpha result: . If no result is given, then try to answer the question on your own. After the answer, add the text: [Wolfram]", 6 | } 7 | 8 | def process_plugins(result): 9 | if "[WOLFRAMALPHA" in result: 10 | return _process_wolframalpha(result) 11 | else: 12 | return [False, ""] 13 | 14 | def _process_wolframalpha(result): 15 | query = result.replace(f"[WOLFRAMALPHA ", "").replace(" END]", "") 16 | wolframalpha_app_id = getenv("WOLFRAMALPHA_APP_ID") 17 | wf_client = wolframalpha.Client(app_id=wolframalpha_app_id) 18 | res = wf_client.query(query) 19 | if res["@success"] == False: 20 | return [False, ""] 21 | else: 22 | w_result = next(res.results).text 23 | return[True, plugins_second_question["wolframalpha"].replace("", query).replace("", w_result)] -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | python-dotenv==1.0.0 2 | Telethon==1.26.1 3 | wolframalpha==5.0 4 | aiohttp==3.11.13 5 | pandas==2.2.3 6 | pyarrow==19.0.1 7 | faiss-cpu==1.10.0 8 | g4f==0.4.7.7 -------------------------------------------------------------------------------- /roles.json: -------------------------------------------------------------------------------- 1 | { 2 | "magician": "I want you to act as a magician. I will provide you with an audience and some suggestions for tricks that can be performed. Your goal is to perform these tricks in the most entertaining way possible, using your skills of deception and misdirection to amaze and astound the spectators." 3 | } --------------------------------------------------------------------------------