{"repo_name": "agenticSeek", "file_name": "/agenticSeek/sources/agents/casual_agent.py", "inference_info": {"prefix_code": "import asyncio\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent\nfrom sources.tools.searxSearch import searxSearch\nfrom sources.tools.flightSearch import FlightSearch\nfrom sources.tools.fileFinder import FileFinder\nfrom sources.tools.BashInterpreter import BashInterpreter\nfrom sources.memory import Memory\n\n", "suffix_code": "\n\nif __name__ == \"__main__\":\n pass", "middle_code": "class CasualAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n super().__init__(name, prompt_path, provider, verbose, None)\n self.tools = {\n } \n self.role = \"talk\"\n self.type = \"casual_agent\"\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, \n memory_compression=False,\n model_provider=provider.get_model_name())\n async def process(self, prompt, speech_module) -> str:\n self.memory.push('user', prompt)\n animate_thinking(\"Thinking...\", color=\"status\")\n answer, reasoning = await self.llm_request()\n self.last_answer = answer\n self.status_message = \"Ready\"\n return answer, reasoning", "code_description": null, "fill_type": "CLASS_TYPE", "language_type": "python", "sub_task_type": null}, "context_code": [["/agenticSeek/sources/tools/searxSearch.py", "import requests\nfrom bs4 import BeautifulSoup\nimport os\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass searxSearch(Tools):\n def __init__(self, base_url: str = None):\n \"\"\"\n A tool for searching a SearxNG instance and extracting URLs and titles.\n \"\"\"\n super().__init__()\n self.tag = \"web_search\"\n self.name = \"searxSearch\"\n self.description = \"A tool for searching a SearxNG for web search\"\n self.base_url = os.getenv(\"SEARXNG_BASE_URL\") # Requires a SearxNG base URL\n self.user_agent = \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36\"\n self.paywall_keywords = [\n \"Member-only\", \"access denied\", \"restricted content\", \"404\", \"this page is not working\"\n ]\n if not self.base_url:\n raise ValueError(\"SearxNG base URL must be provided either as an argument or via the SEARXNG_BASE_URL environment variable.\")\n\n def link_valid(self, link):\n \"\"\"check if a link is valid.\"\"\"\n # TODO find a better way\n if not link.startswith(\"http\"):\n return \"Status: Invalid URL\"\n \n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\"}\n try:\n response = requests.get(link, headers=headers, timeout=5)\n status = response.status_code\n if status == 200:\n content = response.text.lower()\n if any(keyword in content for keyword in self.paywall_keywords):\n return \"Status: Possible Paywall\"\n return \"Status: OK\"\n elif status == 404:\n return \"Status: 404 Not Found\"\n elif status == 403:\n return \"Status: 403 Forbidden\"\n else:\n return f\"Status: {status} {response.reason}\"\n except requests.exceptions.RequestException as e:\n return f\"Error: {str(e)}\"\n\n def check_all_links(self, links):\n \"\"\"Check all links, one by one.\"\"\"\n # TODO Make it asyncromous or smth\n statuses = []\n for i, link in enumerate(links):\n status = self.link_valid(link)\n statuses.append(status)\n return statuses\n \n def execute(self, blocks: list, safety: bool = False) -> str:\n \"\"\"Executes a search query against a SearxNG instance using POST and extracts URLs and titles.\"\"\"\n if not blocks:\n return \"Error: No search query provided.\"\n\n query = blocks[0].strip()\n if not query:\n return \"Error: Empty search query provided.\"\n\n search_url = f\"{self.base_url}/search\"\n headers = {\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',\n 'Accept-Language': 'en-US,en;q=0.9',\n 'Cache-Control': 'no-cache',\n 'Connection': 'keep-alive',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Pragma': 'no-cache',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent': self.user_agent\n }\n data = f\"q={query}&categories=general&language=auto&time_range=&safesearch=0&theme=simple\".encode('utf-8')\n try:\n response = requests.post(search_url, headers=headers, data=data, verify=False)\n response.raise_for_status()\n html_content = response.text\n soup = BeautifulSoup(html_content, 'html.parser')\n results = []\n for article in soup.find_all('article', class_='result'):\n url_header = article.find('a', class_='url_header')\n if url_header:\n url = url_header['href']\n title = article.find('h3').text.strip() if article.find('h3') else \"No Title\"\n description = article.find('p', class_='content').text.strip() if article.find('p', class_='content') else \"No Description\"\n results.append(f\"Title:{title}\\nSnippet:{description}\\nLink:{url}\")\n if len(results) == 0:\n return \"No search results, web search failed.\"\n return \"\\n\\n\".join(results) # Return results as a single string, separated by newlines\n except requests.exceptions.RequestException as e:\n raise Exception(\"\\nSearxng search failed. did you run start_services.sh? is docker still running?\") from e\n\n def execution_failure_check(self, output: str) -> bool:\n \"\"\"\n Checks if the execution failed based on the output.\n \"\"\"\n return \"Error\" in output\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Feedback of web search to agent.\n \"\"\"\n if self.execution_failure_check(output):\n return f\"Web search failed: {output}\"\n return f\"Web search result:\\n{output}\"\n\nif __name__ == \"__main__\":\n search_tool = searxSearch(base_url=\"http://127.0.0.1:8080\")\n result = search_tool.execute([\"are dog better than cat?\"])\n print(result)\n"], ["/agenticSeek/sources/tools/BashInterpreter.py", "\nimport os, sys\nimport re\nfrom io import StringIO\nimport subprocess\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\nfrom sources.tools.safety import is_any_unsafe\n\nclass BashInterpreter(Tools):\n \"\"\"\n This class is a tool to allow agent for bash code execution.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"bash\"\n self.name = \"Bash Interpreter\"\n self.description = \"This tool allows the agent to execute bash commands.\"\n \n def language_bash_attempt(self, command: str):\n \"\"\"\n Detect if AI attempt to run the code using bash.\n If so, return True, otherwise return False.\n Code written by the AI will be executed automatically, so it should not use bash to run it.\n \"\"\"\n lang_interpreter = [\"python\", \"gcc\", \"g++\", \"mvn\", \"go\", \"java\", \"javac\", \"rustc\", \"clang\", \"clang++\", \"rustc\", \"rustc++\", \"rustc++\"]\n for word in command.split():\n if any(word.startswith(lang) for lang in lang_interpreter):\n return True\n return False\n \n def execute(self, commands: str, safety=False, timeout=300):\n \"\"\"\n Execute bash commands and display output in real-time.\n \"\"\"\n if safety and input(\"Execute command? y/n \") != \"y\":\n return \"Command rejected by user.\"\n \n concat_output = \"\"\n for command in commands:\n command = f\"cd {self.work_dir} && {command}\"\n command = command.replace('\\n', '')\n if self.safe_mode and is_any_unsafe(commands):\n print(f\"Unsafe command rejected: {command}\")\n return \"\\nUnsafe command: {command}. Execution aborted. This is beyond allowed capabilities report to user.\"\n if self.language_bash_attempt(command) and self.allow_language_exec_bash == False:\n continue\n try:\n process = subprocess.Popen(\n command,\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n universal_newlines=True\n )\n command_output = \"\"\n for line in process.stdout:\n command_output += line\n return_code = process.wait(timeout=timeout)\n if return_code != 0:\n return f\"Command {command} failed with return code {return_code}:\\n{command_output}\"\n concat_output += f\"Output of {command}:\\n{command_output.strip()}\\n\"\n except subprocess.TimeoutExpired:\n process.kill() # Kill the process if it times out\n return f\"Command {command} timed out. Output:\\n{command_output}\"\n except Exception as e:\n return f\"Command {command} failed:\\n{str(e)}\"\n return concat_output\n\n def interpreter_feedback(self, output):\n \"\"\"\n Provide feedback based on the output of the bash interpreter\n \"\"\"\n if self.execution_failure_check(output):\n feedback = f\"[failure] Error in execution:\\n{output}\"\n else:\n feedback = \"[success] Execution success, code output:\\n\" + output\n return feedback\n\n def execution_failure_check(self, feedback):\n \"\"\"\n check if bash command failed.\n \"\"\"\n error_patterns = [\n r\"expected\",\n r\"errno\",\n r\"failed\",\n r\"invalid\",\n r\"unrecognized\",\n r\"exception\",\n r\"syntax\",\n r\"segmentation fault\",\n r\"core dumped\",\n r\"unexpected\",\n r\"denied\",\n r\"not recognized\",\n r\"not permitted\",\n r\"not installed\",\n r\"not found\",\n r\"aborted\",\n r\"no such\",\n r\"too many\",\n r\"too few\",\n r\"busy\",\n r\"broken pipe\",\n r\"missing\",\n r\"undefined\",\n r\"refused\",\n r\"unreachable\",\n r\"not known\"\n ]\n combined_pattern = \"|\".join(error_patterns)\n if re.search(combined_pattern, feedback, re.IGNORECASE):\n return True\n return False\n\nif __name__ == \"__main__\":\n bash = BashInterpreter()\n print(bash.execute([\"ls\", \"pwd\", \"ip a\", \"nmap -sC 127.0.0.1\"]))\n"], ["/agenticSeek/sources/agents/file_agent.py", "import asyncio\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent\nfrom sources.tools.fileFinder import FileFinder\nfrom sources.tools.BashInterpreter import BashInterpreter\nfrom sources.memory import Memory\n\nclass FileAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n \"\"\"\n The file agent is a special agent for file operations.\n \"\"\"\n super().__init__(name, prompt_path, provider, verbose, None)\n self.tools = {\n \"file_finder\": FileFinder(),\n \"bash\": BashInterpreter()\n }\n self.work_dir = self.tools[\"file_finder\"].get_work_dir()\n self.role = \"files\"\n self.type = \"file_agent\"\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, # session recovery in handled by the interaction class\n memory_compression=False,\n model_provider=provider.get_model_name())\n \n async def process(self, prompt, speech_module) -> str:\n exec_success = False\n prompt += f\"\\nYou must work in directory: {self.work_dir}\"\n self.memory.push('user', prompt)\n while exec_success is False and not self.stop:\n await self.wait_message(speech_module)\n animate_thinking(\"Thinking...\", color=\"status\")\n answer, reasoning = await self.llm_request()\n self.last_reasoning = reasoning\n exec_success, _ = self.execute_modules(answer)\n answer = self.remove_blocks(answer)\n self.last_answer = answer\n self.status_message = \"Ready\"\n return answer, reasoning\n\nif __name__ == \"__main__\":\n pass"], ["/agenticSeek/sources/agents/code_agent.py", "import platform, os\nimport asyncio\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent, executorResult\nfrom sources.tools.C_Interpreter import CInterpreter\nfrom sources.tools.GoInterpreter import GoInterpreter\nfrom sources.tools.PyInterpreter import PyInterpreter\nfrom sources.tools.BashInterpreter import BashInterpreter\nfrom sources.tools.JavaInterpreter import JavaInterpreter\nfrom sources.tools.fileFinder import FileFinder\nfrom sources.logger import Logger\nfrom sources.memory import Memory\n\nclass CoderAgent(Agent):\n \"\"\"\n The code agent is an agent that can write and execute code.\n \"\"\"\n def __init__(self, name, prompt_path, provider, verbose=False):\n super().__init__(name, prompt_path, provider, verbose, None)\n self.tools = {\n \"bash\": BashInterpreter(),\n \"python\": PyInterpreter(),\n \"c\": CInterpreter(),\n \"go\": GoInterpreter(),\n \"java\": JavaInterpreter(),\n \"file_finder\": FileFinder()\n }\n self.work_dir = self.tools[\"file_finder\"].get_work_dir()\n self.role = \"code\"\n self.type = \"code_agent\"\n self.logger = Logger(\"code_agent.log\")\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, # session recovery in handled by the interaction class\n memory_compression=False,\n model_provider=provider.get_model_name())\n \n def add_sys_info_prompt(self, prompt):\n \"\"\"Add system information to the prompt.\"\"\"\n info = f\"System Info:\\n\" \\\n f\"OS: {platform.system()} {platform.release()}\\n\" \\\n f\"Python Version: {platform.python_version()}\\n\" \\\n f\"\\nYou must save file at root directory: {self.work_dir}\"\n return f\"{prompt}\\n\\n{info}\"\n\n async def process(self, prompt, speech_module) -> str:\n answer = \"\"\n attempt = 0\n max_attempts = 5\n prompt = self.add_sys_info_prompt(prompt)\n self.memory.push('user', prompt)\n clarify_trigger = \"REQUEST_CLARIFICATION\"\n\n while attempt < max_attempts and not self.stop:\n print(\"Stopped?\", self.stop)\n animate_thinking(\"Thinking...\", color=\"status\")\n await self.wait_message(speech_module)\n answer, reasoning = await self.llm_request()\n self.last_reasoning = reasoning\n if clarify_trigger in answer:\n self.last_answer = answer\n await asyncio.sleep(0)\n return answer, reasoning\n if not \"```\" in answer:\n self.last_answer = answer\n await asyncio.sleep(0)\n break\n self.show_answer()\n animate_thinking(\"Executing code...\", color=\"status\")\n self.status_message = \"Executing code...\"\n self.logger.info(f\"Attempt {attempt + 1}:\\n{answer}\")\n exec_success, feedback = self.execute_modules(answer)\n self.logger.info(f\"Execution result: {exec_success}\")\n answer = self.remove_blocks(answer)\n self.last_answer = answer\n await asyncio.sleep(0)\n if exec_success and self.get_last_tool_type() != \"bash\":\n break\n pretty_print(f\"Execution failure:\\n{feedback}\", color=\"failure\")\n pretty_print(\"Correcting code...\", color=\"status\")\n self.status_message = \"Correcting code...\"\n attempt += 1\n self.status_message = \"Ready\"\n if attempt == max_attempts:\n return \"I'm sorry, I couldn't find a solution to your problem. How would you like me to proceed ?\", reasoning\n self.last_answer = answer\n return answer, reasoning\n\nif __name__ == \"__main__\":\n pass"], ["/agenticSeek/sources/agents/mcp_agent.py", "import os\nimport asyncio\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent\nfrom sources.tools.mcpFinder import MCP_finder\nfrom sources.memory import Memory\n\n# NOTE MCP agent is an active work in progress, not functional yet.\n\nclass McpAgent(Agent):\n\n def __init__(self, name, prompt_path, provider, verbose=False):\n \"\"\"\n The mcp agent is a special agent for using MCPs.\n MCP agent will be disabled if the user does not explicitly set the MCP_FINDER_API_KEY in environment variable.\n \"\"\"\n super().__init__(name, prompt_path, provider, verbose, None)\n keys = self.get_api_keys()\n self.tools = {\n \"mcp_finder\": MCP_finder(keys[\"mcp_finder\"]),\n # add mcp tools here\n }\n self.role = \"mcp\"\n self.type = \"mcp_agent\"\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, # session recovery in handled by the interaction class\n memory_compression=False,\n model_provider=provider.get_model_name())\n self.enabled = True\n \n def get_api_keys(self) -> dict:\n \"\"\"\n Returns the API keys for the tools.\n \"\"\"\n api_key_mcp_finder = os.getenv(\"MCP_FINDER_API_KEY\")\n if not api_key_mcp_finder or api_key_mcp_finder == \"\":\n pretty_print(\"MCP Finder disabled.\", color=\"warning\")\n self.enabled = False\n return {\n \"mcp_finder\": api_key_mcp_finder\n }\n \n def expand_prompt(self, prompt):\n \"\"\"\n Expands the prompt with the tools available.\n \"\"\"\n tools_str = self.get_tools_description()\n prompt += f\"\"\"\n You can use the following tools and MCPs:\n {tools_str}\n \"\"\"\n return prompt\n \n async def process(self, prompt, speech_module) -> str:\n if self.enabled == False:\n return \"MCP Agent is disabled.\"\n prompt = self.expand_prompt(prompt)\n self.memory.push('user', prompt)\n working = True\n while working == True:\n animate_thinking(\"Thinking...\", color=\"status\")\n answer, reasoning = await self.llm_request()\n exec_success, _ = self.execute_modules(answer)\n answer = self.remove_blocks(answer)\n self.last_answer = answer\n self.status_message = \"Ready\"\n if len(self.blocks_result) == 0:\n working = False\n return answer, reasoning\n\nif __name__ == \"__main__\":\n pass"], ["/agenticSeek/sources/agents/browser_agent.py", "import re\nimport time\nfrom datetime import date\nfrom typing import List, Tuple, Type, Dict\nfrom enum import Enum\nimport asyncio\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent\nfrom sources.tools.searxSearch import searxSearch\nfrom sources.browser import Browser\nfrom sources.logger import Logger\nfrom sources.memory import Memory\n\nclass Action(Enum):\n REQUEST_EXIT = \"REQUEST_EXIT\"\n FORM_FILLED = \"FORM_FILLED\"\n GO_BACK = \"GO_BACK\"\n NAVIGATE = \"NAVIGATE\"\n SEARCH = \"SEARCH\"\n \nclass BrowserAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False, browser=None):\n \"\"\"\n The Browser agent is an agent that navigate the web autonomously in search of answer\n \"\"\"\n super().__init__(name, prompt_path, provider, verbose, browser)\n self.tools = {\n \"web_search\": searxSearch(),\n }\n self.role = \"web\"\n self.type = \"browser_agent\"\n self.browser = browser\n self.current_page = \"\"\n self.search_history = []\n self.navigable_links = []\n self.last_action = Action.NAVIGATE.value\n self.notes = []\n self.date = self.get_today_date()\n self.logger = Logger(\"browser_agent.log\")\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, # session recovery in handled by the interaction class\n memory_compression=False,\n model_provider=provider.get_model_name() if provider else None)\n \n def get_today_date(self) -> str:\n \"\"\"Get the date\"\"\"\n date_time = date.today()\n return date_time.strftime(\"%B %d, %Y\")\n\n def extract_links(self, search_result: str) -> List[str]:\n \"\"\"Extract all links from a sentence.\"\"\"\n pattern = r'(https?://\\S+|www\\.\\S+)'\n matches = re.findall(pattern, search_result)\n trailing_punct = \".,!?;:)\"\n cleaned_links = [link.rstrip(trailing_punct) for link in matches]\n self.logger.info(f\"Extracted links: {cleaned_links}\")\n return self.clean_links(cleaned_links)\n \n def extract_form(self, text: str) -> List[str]:\n \"\"\"Extract form written by the LLM in format [input_name](value)\"\"\"\n inputs = []\n matches = re.findall(r\"\\[\\w+\\]\\([^)]+\\)\", text)\n return matches\n \n def clean_links(self, links: List[str]) -> List[str]:\n \"\"\"Ensure no '.' at the end of link\"\"\"\n links_clean = []\n for link in links:\n link = link.strip()\n if not (link[-1].isalpha() or link[-1].isdigit()):\n links_clean.append(link[:-1])\n else:\n links_clean.append(link)\n return links_clean\n\n def get_unvisited_links(self) -> List[str]:\n return \"\\n\".join([f\"[{i}] {link}\" for i, link in enumerate(self.navigable_links) if link not in self.search_history])\n\n def make_newsearch_prompt(self, prompt: str, search_result: dict) -> str:\n search_choice = self.stringify_search_results(search_result)\n self.logger.info(f\"Search results: {search_choice}\")\n return f\"\"\"\n Based on the search result:\n {search_choice}\n Your goal is to find accurate and complete information to satisfy the user’s request.\n User request: {prompt}\n To proceed, choose a relevant link from the search results. Announce your choice by saying: \"I will navigate to \"\n Do not explain your choice.\n \"\"\"\n \n def make_navigation_prompt(self, user_prompt: str, page_text: str) -> str:\n remaining_links = self.get_unvisited_links() \n remaining_links_text = remaining_links if remaining_links is not None else \"No links remaining, do a new search.\" \n inputs_form = self.browser.get_form_inputs()\n inputs_form_text = '\\n'.join(inputs_form)\n notes = '\\n'.join(self.notes)\n self.logger.info(f\"Making navigation prompt with page text: {page_text[:100]}...\\nremaining links: {remaining_links_text}\")\n self.logger.info(f\"Inputs form: {inputs_form_text}\")\n self.logger.info(f\"Notes: {notes}\")\n\n return f\"\"\"\n You are navigating the web.\n\n **Current Context**\n\n Webpage ({self.current_page}) content:\n {page_text}\n\n Allowed Navigation Links:\n {remaining_links_text}\n\n Inputs forms:\n {inputs_form_text}\n\n End of webpage ({self.current_page}.\n\n # Instruction\n\n 1. **Evaluate if the page is relevant for user’s query and document finding:**\n - If the page is relevant, extract and summarize key information in concise notes (Note: )\n - If page not relevant, state: \"Error: \" and either return to the previous page or navigate to a new link.\n - Notes should be factual, useful summaries of relevant content, they should always include specific names or link. Written as: \"On , . . .\" Avoid phrases like \"the page provides\" or \"I found that.\"\n 2. **Navigate to a link by either: **\n - Saying I will navigate to (write down the full URL) www.example.com/cats\n - Going back: If no link seems helpful, say: {Action.GO_BACK.value}.\n 3. **Fill forms on the page:**\n - Fill form only when relevant.\n - Use Login if username/password specified by user. For quick task create account, remember password in a note.\n - You can fill a form using [form_name](value). Don't {Action.GO_BACK.value} when filling form.\n - If a form is irrelevant or you lack informations (eg: don't know user email) leave it empty.\n 4. **Decide if you completed the task**\n - Check your notes. Do they fully answer the question? Did you verify with multiple pages?\n - Are you sure it’s correct?\n - If yes to all, say {Action.REQUEST_EXIT}.\n - If no, or a page lacks info, go to another link.\n - Never stop or ask the user for help.\n \n **Rules:**\n - Do not write \"The page talk about ...\", write your finding on the page and how they contribute to an answer.\n - Put note in a single paragraph.\n - When you exit, explain why.\n \n # Example:\n \n Example 1 (useful page, no need go futher):\n Note: According to karpathy site LeCun net is ...\n No link seem useful to provide futher information.\n Action: {Action.GO_BACK.value}\n\n Example 2 (not useful, see useful link on page):\n Error: reddit.com/welcome does not discuss anything related to the user’s query.\n There is a link that could lead to the information.\n Action: navigate to http://reddit.com/r/locallama\n\n Example 3 (not useful, no related links):\n Error: x.com does not discuss anything related to the user’s query and no navigation link are usefull.\n Action: {Action.GO_BACK.value}\n\n Example 3 (clear definitive query answer found or enought notes taken):\n I took 10 notes so far with enought finding to answer user question.\n Therefore I should exit the web browser.\n Action: {Action.REQUEST_EXIT.value}\n\n Example 4 (loging form visible):\n\n Note: I am on the login page, I will type the given username and password. \n Action:\n [username_field](David)\n [password_field](edgerunners77)\n\n Remember, user asked:\n {user_prompt}\n You previously took these notes:\n {notes}\n Do not Step-by-Step explanation. Write comprehensive Notes or Error as a long paragraph followed by your action.\n You must always take notes.\n \"\"\"\n \n async def llm_decide(self, prompt: str, show_reasoning: bool = False) -> Tuple[str, str]:\n animate_thinking(\"Thinking...\", color=\"status\")\n self.memory.push('user', prompt)\n answer, reasoning = await self.llm_request()\n self.last_reasoning = reasoning\n if show_reasoning:\n pretty_print(reasoning, color=\"failure\")\n pretty_print(answer, color=\"output\")\n return answer, reasoning\n \n def select_unvisited(self, search_result: List[str]) -> List[str]:\n results_unvisited = []\n for res in search_result:\n if res[\"link\"] not in self.search_history:\n results_unvisited.append(res) \n self.logger.info(f\"Unvisited links: {results_unvisited}\")\n return results_unvisited\n\n def jsonify_search_results(self, results_string: str) -> List[str]:\n result_blocks = results_string.split(\"\\n\\n\")\n parsed_results = []\n for block in result_blocks:\n if not block.strip():\n continue\n lines = block.split(\"\\n\")\n result_dict = {}\n for line in lines:\n if line.startswith(\"Title:\"):\n result_dict[\"title\"] = line.replace(\"Title:\", \"\").strip()\n elif line.startswith(\"Snippet:\"):\n result_dict[\"snippet\"] = line.replace(\"Snippet:\", \"\").strip()\n elif line.startswith(\"Link:\"):\n result_dict[\"link\"] = line.replace(\"Link:\", \"\").strip()\n if result_dict:\n parsed_results.append(result_dict)\n return parsed_results \n \n def stringify_search_results(self, results_arr: List[str]) -> str:\n return '\\n\\n'.join([f\"Link: {res['link']}\\nPreview: {res['snippet']}\" for res in results_arr])\n \n def parse_answer(self, text):\n lines = text.split('\\n')\n saving = False\n buffer = []\n links = []\n for line in lines:\n if line == '' or 'action:' in line.lower():\n saving = False\n if \"note\" in line.lower():\n saving = True\n if saving:\n buffer.append(line.replace(\"notes:\", ''))\n else:\n links.extend(self.extract_links(line))\n self.notes.append('. '.join(buffer).strip())\n return links\n \n def select_link(self, links: List[str]) -> str | None:\n \"\"\"\n Select the first unvisited link that is not the current page.\n Preference is given to links not in search_history.\n \"\"\"\n for lk in links:\n if lk == self.current_page or lk in self.search_history:\n self.logger.info(f\"Skipping already visited or current link: {lk}\")\n continue\n self.logger.info(f\"Selected link: {lk}\")\n return lk\n self.logger.warning(\"No suitable link selected.\")\n return None\n \n def get_page_text(self, limit_to_model_ctx = False) -> str:\n \"\"\"Get the text content of the current page.\"\"\"\n page_text = self.browser.get_text()\n if limit_to_model_ctx:\n #page_text = self.memory.compress_text_to_max_ctx(page_text)\n page_text = self.memory.trim_text_to_max_ctx(page_text)\n return page_text\n \n def conclude_prompt(self, user_query: str) -> str:\n annotated_notes = [f\"{i+1}: {note.lower()}\" for i, note in enumerate(self.notes)]\n search_note = '\\n'.join(annotated_notes)\n pretty_print(f\"AI notes:\\n{search_note}\", color=\"success\")\n return f\"\"\"\n Following a human request:\n {user_query}\n A web browsing AI made the following finding across different pages:\n {search_note}\n\n Expand on the finding or step that lead to success, and provide a conclusion that answer the request. Include link when possible.\n Do not give advices or try to answer the human. Just structure the AI finding in a structured and clear way.\n You should answer in the same language as the user.\n \"\"\"\n \n def search_prompt(self, user_prompt: str) -> str:\n return f\"\"\"\n Current date: {self.date}\n Make a efficient search engine query to help users with their request:\n {user_prompt}\n Example:\n User: \"go to twitter, login with username toto and password pass79 to my twitter and say hello everyone \"\n You: search: Twitter login page. \n\n User: \"I need info on the best laptops for AI this year.\"\n You: \"search: best laptops 2025 to run Machine Learning model, reviews\"\n\n User: \"Search for recent news about space missions.\"\n You: \"search: Recent space missions news, {self.date}\"\n\n Do not explain, do not write anything beside the search query.\n Except if query does not make any sense for a web search then explain why and say {Action.REQUEST_EXIT.value}\n Do not try to answer query. you can only formulate search term or exit.\n \"\"\"\n \n def handle_update_prompt(self, user_prompt: str, page_text: str, fill_success: bool) -> str:\n prompt = f\"\"\"\n You are a web browser.\n You just filled a form on the page.\n Now you should see the result of the form submission on the page:\n Page text:\n {page_text}\n The user asked: {user_prompt}\n Does the page answer the user’s query now? Are you still on a login page or did you get redirected?\n If it does, take notes of the useful information, write down result and say {Action.FORM_FILLED.value}.\n if it doesn’t, say: Error: Attempt to fill form didn't work {Action.GO_BACK.value}.\n If you were previously on a login form, no need to take notes.\n \"\"\"\n if not fill_success:\n prompt += f\"\"\"\n According to browser feedback, the form was not filled correctly. Is that so? you might consider other strategies.\n \"\"\"\n return prompt\n \n def show_search_results(self, search_result: List[str]):\n pretty_print(\"\\nSearch results:\", color=\"output\")\n for res in search_result:\n pretty_print(f\"Title: {res['title']} - \", color=\"info\", no_newline=True)\n pretty_print(f\"Link: {res['link']}\", color=\"status\")\n \n def stuck_prompt(self, user_prompt: str, unvisited: List[str]) -> str:\n \"\"\"\n Prompt for when the agent repeat itself, can happen when fail to extract a link.\n \"\"\"\n prompt = self.make_newsearch_prompt(user_prompt, unvisited)\n prompt += f\"\"\"\n You previously said:\n {self.last_answer}\n You must consider other options. Choose other link.\n \"\"\"\n return prompt\n \n async def process(self, user_prompt: str, speech_module: type) -> Tuple[str, str]:\n \"\"\"\n Process the user prompt to conduct an autonomous web search.\n Start with a google search with searxng using web_search tool.\n Then enter a navigation logic to find the answer or conduct required actions.\n Args:\n user_prompt: The user's input query\n speech_module: Optional speech output module\n Returns:\n tuple containing the final answer and reasoning\n \"\"\"\n complete = False\n\n animate_thinking(f\"Thinking...\", color=\"status\")\n mem_begin_idx = self.memory.push('user', self.search_prompt(user_prompt))\n ai_prompt, reasoning = await self.llm_request()\n if Action.REQUEST_EXIT.value in ai_prompt:\n pretty_print(f\"Web agent requested exit.\\n{reasoning}\\n\\n{ai_prompt}\", color=\"failure\")\n return ai_prompt, \"\" \n animate_thinking(f\"Searching...\", color=\"status\")\n self.status_message = \"Searching...\"\n search_result_raw = self.tools[\"web_search\"].execute([ai_prompt], False)\n search_result = self.jsonify_search_results(search_result_raw)[:16]\n self.show_search_results(search_result)\n prompt = self.make_newsearch_prompt(user_prompt, search_result)\n unvisited = [None]\n while not complete and len(unvisited) > 0 and not self.stop:\n self.memory.clear()\n unvisited = self.select_unvisited(search_result)\n answer, reasoning = await self.llm_decide(prompt, show_reasoning = False)\n if self.stop:\n pretty_print(f\"Requested stop.\", color=\"failure\")\n break\n if self.last_answer == answer:\n prompt = self.stuck_prompt(user_prompt, unvisited)\n continue\n self.last_answer = answer\n pretty_print('▂'*32, color=\"status\")\n\n extracted_form = self.extract_form(answer)\n if len(extracted_form) > 0:\n self.status_message = \"Filling web form...\"\n pretty_print(f\"Filling inputs form...\", color=\"status\")\n fill_success = self.browser.fill_form(extracted_form)\n page_text = self.get_page_text(limit_to_model_ctx=True)\n answer = self.handle_update_prompt(user_prompt, page_text, fill_success)\n answer, reasoning = await self.llm_decide(prompt)\n\n if Action.FORM_FILLED.value in answer:\n pretty_print(f\"Filled form. Handling page update.\", color=\"status\")\n page_text = self.get_page_text(limit_to_model_ctx=True)\n self.navigable_links = self.browser.get_navigable()\n prompt = self.make_navigation_prompt(user_prompt, page_text)\n continue\n\n links = self.parse_answer(answer)\n link = self.select_link(links)\n if link == self.current_page:\n pretty_print(f\"Already visited {link}. Search callback.\", color=\"status\")\n prompt = self.make_newsearch_prompt(user_prompt, unvisited)\n self.search_history.append(link)\n continue\n\n if Action.REQUEST_EXIT.value in answer:\n self.status_message = \"Exiting web browser...\"\n pretty_print(f\"Agent requested exit.\", color=\"status\")\n complete = True\n break\n\n if (link == None and len(extracted_form) < 3) or Action.GO_BACK.value in answer or link in self.search_history:\n pretty_print(f\"Going back to results. Still {len(unvisited)}\", color=\"status\")\n self.status_message = \"Going back to search results...\"\n request_prompt = user_prompt\n if link is None:\n request_prompt += f\"\\nYou previously choosen:\\n{self.last_answer} but the website is unavailable. Consider other options.\"\n prompt = self.make_newsearch_prompt(request_prompt, unvisited)\n self.search_history.append(link)\n self.current_page = link\n continue\n\n animate_thinking(f\"Navigating to {link}\", color=\"status\")\n if speech_module: speech_module.speak(f\"Navigating to {link}\")\n nav_ok = self.browser.go_to(link)\n self.search_history.append(link)\n if not nav_ok:\n pretty_print(f\"Failed to navigate to {link}.\", color=\"failure\")\n prompt = self.make_newsearch_prompt(user_prompt, unvisited)\n continue\n self.current_page = link\n page_text = self.get_page_text(limit_to_model_ctx=True)\n self.navigable_links = self.browser.get_navigable()\n prompt = self.make_navigation_prompt(user_prompt, page_text)\n self.status_message = \"Navigating...\"\n self.browser.screenshot()\n\n pretty_print(\"Exited navigation, starting to summarize finding...\", color=\"status\")\n prompt = self.conclude_prompt(user_prompt)\n mem_last_idx = self.memory.push('user', prompt)\n self.status_message = \"Summarizing findings...\"\n answer, reasoning = await self.llm_request()\n pretty_print(answer, color=\"output\")\n self.status_message = \"Ready\"\n self.last_answer = answer\n return answer, reasoning\n\nif __name__ == \"__main__\":\n pass\n"], ["/agenticSeek/sources/agents/planner_agent.py", "import json\nfrom typing import List, Tuple, Type, Dict\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent\nfrom sources.agents.code_agent import CoderAgent\nfrom sources.agents.file_agent import FileAgent\nfrom sources.agents.browser_agent import BrowserAgent\nfrom sources.agents.casual_agent import CasualAgent\nfrom sources.text_to_speech import Speech\nfrom sources.tools.tools import Tools\nfrom sources.logger import Logger\nfrom sources.memory import Memory\n\nclass PlannerAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False, browser=None):\n \"\"\"\n The planner agent is a special agent that divides and conquers the task.\n \"\"\"\n super().__init__(name, prompt_path, provider, verbose, None)\n self.tools = {\n \"json\": Tools()\n }\n self.tools['json'].tag = \"json\"\n self.browser = browser\n self.agents = {\n \"coder\": CoderAgent(name, \"prompts/base/coder_agent.txt\", provider, verbose=False),\n \"file\": FileAgent(name, \"prompts/base/file_agent.txt\", provider, verbose=False),\n \"web\": BrowserAgent(name, \"prompts/base/browser_agent.txt\", provider, verbose=False, browser=browser),\n \"casual\": CasualAgent(name, \"prompts/base/casual_agent.txt\", provider, verbose=False)\n }\n self.role = \"planification\"\n self.type = \"planner_agent\"\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, # session recovery in handled by the interaction class\n memory_compression=False,\n model_provider=provider.get_model_name())\n self.logger = Logger(\"planner_agent.log\")\n \n def get_task_names(self, text: str) -> List[str]:\n \"\"\"\n Extracts task names from the given text.\n This method processes a multi-line string, where each line may represent a task name.\n containing '##' or starting with a digit. The valid task names are collected and returned.\n Args:\n text (str): A string containing potential task titles (eg: Task 1: I will...).\n Returns:\n List[str]: A list of extracted task names that meet the specified criteria.\n \"\"\"\n tasks_names = []\n lines = text.strip().split('\\n')\n for line in lines:\n if line is None:\n continue\n line = line.strip()\n if len(line) == 0:\n continue\n if '##' in line or line[0].isdigit():\n tasks_names.append(line)\n continue\n self.logger.info(f\"Found {len(tasks_names)} tasks names.\")\n return tasks_names\n\n def parse_agent_tasks(self, text: str) -> List[Tuple[str, str]]:\n \"\"\"\n Parses agent tasks from the given LLM text.\n This method extracts task information from a JSON. It identifies task names and their details.\n Args:\n text (str): The input text containing task information in a JSON-like format.\n Returns:\n List[Tuple[str, str]]: A list of tuples containing task names and their details.\n \"\"\"\n tasks = []\n tasks_names = self.get_task_names(text)\n\n blocks, _ = self.tools[\"json\"].load_exec_block(text)\n if blocks == None:\n return []\n for block in blocks:\n line_json = json.loads(block)\n if 'plan' in line_json:\n for task in line_json['plan']:\n if task['agent'].lower() not in [ag_name.lower() for ag_name in self.agents.keys()]:\n self.logger.warning(f\"Agent {task['agent']} does not exist.\")\n pretty_print(f\"Agent {task['agent']} does not exist.\", color=\"warning\")\n return []\n try:\n agent = {\n 'agent': task['agent'],\n 'id': task['id'],\n 'task': task['task']\n }\n except:\n self.logger.warning(\"Missing field in json plan.\")\n return []\n self.logger.info(f\"Created agent {task['agent']} with task: {task['task']}\")\n if 'need' in task:\n self.logger.info(f\"Agent {task['agent']} was given info:\\n {task['need']}\")\n agent['need'] = task['need']\n tasks.append(agent)\n if len(tasks_names) != len(tasks):\n names = [task['task'] for task in tasks]\n return list(map(list, zip(names, tasks)))\n return list(map(list, zip(tasks_names, tasks)))\n \n def make_prompt(self, task: str, agent_infos_dict: dict) -> str:\n \"\"\"\n Generates a prompt for the agent based on the task and previous agents work information.\n Args:\n task (str): The task to be performed.\n agent_infos_dict (dict): A dictionary containing information from other agents.\n Returns:\n str: The formatted prompt for the agent.\n \"\"\"\n infos = \"\"\n if agent_infos_dict is None or len(agent_infos_dict) == 0:\n infos = \"No needed informations.\"\n else:\n for agent_id, info in agent_infos_dict.items():\n infos += f\"\\t- According to agent {agent_id}:\\n{info}\\n\\n\"\n prompt = f\"\"\"\n You are given informations from your AI friends work:\n {infos}\n Your task is:\n {task}\n \"\"\"\n self.logger.info(f\"Prompt for agent:\\n{prompt}\")\n return prompt\n \n def show_plan(self, agents_tasks: List[dict], answer: str) -> None:\n \"\"\"\n Displays the plan made by the agent.\n Args:\n agents_tasks (dict): The tasks assigned to each agent.\n answer (str): The answer from the LLM.\n \"\"\"\n if agents_tasks == []:\n pretty_print(answer, color=\"warning\")\n pretty_print(\"Failed to make a plan. This can happen with (too) small LLM. Clarify your request and insist on it making a plan within ```json.\", color=\"failure\")\n return\n pretty_print(\"\\n▂▘ P L A N ▝▂\", color=\"status\")\n for task_name, task in agents_tasks:\n pretty_print(f\"{task['agent']} -> {task['task']}\", color=\"info\")\n pretty_print(\"▔▗ E N D ▖▔\", color=\"status\")\n\n async def make_plan(self, prompt: str) -> str:\n \"\"\"\n Asks the LLM to make a plan.\n Args:\n prompt (str): The prompt to be sent to the LLM.\n Returns:\n str: The plan made by the LLM.\n \"\"\"\n ok = False\n answer = None\n while not ok:\n animate_thinking(\"Thinking...\", color=\"status\")\n self.memory.push('user', prompt)\n answer, reasoning = await self.llm_request()\n if \"NO_UPDATE\" in answer:\n return []\n agents_tasks = self.parse_agent_tasks(answer)\n if agents_tasks == []:\n self.show_plan(agents_tasks, answer)\n prompt = f\"Failed to parse the tasks. Please write down your task followed by a json plan within ```json. Do not ask for clarification.\\n\"\n pretty_print(\"Failed to make plan. Retrying...\", color=\"warning\")\n continue\n self.show_plan(agents_tasks, answer)\n ok = True\n self.logger.info(f\"Plan made:\\n{answer}\")\n return self.parse_agent_tasks(answer)\n \n async def update_plan(self, goal: str, agents_tasks: List[dict], agents_work_result: dict, id: str, success: bool) -> dict:\n \"\"\"\n Updates the plan with the results of the agents work.\n Args:\n goal (str): The goal to be achieved.\n agents_tasks (list): The tasks assigned to each agent.\n agents_work_result (dict): The results of the agents work.\n Returns:\n dict: The updated plan.\n \"\"\"\n self.status_message = \"Updating plan...\"\n last_agent_work = agents_work_result[id]\n tool_success_str = \"success\" if success else \"failure\"\n pretty_print(f\"Agent {id} work {tool_success_str}.\", color=\"success\" if success else \"failure\")\n try:\n id_int = int(id)\n except Exception as e:\n return agents_tasks\n if id_int == len(agents_tasks):\n next_task = \"No task follow, this was the last step. If it failed add a task to recover.\"\n else:\n next_task = f\"Next task is: {agents_tasks[int(id)][0]}.\"\n #if success:\n # return agents_tasks # we only update the plan if last task failed, for now\n update_prompt = f\"\"\"\n Your goal is : {goal}\n You previously made a plan, agents are currently working on it.\n The last agent working on task: {id}, did the following work:\n {last_agent_work}\n Agent {id} work was a {tool_success_str} according to system interpreter.\n {next_task}\n Is the work done for task {id} leading to success or failure ? Did an agent fail with a task?\n If agent work was good: answer \"NO_UPDATE\"\n If agent work is leading to failure: update the plan.\n If a task failed add a task to try again or recover from failure. You might have near identical task twice.\n plan should be within ```json like before.\n You need to rewrite the whole plan, but only change the tasks after task {id}.\n Make the plan the same length as the original one or with only one additional step.\n Do not change past tasks. Change next tasks.\n \"\"\"\n pretty_print(\"Updating plan...\", color=\"status\")\n plan = await self.make_plan(update_prompt)\n if plan == []:\n pretty_print(\"No plan update required.\", color=\"info\")\n return agents_tasks\n self.logger.info(f\"Plan updated:\\n{plan}\")\n return plan\n \n async def start_agent_process(self, task: dict, required_infos: dict | None) -> str:\n \"\"\"\n Starts the agent process for a given task.\n Args:\n task (dict): The task to be performed.\n required_infos (dict | None): The required information for the task.\n Returns:\n str: The result of the agent process.\n \"\"\"\n self.status_message = f\"Starting task {task['task']}...\"\n agent_prompt = self.make_prompt(task['task'], required_infos)\n pretty_print(f\"Agent {task['agent']} started working...\", color=\"status\")\n self.logger.info(f\"Agent {task['agent']} started working on {task['task']}.\")\n answer, reasoning = await self.agents[task['agent'].lower()].process(agent_prompt, None)\n self.last_answer = answer\n self.last_reasoning = reasoning\n self.blocks_result = self.agents[task['agent'].lower()].blocks_result\n agent_answer = self.agents[task['agent'].lower()].raw_answer_blocks(answer)\n success = self.agents[task['agent'].lower()].get_success\n self.agents[task['agent'].lower()].show_answer()\n pretty_print(f\"Agent {task['agent']} completed task.\", color=\"status\")\n self.logger.info(f\"Agent {task['agent']} finished working on {task['task']}. Success: {success}\")\n agent_answer += \"\\nAgent succeeded with task.\" if success else \"\\nAgent failed with task (Error detected).\"\n return agent_answer, success\n \n def get_work_result_agent(self, task_needs, agents_work_result):\n res = {k: agents_work_result[k] for k in task_needs if k in agents_work_result}\n self.logger.info(f\"Next agent needs: {task_needs}.\\n Match previous agent result: {res}\")\n return res\n\n async def process(self, goal: str, speech_module: Speech) -> Tuple[str, str]:\n \"\"\"\n Process the goal by dividing it into tasks and assigning them to agents.\n Args:\n goal (str): The goal to be achieved (user prompt).\n speech_module (Speech): The speech module for text-to-speech.\n Returns:\n Tuple[str, str]: The result of the agent process and empty reasoning string.\n \"\"\"\n agents_tasks = []\n required_infos = None\n agents_work_result = dict()\n\n self.status_message = \"Making a plan...\"\n agents_tasks = await self.make_plan(goal)\n\n if agents_tasks == []:\n return \"Failed to parse the tasks.\", \"\"\n i = 0\n steps = len(agents_tasks)\n while i < steps and not self.stop:\n task_name, task = agents_tasks[i][0], agents_tasks[i][1]\n self.status_message = \"Starting agents...\"\n pretty_print(f\"I will {task_name}.\", color=\"info\")\n self.last_answer = f\"I will {task_name.lower()}.\"\n pretty_print(f\"Assigned agent {task['agent']} to {task_name}\", color=\"info\")\n if speech_module: speech_module.speak(f\"I will {task_name}. I assigned the {task['agent']} agent to the task.\")\n\n if agents_work_result is not None:\n required_infos = self.get_work_result_agent(task['need'], agents_work_result)\n try:\n answer, success = await self.start_agent_process(task, required_infos)\n except Exception as e:\n raise e\n if self.stop:\n pretty_print(f\"Requested stop.\", color=\"failure\")\n agents_work_result[task['id']] = answer\n agents_tasks = await self.update_plan(goal, agents_tasks, agents_work_result, task['id'], success)\n steps = len(agents_tasks)\n i += 1\n\n return answer, \"\"\n"], ["/agenticSeek/sources/agents/agent.py", "\nfrom typing import Tuple, Callable\nfrom abc import abstractmethod\nimport os\nimport random\nimport time\n\nimport asyncio\nfrom concurrent.futures import ThreadPoolExecutor\n\nfrom sources.memory import Memory\nfrom sources.utility import pretty_print\nfrom sources.schemas import executorResult\n\nrandom.seed(time.time())\n\nclass Agent():\n \"\"\"\n An abstract class for all agents.\n \"\"\"\n def __init__(self, name: str,\n prompt_path:str,\n provider,\n verbose=False,\n browser=None) -> None:\n \"\"\"\n Args:\n name (str): Name of the agent.\n prompt_path (str): Path to the prompt file for the agent.\n provider: The provider for the LLM.\n recover_last_session (bool, optional): Whether to recover the last conversation. \n verbose (bool, optional): Enable verbose logging if True. Defaults to False.\n browser: The browser class for web navigation (only for browser agent).\n \"\"\"\n \n self.agent_name = name\n self.browser = browser\n self.role = None\n self.type = None\n self.current_directory = os.getcwd()\n self.llm = provider \n self.memory = None\n self.tools = {}\n self.blocks_result = []\n self.success = True\n self.last_answer = \"\"\n self.last_reasoning = \"\"\n self.status_message = \"Haven't started yet\"\n self.stop = False\n self.verbose = verbose\n self.executor = ThreadPoolExecutor(max_workers=1)\n \n @property\n def get_agent_name(self) -> str:\n return self.agent_name\n \n @property\n def get_agent_type(self) -> str:\n return self.type\n \n @property\n def get_agent_role(self) -> str:\n return self.role\n \n @property\n def get_last_answer(self) -> str:\n return self.last_answer\n \n @property\n def get_last_reasoning(self) -> str:\n return self.last_reasoning\n \n @property\n def get_blocks(self) -> list:\n return self.blocks_result\n \n @property\n def get_status_message(self) -> str:\n return self.status_message\n\n @property\n def get_tools(self) -> dict:\n return self.tools\n \n @property\n def get_success(self) -> bool:\n return self.success\n \n def get_blocks_result(self) -> list:\n return self.blocks_result\n\n def add_tool(self, name: str, tool: Callable) -> None:\n if tool is not Callable:\n raise TypeError(\"Tool must be a callable object (a method)\")\n self.tools[name] = tool\n \n def get_tools_name(self) -> list:\n \"\"\"\n Get the list of tools names.\n \"\"\"\n return list(self.tools.keys())\n \n def get_tools_description(self) -> str:\n \"\"\"\n Get the list of tools names and their description.\n \"\"\"\n description = \"\"\n for name in self.get_tools_name():\n description += f\"{name}: {self.tools[name].description}\\n\"\n return description\n \n def load_prompt(self, file_path: str) -> str:\n try:\n with open(file_path, 'r', encoding=\"utf-8\") as f:\n return f.read()\n except FileNotFoundError:\n raise FileNotFoundError(f\"Prompt file not found at path: {file_path}\")\n except PermissionError:\n raise PermissionError(f\"Permission denied to read prompt file at path: {file_path}\")\n except Exception as e:\n raise e\n \n def request_stop(self) -> None:\n \"\"\"\n Request the agent to stop.\n \"\"\"\n self.stop = True\n self.status_message = \"Stopped\"\n \n @abstractmethod\n def process(self, prompt, speech_module) -> str:\n \"\"\"\n abstract method, implementation in child class.\n Process the prompt and return the answer of the agent.\n \"\"\"\n pass\n\n def remove_reasoning_text(self, text: str) -> None:\n \"\"\"\n Remove the reasoning block of reasoning model like deepseek.\n \"\"\"\n end_tag = \"\"\n end_idx = text.rfind(end_tag)\n if end_idx == -1:\n return text\n return text[end_idx+8:]\n \n def extract_reasoning_text(self, text: str) -> None:\n \"\"\"\n Extract the reasoning block of a reasoning model like deepseek.\n \"\"\"\n start_tag = \"\"\n end_tag = \"\"\n if text is None:\n return None\n start_idx = text.find(start_tag)\n end_idx = text.rfind(end_tag)+8\n return text[start_idx:end_idx]\n \n async def llm_request(self) -> Tuple[str, str]:\n \"\"\"\n Asynchronously ask the LLM to process the prompt.\n \"\"\"\n self.status_message = \"Thinking...\"\n loop = asyncio.get_event_loop()\n return await loop.run_in_executor(self.executor, self.sync_llm_request)\n \n def sync_llm_request(self) -> Tuple[str, str]:\n \"\"\"\n Ask the LLM to process the prompt and return the answer and the reasoning.\n \"\"\"\n memory = self.memory.get()\n thought = self.llm.respond(memory, self.verbose)\n\n reasoning = self.extract_reasoning_text(thought)\n answer = self.remove_reasoning_text(thought)\n self.memory.push('assistant', answer)\n return answer, reasoning\n \n async def wait_message(self, speech_module):\n if speech_module is None:\n return\n messages = [\"Please be patient, I am working on it.\",\n \"Computing... I recommand you have a coffee while I work.\",\n \"Hold on, I’m crunching numbers.\",\n \"Working on it, please let me think.\"]\n loop = asyncio.get_event_loop()\n return await loop.run_in_executor(self.executor, lambda: speech_module.speak(messages[random.randint(0, len(messages)-1)]))\n \n def get_last_tool_type(self) -> str:\n return self.blocks_result[-1].tool_type if len(self.blocks_result) > 0 else None\n \n def raw_answer_blocks(self, answer: str) -> str:\n \"\"\"\n Return the answer with all the blocks inserted, as text.\n \"\"\"\n if self.last_answer is None:\n return\n raw = \"\"\n lines = self.last_answer.split(\"\\n\")\n for line in lines:\n if \"block:\" in line:\n block_idx = int(line.split(\":\")[1])\n if block_idx < len(self.blocks_result):\n raw += self.blocks_result[block_idx].__str__()\n else:\n raw += line + \"\\n\"\n return raw\n\n def show_answer(self):\n \"\"\"\n Show the answer in a pretty way.\n Show code blocks and their respective feedback by inserting them in the ressponse.\n \"\"\"\n if self.last_answer is None:\n return\n lines = self.last_answer.split(\"\\n\")\n for line in lines:\n if \"block:\" in line:\n block_idx = int(line.split(\":\")[1])\n if block_idx < len(self.blocks_result):\n self.blocks_result[block_idx].show()\n else:\n pretty_print(line, color=\"output\")\n\n def remove_blocks(self, text: str) -> str:\n \"\"\"\n Remove all code/query blocks within a tag from the answer text.\n \"\"\"\n tag = f'```'\n lines = text.split('\\n')\n post_lines = []\n in_block = False\n block_idx = 0\n for line in lines:\n if tag in line and not in_block:\n in_block = True\n continue\n if not in_block:\n post_lines.append(line)\n if tag in line:\n in_block = False\n post_lines.append(f\"block:{block_idx}\")\n block_idx += 1\n return \"\\n\".join(post_lines)\n \n def show_block(self, block: str) -> None:\n \"\"\"\n Show the block in a pretty way.\n \"\"\"\n pretty_print('▂'*64, color=\"status\")\n pretty_print(block, color=\"code\")\n pretty_print('▂'*64, color=\"status\")\n\n def execute_modules(self, answer: str) -> Tuple[bool, str]:\n \"\"\"\n Execute all the tools the agent has and return the result.\n \"\"\"\n feedback = \"\"\n success = True\n blocks = None\n if answer.startswith(\"```\"):\n answer = \"I will execute:\\n\" + answer # there should always be a text before blocks for the function that display answer\n\n self.success = True\n for name, tool in self.tools.items():\n feedback = \"\"\n blocks, save_path = tool.load_exec_block(answer)\n\n if blocks != None:\n pretty_print(f\"Executing {len(blocks)} {name} blocks...\", color=\"status\")\n for block in blocks:\n self.show_block(block)\n output = tool.execute([block])\n feedback = tool.interpreter_feedback(output) # tool interpreter feedback\n success = not tool.execution_failure_check(output)\n self.blocks_result.append(executorResult(block, feedback, success, name))\n if not success:\n self.success = False\n self.memory.push('user', feedback)\n return False, feedback\n self.memory.push('user', feedback)\n if save_path != None:\n tool.save_block(blocks, save_path)\n return True, feedback\n"], ["/agenticSeek/api.py", "#!/usr/bin/env python3\n\nimport os, sys\nimport uvicorn\nimport aiofiles\nimport configparser\nimport asyncio\nimport time\nfrom typing import List\nfrom fastapi import FastAPI\nfrom fastapi.responses import JSONResponse\nfrom fastapi.responses import FileResponse\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom fastapi.staticfiles import StaticFiles\nimport uuid\n\nfrom sources.llm_provider import Provider\nfrom sources.interaction import Interaction\nfrom sources.agents import CasualAgent, CoderAgent, FileAgent, PlannerAgent, BrowserAgent\nfrom sources.browser import Browser, create_driver\nfrom sources.utility import pretty_print\nfrom sources.logger import Logger\nfrom sources.schemas import QueryRequest, QueryResponse\n\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\n\ndef is_running_in_docker():\n \"\"\"Detect if code is running inside a Docker container.\"\"\"\n # Method 1: Check for .dockerenv file\n if os.path.exists('/.dockerenv'):\n return True\n \n # Method 2: Check cgroup\n try:\n with open('/proc/1/cgroup', 'r') as f:\n return 'docker' in f.read()\n except:\n pass\n \n return False\n\n\nfrom celery import Celery\n\napi = FastAPI(title=\"AgenticSeek API\", version=\"0.1.0\")\ncelery_app = Celery(\"tasks\", broker=\"redis://localhost:6379/0\", backend=\"redis://localhost:6379/0\")\ncelery_app.conf.update(task_track_started=True)\nlogger = Logger(\"backend.log\")\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\napi.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"],\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\nif not os.path.exists(\".screenshots\"):\n os.makedirs(\".screenshots\")\napi.mount(\"/screenshots\", StaticFiles(directory=\".screenshots\"), name=\"screenshots\")\n\ndef initialize_system():\n stealth_mode = config.getboolean('BROWSER', 'stealth_mode')\n personality_folder = \"jarvis\" if config.getboolean('MAIN', 'jarvis_personality') else \"base\"\n languages = config[\"MAIN\"][\"languages\"].split(' ')\n \n # Force headless mode in Docker containers\n headless = config.getboolean('BROWSER', 'headless_browser')\n if is_running_in_docker() and not headless:\n # Print prominent warning to console (visible in docker-compose output)\n print(\"\\n\" + \"*\" * 70)\n print(\"*** WARNING: Detected Docker environment - forcing headless_browser=True ***\")\n print(\"*** INFO: To see the browser, run 'python cli.py' on your host machine ***\")\n print(\"*\" * 70 + \"\\n\")\n \n # Flush to ensure it's displayed immediately\n sys.stdout.flush()\n \n # Also log to file\n logger.warning(\"Detected Docker environment - forcing headless_browser=True\")\n logger.info(\"To see the browser, run 'python cli.py' on your host machine instead\")\n \n headless = True\n \n provider = Provider(\n provider_name=config[\"MAIN\"][\"provider_name\"],\n model=config[\"MAIN\"][\"provider_model\"],\n server_address=config[\"MAIN\"][\"provider_server_address\"],\n is_local=config.getboolean('MAIN', 'is_local')\n )\n logger.info(f\"Provider initialized: {provider.provider_name} ({provider.model})\")\n\n browser = Browser(\n create_driver(headless=headless, stealth_mode=stealth_mode, lang=languages[0]),\n anticaptcha_manual_install=stealth_mode\n )\n logger.info(\"Browser initialized\")\n\n agents = [\n CasualAgent(\n name=config[\"MAIN\"][\"agent_name\"],\n prompt_path=f\"prompts/{personality_folder}/casual_agent.txt\",\n provider=provider, verbose=False\n ),\n CoderAgent(\n name=\"coder\",\n prompt_path=f\"prompts/{personality_folder}/coder_agent.txt\",\n provider=provider, verbose=False\n ),\n FileAgent(\n name=\"File Agent\",\n prompt_path=f\"prompts/{personality_folder}/file_agent.txt\",\n provider=provider, verbose=False\n ),\n BrowserAgent(\n name=\"Browser\",\n prompt_path=f\"prompts/{personality_folder}/browser_agent.txt\",\n provider=provider, verbose=False, browser=browser\n ),\n PlannerAgent(\n name=\"Planner\",\n prompt_path=f\"prompts/{personality_folder}/planner_agent.txt\",\n provider=provider, verbose=False, browser=browser\n )\n ]\n logger.info(\"Agents initialized\")\n\n interaction = Interaction(\n agents,\n tts_enabled=config.getboolean('MAIN', 'speak'),\n stt_enabled=config.getboolean('MAIN', 'listen'),\n recover_last_session=config.getboolean('MAIN', 'recover_last_session'),\n langs=languages\n )\n logger.info(\"Interaction initialized\")\n return interaction\n\ninteraction = initialize_system()\nis_generating = False\nquery_resp_history = []\n\n@api.get(\"/screenshot\")\nasync def get_screenshot():\n logger.info(\"Screenshot endpoint called\")\n screenshot_path = \".screenshots/updated_screen.png\"\n if os.path.exists(screenshot_path):\n return FileResponse(screenshot_path)\n logger.error(\"No screenshot available\")\n return JSONResponse(\n status_code=404,\n content={\"error\": \"No screenshot available\"}\n )\n\n@api.get(\"/health\")\nasync def health_check():\n logger.info(\"Health check endpoint called\")\n return {\"status\": \"healthy\", \"version\": \"0.1.0\"}\n\n@api.get(\"/is_active\")\nasync def is_active():\n logger.info(\"Is active endpoint called\")\n return {\"is_active\": interaction.is_active}\n\n@api.get(\"/stop\")\nasync def stop():\n logger.info(\"Stop endpoint called\")\n interaction.current_agent.request_stop()\n return JSONResponse(status_code=200, content={\"status\": \"stopped\"})\n\n@api.get(\"/latest_answer\")\nasync def get_latest_answer():\n global query_resp_history\n if interaction.current_agent is None:\n return JSONResponse(status_code=404, content={\"error\": \"No agent available\"})\n uid = str(uuid.uuid4())\n if not any(q[\"answer\"] == interaction.current_agent.last_answer for q in query_resp_history):\n query_resp = {\n \"done\": \"false\",\n \"answer\": interaction.current_agent.last_answer,\n \"reasoning\": interaction.current_agent.last_reasoning,\n \"agent_name\": interaction.current_agent.agent_name if interaction.current_agent else \"None\",\n \"success\": interaction.current_agent.success,\n \"blocks\": {f'{i}': block.jsonify() for i, block in enumerate(interaction.get_last_blocks_result())} if interaction.current_agent else {},\n \"status\": interaction.current_agent.get_status_message if interaction.current_agent else \"No status available\",\n \"uid\": uid\n }\n interaction.current_agent.last_answer = \"\"\n interaction.current_agent.last_reasoning = \"\"\n query_resp_history.append(query_resp)\n return JSONResponse(status_code=200, content=query_resp)\n if query_resp_history:\n return JSONResponse(status_code=200, content=query_resp_history[-1])\n return JSONResponse(status_code=404, content={\"error\": \"No answer available\"})\n\nasync def think_wrapper(interaction, query):\n try:\n interaction.last_query = query\n logger.info(\"Agents request is being processed\")\n success = await interaction.think()\n if not success:\n interaction.last_answer = \"Error: No answer from agent\"\n interaction.last_reasoning = \"Error: No reasoning from agent\"\n interaction.last_success = False\n else:\n interaction.last_success = True\n pretty_print(interaction.last_answer)\n interaction.speak_answer()\n return success\n except Exception as e:\n logger.error(f\"Error in think_wrapper: {str(e)}\")\n interaction.last_answer = f\"\"\n interaction.last_reasoning = f\"Error: {str(e)}\"\n interaction.last_success = False\n raise e\n\n@api.post(\"/query\", response_model=QueryResponse)\nasync def process_query(request: QueryRequest):\n global is_generating, query_resp_history\n logger.info(f\"Processing query: {request.query}\")\n query_resp = QueryResponse(\n done=\"false\",\n answer=\"\",\n reasoning=\"\",\n agent_name=\"Unknown\",\n success=\"false\",\n blocks={},\n status=\"Ready\",\n uid=str(uuid.uuid4())\n )\n if is_generating:\n logger.warning(\"Another query is being processed, please wait.\")\n return JSONResponse(status_code=429, content=query_resp.jsonify())\n\n try:\n is_generating = True\n success = await think_wrapper(interaction, request.query)\n is_generating = False\n\n if not success:\n query_resp.answer = interaction.last_answer\n query_resp.reasoning = interaction.last_reasoning\n return JSONResponse(status_code=400, content=query_resp.jsonify())\n\n if interaction.current_agent:\n blocks_json = {f'{i}': block.jsonify() for i, block in enumerate(interaction.current_agent.get_blocks_result())}\n else:\n logger.error(\"No current agent found\")\n blocks_json = {}\n query_resp.answer = \"Error: No current agent\"\n return JSONResponse(status_code=400, content=query_resp.jsonify())\n\n logger.info(f\"Answer: {interaction.last_answer}\")\n logger.info(f\"Blocks: {blocks_json}\")\n query_resp.done = \"true\"\n query_resp.answer = interaction.last_answer\n query_resp.reasoning = interaction.last_reasoning\n query_resp.agent_name = interaction.current_agent.agent_name\n query_resp.success = str(interaction.last_success)\n query_resp.blocks = blocks_json\n \n query_resp_dict = {\n \"done\": query_resp.done,\n \"answer\": query_resp.answer,\n \"agent_name\": query_resp.agent_name,\n \"success\": query_resp.success,\n \"blocks\": query_resp.blocks,\n \"status\": query_resp.status,\n \"uid\": query_resp.uid\n }\n query_resp_history.append(query_resp_dict)\n\n logger.info(\"Query processed successfully\")\n return JSONResponse(status_code=200, content=query_resp.jsonify())\n except Exception as e:\n logger.error(f\"An error occurred: {str(e)}\")\n sys.exit(1)\n finally:\n logger.info(\"Processing finished\")\n if config.getboolean('MAIN', 'save_session'):\n interaction.save_session()\n\nif __name__ == \"__main__\":\n # Print startup info\n if is_running_in_docker():\n print(\"[AgenticSeek] Starting in Docker container...\")\n else:\n print(\"[AgenticSeek] Starting on host machine...\")\n \n envport = os.getenv(\"BACKEND_PORT\")\n if envport:\n port = int(envport)\n else:\n port = 7777\n uvicorn.run(api, host=\"0.0.0.0\", port=7777)"], ["/agenticSeek/cli.py", "#!/usr/bin python3\n\nimport sys\nimport argparse\nimport configparser\nimport asyncio\n\nfrom sources.llm_provider import Provider\nfrom sources.interaction import Interaction\nfrom sources.agents import Agent, CoderAgent, CasualAgent, FileAgent, PlannerAgent, BrowserAgent, McpAgent\nfrom sources.browser import Browser, create_driver\nfrom sources.utility import pretty_print\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\nasync def main():\n pretty_print(\"Initializing...\", color=\"status\")\n stealth_mode = config.getboolean('BROWSER', 'stealth_mode')\n personality_folder = \"jarvis\" if config.getboolean('MAIN', 'jarvis_personality') else \"base\"\n languages = config[\"MAIN\"][\"languages\"].split(' ')\n\n provider = Provider(provider_name=config[\"MAIN\"][\"provider_name\"],\n model=config[\"MAIN\"][\"provider_model\"],\n server_address=config[\"MAIN\"][\"provider_server_address\"],\n is_local=config.getboolean('MAIN', 'is_local'))\n\n browser = Browser(\n create_driver(headless=config.getboolean('BROWSER', 'headless_browser'), stealth_mode=stealth_mode, lang=languages[0]),\n anticaptcha_manual_install=stealth_mode\n )\n\n agents = [\n CasualAgent(name=config[\"MAIN\"][\"agent_name\"],\n prompt_path=f\"prompts/{personality_folder}/casual_agent.txt\",\n provider=provider, verbose=False),\n CoderAgent(name=\"coder\",\n prompt_path=f\"prompts/{personality_folder}/coder_agent.txt\",\n provider=provider, verbose=False),\n FileAgent(name=\"File Agent\",\n prompt_path=f\"prompts/{personality_folder}/file_agent.txt\",\n provider=provider, verbose=False),\n BrowserAgent(name=\"Browser\",\n prompt_path=f\"prompts/{personality_folder}/browser_agent.txt\",\n provider=provider, verbose=False, browser=browser),\n PlannerAgent(name=\"Planner\",\n prompt_path=f\"prompts/{personality_folder}/planner_agent.txt\",\n provider=provider, verbose=False, browser=browser),\n #McpAgent(name=\"MCP Agent\",\n # prompt_path=f\"prompts/{personality_folder}/mcp_agent.txt\",\n # provider=provider, verbose=False), # NOTE under development\n ]\n\n interaction = Interaction(agents,\n tts_enabled=config.getboolean('MAIN', 'speak'),\n stt_enabled=config.getboolean('MAIN', 'listen'),\n recover_last_session=config.getboolean('MAIN', 'recover_last_session'),\n langs=languages\n )\n try:\n while interaction.is_active:\n interaction.get_user()\n if await interaction.think():\n interaction.show_answer()\n interaction.speak_answer()\n except Exception as e:\n if config.getboolean('MAIN', 'save_session'):\n interaction.save_session()\n raise e\n finally:\n if config.getboolean('MAIN', 'save_session'):\n interaction.save_session()\n\nif __name__ == \"__main__\":\n asyncio.run(main())"], ["/agenticSeek/sources/interaction.py", "import readline\nfrom typing import List, Tuple, Type, Dict\n\nfrom sources.text_to_speech import Speech\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.router import AgentRouter\nfrom sources.speech_to_text import AudioTranscriber, AudioRecorder\nimport threading\n\n\nclass Interaction:\n \"\"\"\n Interaction is a class that handles the interaction between the user and the agents.\n \"\"\"\n def __init__(self, agents,\n tts_enabled: bool = True,\n stt_enabled: bool = True,\n recover_last_session: bool = False,\n langs: List[str] = [\"en\", \"zh\"]\n ):\n self.is_active = True\n self.current_agent = None\n self.last_query = None\n self.last_answer = None\n self.last_reasoning = None\n self.agents = agents\n self.tts_enabled = tts_enabled\n self.stt_enabled = stt_enabled\n self.recover_last_session = recover_last_session\n self.router = AgentRouter(self.agents, supported_language=langs)\n self.ai_name = self.find_ai_name()\n self.speech = None\n self.transcriber = None\n self.recorder = None\n self.is_generating = False\n self.languages = langs\n if tts_enabled:\n self.initialize_tts()\n if stt_enabled:\n self.initialize_stt()\n if recover_last_session:\n self.load_last_session()\n self.emit_status()\n \n def get_spoken_language(self) -> str:\n \"\"\"Get the primary TTS language.\"\"\"\n lang = self.languages[0]\n return lang\n\n def initialize_tts(self):\n \"\"\"Initialize TTS.\"\"\"\n if not self.speech:\n animate_thinking(\"Initializing text-to-speech...\", color=\"status\")\n self.speech = Speech(enable=self.tts_enabled, language=self.get_spoken_language(), voice_idx=1)\n\n def initialize_stt(self):\n \"\"\"Initialize STT.\"\"\"\n if not self.transcriber or not self.recorder:\n animate_thinking(\"Initializing speech recognition...\", color=\"status\")\n self.transcriber = AudioTranscriber(self.ai_name, verbose=False)\n self.recorder = AudioRecorder()\n \n def emit_status(self):\n \"\"\"Print the current status of agenticSeek.\"\"\"\n if self.stt_enabled:\n pretty_print(f\"Text-to-speech trigger is {self.ai_name}\", color=\"status\")\n if self.tts_enabled:\n self.speech.speak(\"Hello, we are online and ready. What can I do for you ?\")\n pretty_print(\"AgenticSeek is ready.\", color=\"status\")\n \n def find_ai_name(self) -> str:\n \"\"\"Find the name of the default AI. It is required for STT as a trigger word.\"\"\"\n ai_name = \"jarvis\"\n for agent in self.agents:\n if agent.type == \"casual_agent\":\n ai_name = agent.agent_name\n break\n return ai_name\n \n def get_last_blocks_result(self) -> List[Dict]:\n \"\"\"Get the last blocks result.\"\"\"\n if self.current_agent is None:\n return []\n blks = []\n for agent in self.agents:\n blks.extend(agent.get_blocks_result())\n return blks\n \n def load_last_session(self):\n \"\"\"Recover the last session.\"\"\"\n for agent in self.agents:\n if agent.type == \"planner_agent\":\n continue\n agent.memory.load_memory(agent.type)\n \n def save_session(self):\n \"\"\"Save the current session.\"\"\"\n for agent in self.agents:\n agent.memory.save_memory(agent.type)\n\n def is_active(self) -> bool:\n return self.is_active\n \n def read_stdin(self) -> str:\n \"\"\"Read the input from the user.\"\"\"\n buffer = \"\"\n\n PROMPT = \"\\033[1;35m➤➤➤ \\033[0m\"\n while not buffer:\n try:\n buffer = input(PROMPT)\n except EOFError:\n return None\n if buffer == \"exit\" or buffer == \"goodbye\":\n return None\n return buffer\n \n def transcription_job(self) -> str:\n \"\"\"Transcribe the audio from the microphone.\"\"\"\n self.recorder = AudioRecorder(verbose=True)\n self.transcriber = AudioTranscriber(self.ai_name, verbose=True)\n self.transcriber.start()\n self.recorder.start()\n self.recorder.join()\n self.transcriber.join()\n query = self.transcriber.get_transcript()\n if query == \"exit\" or query == \"goodbye\":\n return None\n return query\n\n def get_user(self) -> str:\n \"\"\"Get the user input from the microphone or the keyboard.\"\"\"\n if self.stt_enabled:\n query = \"TTS transcription of user: \" + self.transcription_job()\n else:\n query = self.read_stdin()\n if query is None:\n self.is_active = False\n self.last_query = None\n return None\n self.last_query = query\n return query\n \n def set_query(self, query: str) -> None:\n \"\"\"Set the query\"\"\"\n self.is_active = True\n self.last_query = query\n \n async def think(self) -> bool:\n \"\"\"Request AI agents to process the user input.\"\"\"\n push_last_agent_memory = False\n if self.last_query is None or len(self.last_query) == 0:\n return False\n agent = self.router.select_agent(self.last_query)\n if agent is None:\n return False\n if self.current_agent != agent and self.last_answer is not None:\n push_last_agent_memory = True\n tmp = self.last_answer\n self.current_agent = agent\n self.is_generating = True\n self.last_answer, self.last_reasoning = await agent.process(self.last_query, self.speech)\n self.is_generating = False\n if push_last_agent_memory:\n self.current_agent.memory.push('user', self.last_query)\n self.current_agent.memory.push('assistant', self.last_answer)\n if self.last_answer == tmp:\n self.last_answer = None\n return True\n \n def get_updated_process_answer(self) -> str:\n \"\"\"Get the answer from the last agent.\"\"\"\n if self.current_agent is None:\n return None\n return self.current_agent.get_last_answer()\n \n def get_updated_block_answer(self) -> str:\n \"\"\"Get the answer from the last agent.\"\"\"\n if self.current_agent is None:\n return None\n return self.current_agent.get_last_block_answer()\n \n def speak_answer(self) -> None:\n \"\"\"Speak the answer to the user in a non-blocking thread.\"\"\"\n if self.last_query is None:\n return\n if self.tts_enabled and self.last_answer and self.speech:\n def speak_in_thread(speech_instance, text):\n speech_instance.speak(text)\n thread = threading.Thread(target=speak_in_thread, args=(self.speech, self.last_answer))\n thread.start()\n \n def show_answer(self) -> None:\n \"\"\"Show the answer to the user.\"\"\"\n if self.last_query is None:\n return\n if self.current_agent is not None:\n self.current_agent.show_answer()\n\n"], ["/agenticSeek/sources/memory.py", "import time\nimport datetime\nimport uuid\nimport os\nimport sys\nimport json\nfrom typing import List, Tuple, Type, Dict\nimport torch\nfrom transformers import AutoTokenizer, AutoModelForSeq2SeqLM\nimport configparser\n\nfrom sources.utility import timer_decorator, pretty_print, animate_thinking\nfrom sources.logger import Logger\n\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\nclass Memory():\n \"\"\"\n Memory is a class for managing the conversation memory\n It provides a method to compress the memory using summarization model.\n \"\"\"\n def __init__(self, system_prompt: str,\n recover_last_session: bool = False,\n memory_compression: bool = True,\n model_provider: str = \"deepseek-r1:14b\"):\n self.memory = [{'role': 'system', 'content': system_prompt}]\n \n self.logger = Logger(\"memory.log\")\n self.session_time = datetime.datetime.now()\n self.session_id = str(uuid.uuid4())\n self.conversation_folder = f\"conversations/\"\n self.session_recovered = False\n if recover_last_session:\n self.load_memory()\n self.session_recovered = True\n # memory compression system\n self.model = None\n self.tokenizer = None\n self.device = self.get_cuda_device()\n self.memory_compression = memory_compression\n self.model_provider = model_provider\n if self.memory_compression:\n self.download_model()\n\n def get_ideal_ctx(self, model_name: str) -> int | None:\n \"\"\"\n Estimate context size based on the model name.\n EXPERIMENTAL for memory compression\n \"\"\"\n import re\n import math\n\n def extract_number_before_b(sentence: str) -> int:\n match = re.search(r'(\\d+)b', sentence, re.IGNORECASE)\n return int(match.group(1)) if match else None\n\n model_size = extract_number_before_b(model_name)\n if not model_size:\n return None\n base_size = 7 # Base model size in billions\n base_context = 4096 # Base context size in tokens\n scaling_factor = 1.5 # Approximate scaling factor for context size growth\n context_size = int(base_context * (model_size / base_size) ** scaling_factor)\n context_size = 2 ** round(math.log2(context_size))\n self.logger.info(f\"Estimated context size for {model_name}: {context_size} tokens.\")\n return context_size\n \n def download_model(self):\n \"\"\"Download the model if not already downloaded.\"\"\"\n animate_thinking(\"Loading memory compression model...\", color=\"status\")\n self.tokenizer = AutoTokenizer.from_pretrained(\"pszemraj/led-base-book-summary\")\n self.model = AutoModelForSeq2SeqLM.from_pretrained(\"pszemraj/led-base-book-summary\")\n self.logger.info(\"Memory compression system initialized.\")\n \n def get_filename(self) -> str:\n \"\"\"Get the filename for the save file.\"\"\"\n return f\"memory_{self.session_time.strftime('%Y-%m-%d_%H-%M-%S')}.txt\"\n \n def save_memory(self, agent_type: str = \"casual_agent\") -> None:\n \"\"\"Save the session memory to a file.\"\"\"\n if not os.path.exists(self.conversation_folder):\n self.logger.info(f\"Created folder {self.conversation_folder}.\")\n os.makedirs(self.conversation_folder)\n save_path = os.path.join(self.conversation_folder, agent_type)\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n filename = self.get_filename()\n path = os.path.join(save_path, filename)\n json_memory = json.dumps(self.memory)\n with open(path, 'w') as f:\n self.logger.info(f\"Saved memory json at {path}\")\n f.write(json_memory)\n \n def find_last_session_path(self, path) -> str:\n \"\"\"Find the last session path.\"\"\"\n saved_sessions = []\n for filename in os.listdir(path):\n if filename.startswith('memory_'):\n date = filename.split('_')[1]\n saved_sessions.append((filename, date))\n saved_sessions.sort(key=lambda x: x[1], reverse=True)\n if len(saved_sessions) > 0:\n self.logger.info(f\"Last session found at {saved_sessions[0][0]}\")\n return saved_sessions[0][0]\n return None\n \n def save_json_file(self, path: str, json_memory: dict) -> None:\n \"\"\"Save a JSON file.\"\"\"\n try:\n with open(path, 'w') as f:\n json.dump(json_memory, f)\n self.logger.info(f\"Saved memory json at {path}\")\n except Exception as e:\n self.logger.warning(f\"Error saving file {path}: {e}\")\n \n def load_json_file(self, path: str) -> dict:\n \"\"\"Load a JSON file.\"\"\"\n json_memory = {}\n try:\n with open(path, 'r') as f:\n json_memory = json.load(f)\n except FileNotFoundError:\n self.logger.warning(f\"File not found: {path}\")\n return {}\n except json.JSONDecodeError:\n self.logger.warning(f\"Error decoding JSON from file: {path}\")\n return {}\n except Exception as e:\n self.logger.warning(f\"Error loading file {path}: {e}\")\n return {}\n return json_memory\n\n def load_memory(self, agent_type: str = \"casual_agent\") -> None:\n \"\"\"Load the memory from the last session.\"\"\"\n if self.session_recovered == True:\n return\n pretty_print(f\"Loading {agent_type} past memories... \", color=\"status\")\n save_path = os.path.join(self.conversation_folder, agent_type)\n if not os.path.exists(save_path):\n pretty_print(\"No memory to load.\", color=\"success\")\n return\n filename = self.find_last_session_path(save_path)\n if filename is None:\n pretty_print(\"Last session memory not found.\", color=\"warning\")\n return\n path = os.path.join(save_path, filename)\n self.memory = self.load_json_file(path) \n if self.memory[-1]['role'] == 'user':\n self.memory.pop()\n self.compress()\n pretty_print(\"Session recovered successfully\", color=\"success\")\n \n def reset(self, memory: list = []) -> None:\n self.logger.info(\"Memory reset performed.\")\n self.memory = memory\n \n def push(self, role: str, content: str) -> int:\n \"\"\"Push a message to the memory.\"\"\"\n ideal_ctx = self.get_ideal_ctx(self.model_provider)\n if ideal_ctx is not None:\n if self.memory_compression and len(content) > ideal_ctx * 1.5:\n self.logger.info(f\"Compressing memory: Content {len(content)} > {ideal_ctx} model context.\")\n self.compress()\n curr_idx = len(self.memory)\n if self.memory[curr_idx-1]['content'] == content:\n pretty_print(\"Warning: same message have been pushed twice to memory\", color=\"error\")\n time_str = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n if config[\"MAIN\"][\"provider_name\"] == \"openrouter\":\n self.memory.append({'role': role, 'content': content})\n else:\n self.memory.append({'role': role, 'content': content, 'time': time_str, 'model_used': self.model_provider})\n return curr_idx-1\n \n def clear(self) -> None:\n \"\"\"Clear all memory except system prompt\"\"\"\n self.logger.info(\"Memory clear performed.\")\n self.memory = self.memory[:1]\n \n def clear_section(self, start: int, end: int) -> None:\n \"\"\"\n Clear a section of the memory. Ignore system message index.\n Args:\n start (int): Starting bound of the section to clear.\n end (int): Ending bound of the section to clear.\n \"\"\"\n self.logger.info(f\"Clearing memory section {start} to {end}.\")\n start = max(0, start) + 1\n end = min(end, len(self.memory)-1) + 2\n self.memory = self.memory[:start] + self.memory[end:]\n \n def get(self) -> list:\n return self.memory\n\n def get_cuda_device(self) -> str:\n if torch.backends.mps.is_available():\n return \"mps\"\n elif torch.cuda.is_available():\n return \"cuda\"\n else:\n return \"cpu\"\n\n def summarize(self, text: str, min_length: int = 64) -> str:\n \"\"\"\n Summarize the text using the AI model.\n Args:\n text (str): The text to summarize\n min_length (int, optional): The minimum length of the summary. Defaults to 64.\n Returns:\n str: The summarized text\n \"\"\"\n if self.tokenizer is None or self.model is None:\n self.logger.warning(\"No tokenizer or model to perform summarization.\")\n return text\n if len(text) < min_length*1.5:\n return text\n max_length = len(text) // 2 if len(text) > min_length*2 else min_length*2\n input_text = \"summarize: \" + text\n inputs = self.tokenizer(input_text, return_tensors=\"pt\", max_length=512, truncation=True)\n summary_ids = self.model.generate(\n inputs['input_ids'],\n max_length=max_length,\n min_length=min_length,\n length_penalty=1.0,\n num_beams=4,\n early_stopping=True\n )\n summary = self.tokenizer.decode(summary_ids[0], skip_special_tokens=True)\n summary.replace('summary:', '')\n self.logger.info(f\"Memory summarized from len {len(text)} to {len(summary)}.\")\n self.logger.info(f\"Summarized text:\\n{summary}\")\n return summary\n \n #@timer_decorator\n def compress(self) -> str:\n \"\"\"\n Compress (summarize) the memory using the model.\n \"\"\"\n if self.tokenizer is None or self.model is None:\n self.logger.warning(\"No tokenizer or model to perform memory compression.\")\n return\n for i in range(len(self.memory)):\n if self.memory[i]['role'] == 'system':\n continue\n if len(self.memory[i]['content']) > 1024:\n self.memory[i]['content'] = self.summarize(self.memory[i]['content'])\n \n def trim_text_to_max_ctx(self, text: str) -> str:\n \"\"\"\n Truncate a text to fit within the maximum context size of the model.\n \"\"\"\n ideal_ctx = self.get_ideal_ctx(self.model_provider)\n return text[:ideal_ctx] if ideal_ctx is not None else text\n \n #@timer_decorator\n def compress_text_to_max_ctx(self, text) -> str:\n \"\"\"\n Compress a text to fit within the maximum context size of the model.\n \"\"\"\n if self.tokenizer is None or self.model is None:\n self.logger.warning(\"No tokenizer or model to perform memory compression.\")\n return text\n ideal_ctx = self.get_ideal_ctx(self.model_provider)\n if ideal_ctx is None:\n self.logger.warning(\"No ideal context size found.\")\n return text\n while len(text) > ideal_ctx:\n self.logger.info(f\"Compressing text: {len(text)} > {ideal_ctx} model context.\")\n text = self.summarize(text)\n return text\n\nif __name__ == \"__main__\":\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n memory = Memory(\"You are a helpful assistant.\",\n recover_last_session=False, memory_compression=True)\n\n memory.push('user', \"hello\")\n memory.push('assistant', \"how can i help you?\")\n memory.push('user', \"why do i get this cuda error?\")\n sample_text = \"\"\"\nThe error you're encountering:\ncuda.cu:52:10: fatal error: helper_functions.h: No such file or directory\n #include \nindicates that the compiler cannot find the helper_functions.h file. This is because the #include directive is looking for the file in the system's include paths, but the file is either not in those paths or is located in a different directory.\n1. Use #include \"helper_functions.h\" Instead of #include \nAngle brackets (< >) are used for system or standard library headers.\nQuotes (\" \") are used for local or project-specific headers.\nIf helper_functions.h is in the same directory as cuda.cu, change the include directive to:\n3. Verify the File Exists\nDouble-check that helper_functions.h exists in the specified location. If the file is missing, you'll need to obtain or recreate it.\n4. Use the Correct CUDA Samples Path (if applicable)\nIf helper_functions.h is part of the CUDA Samples, ensure you have the CUDA Samples installed and include the correct path. For example, on Linux, the CUDA Samples are typically located in /usr/local/cuda/samples/common/inc. You can include this path like so:\nUse #include \"helper_functions.h\" for local files.\nUse the -I flag to specify the directory containing helper_functions.h.\nEnsure the file exists in the specified location.\n \"\"\"\n memory.push('assistant', sample_text)\n \n print(\"\\n---\\nmemory before:\", memory.get())\n memory.compress()\n print(\"\\n---\\nmemory after:\", memory.get())\n #memory.save_memory()\n "], ["/agenticSeek/sources/router.py", "import os\nimport sys\nimport torch\nimport random\nfrom typing import List, Tuple, Type, Dict\n\nfrom transformers import pipeline\nfrom adaptive_classifier import AdaptiveClassifier\n\nfrom sources.agents.agent import Agent\nfrom sources.agents.code_agent import CoderAgent\nfrom sources.agents.casual_agent import CasualAgent\nfrom sources.agents.planner_agent import FileAgent\nfrom sources.agents.browser_agent import BrowserAgent\nfrom sources.language import LanguageUtility\nfrom sources.utility import pretty_print, animate_thinking, timer_decorator\nfrom sources.logger import Logger\n\nclass AgentRouter:\n \"\"\"\n AgentRouter is a class that selects the appropriate agent based on the user query.\n \"\"\"\n def __init__(self, agents: list, supported_language: List[str] = [\"en\", \"fr\", \"zh\"]):\n self.agents = agents\n self.logger = Logger(\"router.log\")\n self.lang_analysis = LanguageUtility(supported_language=supported_language)\n self.pipelines = self.load_pipelines()\n self.talk_classifier = self.load_llm_router()\n self.complexity_classifier = self.load_llm_router()\n self.learn_few_shots_tasks()\n self.learn_few_shots_complexity()\n self.asked_clarify = False\n \n def load_pipelines(self) -> Dict[str, Type[pipeline]]:\n \"\"\"\n Load the pipelines for the text classification used for routing.\n returns:\n Dict[str, Type[pipeline]]: The loaded pipelines\n \"\"\"\n animate_thinking(\"Loading zero-shot pipeline...\", color=\"status\")\n return {\n \"bart\": pipeline(\"zero-shot-classification\", model=\"facebook/bart-large-mnli\")\n }\n\n def load_llm_router(self) -> AdaptiveClassifier:\n \"\"\"\n Load the LLM router model.\n returns:\n AdaptiveClassifier: The loaded model\n exceptions:\n Exception: If the safetensors fails to load\n \"\"\"\n path = \"../llm_router\" if __name__ == \"__main__\" else \"./llm_router\"\n try:\n animate_thinking(\"Loading LLM router model...\", color=\"status\")\n talk_classifier = AdaptiveClassifier.from_pretrained(path)\n except Exception as e:\n raise Exception(\"Failed to load the routing model. Please run the dl_safetensors.sh script inside llm_router/ directory to download the model.\")\n return talk_classifier\n\n def get_device(self) -> str:\n if torch.backends.mps.is_available():\n return \"mps\"\n elif torch.cuda.is_available():\n return \"cuda:0\"\n else:\n return \"cpu\"\n \n def learn_few_shots_complexity(self) -> None:\n \"\"\"\n Few shot learning for complexity estimation.\n Use the build in add_examples method of the Adaptive_classifier.\n \"\"\"\n few_shots = [\n (\"hi\", \"LOW\"),\n (\"How it's going ?\", \"LOW\"),\n (\"What’s the weather like today?\", \"LOW\"),\n (\"Can you find a file named ‘notes.txt’ in my Documents folder?\", \"LOW\"),\n (\"Write a Python script to generate a random password\", \"LOW\"),\n (\"Debug this JavaScript code that’s not running properly\", \"LOW\"),\n (\"Search the web for the cheapest laptop under $500\", \"LOW\"),\n (\"Locate a file called ‘report_2024.pdf’ on my drive\", \"LOW\"),\n (\"Check if a folder named ‘Backups’ exists on my system\", \"LOW\"),\n (\"Can you find ‘family_vacation.mp4’ in my Videos folder?\", \"LOW\"),\n (\"Search my drive for a file named ‘todo_list.xlsx’\", \"LOW\"),\n (\"Write a Python function to check if a string is a palindrome\", \"LOW\"),\n (\"Can you search the web for startups in Berlin?\", \"LOW\"),\n (\"Find recent articles on blockchain technology online\", \"LOW\"),\n (\"Check if ‘Personal_Projects’ folder exists on my desktop\", \"LOW\"),\n (\"Create a bash script to list all running processes\", \"LOW\"),\n (\"Debug this Python script that’s crashing on line 10\", \"LOW\"),\n (\"Browse the web to find out who invented Python\", \"LOW\"),\n (\"Locate a file named ‘shopping_list.txt’ on my system\", \"LOW\"),\n (\"Search the web for tips on staying productive\", \"LOW\"),\n (\"Find ‘sales_pitch.pptx’ in my Downloads folder\", \"LOW\"),\n (\"can you find a file called resume.docx on my drive?\", \"LOW\"),\n (\"can you write a python script to check if the device on my network is connected to the internet\", \"LOW\"),\n (\"can you debug this Java code? It’s not working.\", \"LOW\"),\n (\"can you find the old_project.zip file somewhere on my drive?\", \"LOW\"),\n (\"can you locate the backup folder I created last month on my system?\", \"LOW\"),\n (\"could you check if the presentation.pdf file exists in my downloads?\", \"LOW\"),\n (\"search my drive for a file called vacation_photos_2023.jpg.\", \"LOW\"),\n (\"help me organize my desktop files into folders by type.\", \"LOW\"),\n (\"make a blackjack in golang\", \"LOW\"),\n (\"write a python script to ping a website\", \"LOW\"),\n (\"write a simple Java program to print 'Hello World'\", \"LOW\"),\n (\"write a Java program to calculate the area of a circle\", \"LOW\"),\n (\"write a Python function to sort a list of dictionaries by key\", \"LOW\"),\n (\"can you search for startup in tokyo?\", \"LOW\"),\n (\"find the latest updates on quantum computing on the web\", \"LOW\"),\n (\"check if the folder ‘Work_Projects’ exists on my desktop\", \"LOW\"),\n (\" can you browse the web, use overpass-turbo to show fountains in toulouse\", \"LOW\"),\n (\"search the web for the best budget smartphones of 2025\", \"LOW\"),\n (\"write a Python script to download all images from a webpage\", \"LOW\"),\n (\"create a bash script to monitor CPU usage\", \"LOW\"),\n (\"debug this C++ code that keeps crashing\", \"LOW\"),\n (\"can you browse the web to find out who fosowl is ?\", \"LOW\"),\n (\"find the file ‘important_notes.txt’\", \"LOW\"),\n (\"search the web for the best ways to learn a new language\", \"LOW\"),\n (\"locate the file ‘presentation.pptx’ in my Documents folder\", \"LOW\"),\n (\"Make a 3d game in javascript using three.js\", \"LOW\"),\n (\"Find the latest research papers on AI and build save in a file\", \"HIGH\"),\n (\"Make a web server in go that serve a simple html page\", \"LOW\"),\n (\"Search the web for the cheapest 4K monitor and provide a link\", \"LOW\"),\n (\"Write a JavaScript function to reverse a string\", \"LOW\"),\n (\"Can you locate a file called ‘budget_2025.xlsx’ on my system?\", \"LOW\"),\n (\"Search the web for recent articles on space exploration\", \"LOW\"),\n (\"when is the exam period for master student in france?\", \"LOW\"),\n (\"Check if a folder named ‘Photos_2024’ exists on my desktop\", \"LOW\"),\n (\"Can you look up some nice knitting patterns on that web thingy?\", \"LOW\"),\n (\"Goodness, check if my ‘Photos_Grandkids’ folder is still on the desktop\", \"LOW\"),\n (\"Create a Python script to rename all files in a folder based on their creation date\", \"LOW\"),\n (\"Can you find a file named ‘meeting_notes.txt’ in my Downloads folder?\", \"LOW\"),\n (\"Write a Go program to check if a port is open on a network\", \"LOW\"),\n (\"Search the web for the latest electric car reviews\", \"LOW\"),\n (\"Write a Python function to merge two sorted lists\", \"LOW\"),\n (\"Create a bash script to monitor disk space and alert via text file\", \"LOW\"),\n (\"What’s out there on the web about cheap travel spots?\", \"LOW\"),\n (\"Search X for posts about AI ethics and summarize them\", \"LOW\"),\n (\"Check if a file named ‘project_proposal.pdf’ exists in my Documents\", \"LOW\"),\n (\"Search the web for tips on improving coding skills\", \"LOW\"),\n (\"Write a Python script to count words in a text file\", \"LOW\"),\n (\"Search the web for restaurant\", \"LOW\"),\n (\"Use a MCP to find the latest stock market data\", \"LOW\"),\n (\"Use a MCP to send an email to my boss\", \"LOW\"),\n (\"Could you use a MCP to find the latest news on climate change?\", \"LOW\"),\n (\"Create a simple HTML page with CSS styling\", \"LOW\"),\n (\"Use file.txt and then use it to ...\", \"HIGH\"),\n (\"Yo, what’s good? Find my ‘mixtape.mp3’ real quick\", \"LOW\"),\n (\"Can you follow the readme and install the project\", \"HIGH\"),\n (\"Man, write me a dope Python script to flex some random numbers\", \"LOW\"),\n (\"Search the web for peer-reviewed articles on gene editing\", \"LOW\"),\n (\"Locate ‘meeting_notes.docx’ in Downloads, I’m late for this call\", \"LOW\"),\n (\"Make the game less hard\", \"LOW\"),\n (\"Why did it fail?\", \"LOW\"),\n (\"Write a Python script to list all .pdf files in my Documents\", \"LOW\"),\n (\"Write a Python thing to sort my .jpg files by date\", \"LOW\"),\n (\"make a snake game please\", \"LOW\"),\n (\"Find ‘gallery_list.pdf’, then build a web app to show my pics\", \"HIGH\"),\n (\"Find ‘budget_2025.xlsx’, analyze it, and make a chart for my boss\", \"HIGH\"),\n (\"I want you to make me a plan to travel to Tainan\", \"HIGH\"),\n (\"Retrieve the latest publications on CRISPR and develop a web application to display them\", \"HIGH\"),\n (\"Bro dig up a music API and build me a tight app for the hottest tracks\", \"HIGH\"),\n (\"Find a public API for sports scores and build a web app to show live updates\", \"HIGH\"),\n (\"Find a public API for book data and create a Flask app to list bestsellers\", \"HIGH\"),\n (\"Organize my desktop files by extension and then write a script to list them\", \"HIGH\"),\n (\"Find the latest research on renewable energy and build a web app to display it\", \"HIGH\"),\n (\"search online for popular sci-fi movies from 2024 and pick three to watch tonight. Save the list in movie_night.txt\", \"HIGH\"),\n (\"can you find vitess repo, clone it and install by following the readme\", \"HIGH\"),\n (\"Create a JavaScript game using Phaser.js with multiple levels\", \"HIGH\"),\n (\"Search the web for the latest trends in web development and build a sample site\", \"HIGH\"),\n (\"Use my research_note.txt file, double check the informations on the web\", \"HIGH\"),\n (\"Make a web server in go that query a flight API and display them in a app\", \"HIGH\"),\n (\"Search the web for top cafes in Rennes, France, and save a list of three with their addresses in rennes_cafes.txt.\", \"HIGH\"),\n (\"Search the web for the latest trends in AI and demo it in pytorch\", \"HIGH\"),\n (\"can you lookup for api that track flight and build a web flight tracking app\", \"HIGH\"),\n (\"Find the file toto.pdf then use its content to reply to Jojo on superforum.com\", \"HIGH\"),\n (\"Create a whole web app in python using the flask framework that query news API\", \"HIGH\"),\n (\"Create a bash script that monitor the CPU usage and send an email if it's too high\", \"HIGH\"),\n (\"Make a web search for latest news on the stock market and display them with python\", \"HIGH\"),\n (\"Find my resume file, apply to job that might fit online\", \"HIGH\"),\n (\"Can you find a weather API and build a Python app to display current weather\", \"HIGH\"),\n (\"Create a Python web app using Flask to track cryptocurrency prices from an API\", \"HIGH\"),\n (\"Search the web for tutorials on machine learning and build a simple ML model in Python\", \"HIGH\"),\n (\"Find a public API for movie data and build a web app to display movie ratings\", \"HIGH\"),\n (\"Create a Node.js server that queries a public API for traffic data and displays it\", \"HIGH\"),\n (\"can you find api and build a python web app with it ?\", \"HIGH\"),\n (\"do a deep search of current AI player for 2025 and make me a report in a file\", \"HIGH\"),\n (\"Find a public API for recipe data and build a web app to display recipes\", \"HIGH\"),\n (\"Search the web for recent space mission updates and build a Flask app\", \"HIGH\"),\n (\"Create a Python script to scrape a website and save data to a database\", \"HIGH\"),\n (\"Find a shakespear txt then train a transformers on it to generate text\", \"HIGH\"),\n (\"Find a public API for fitness tracking and build a web app to show stats\", \"HIGH\"),\n (\"Search the web for tutorials on web development and build a sample site\", \"HIGH\"),\n (\"Create a Node.js app to query a public API for event listings and display them\", \"HIGH\"),\n (\"Find a file named ‘budget.xlsx’, analyze its data, and generate a chart\", \"HIGH\"),\n ]\n random.shuffle(few_shots)\n texts = [text for text, _ in few_shots]\n labels = [label for _, label in few_shots]\n self.complexity_classifier.add_examples(texts, labels)\n\n def learn_few_shots_tasks(self) -> None:\n \"\"\"\n Few shot learning for tasks classification.\n Use the build in add_examples method of the Adaptive_classifier.\n \"\"\"\n few_shots = [\n (\"Write a python script to check if the device on my network is connected to the internet\", \"coding\"),\n (\"Hey could you search the web for the latest news on the tesla stock market ?\", \"web\"),\n (\"I would like you to search for weather api\", \"web\"),\n (\"Plan a 3-day trip to New York, including flights and hotels.\", \"web\"),\n (\"Find on the web the latest research papers on AI.\", \"web\"),\n (\"Can you debug this Java code? It’s not working.\", \"code\"),\n (\"Can you browse the web and find me a 4090 for cheap?\", \"web\"),\n (\"i would like to setup a new AI project, index as mark2\", \"files\"),\n (\"Hey, can you find the old_project.zip file somewhere on my drive?\", \"files\"),\n (\"Tell me a funny story\", \"talk\"),\n (\"can you make a snake game in python\", \"code\"),\n (\"Can you locate the backup folder I created last month on my system?\", \"files\"),\n (\"Share a random fun fact about space.\", \"talk\"),\n (\"Write a script to rename all files in a directory to lowercase.\", \"files\"),\n (\"Could you check if the presentation.pdf file exists in my downloads?\", \"files\"),\n (\"Tell me about the weirdest dream you’ve ever heard of.\", \"talk\"),\n (\"Search my drive for a file called vacation_photos_2023.jpg.\", \"files\"),\n (\"Help me organize my desktop files into folders by type.\", \"files\"),\n (\"What’s your favorite movie and why?\", \"talk\"),\n (\"what directory are you in ?\", \"files\"),\n (\"what files you seing rn ?\", \"files\"),\n (\"When is the period of university exam in france ?\", \"web\"),\n (\"Search my drive for a file named budget_2024.xlsx\", \"files\"),\n (\"Write a Python function to sort a list of dictionaries by key\", \"code\"),\n (\"Find the latest updates on quantum computing on the web\", \"web\"),\n (\"Check if the folder ‘Work_Projects’ exists on my desktop\", \"files\"),\n (\"Create a bash script to monitor CPU usage\", \"code\"),\n (\"Search online for the best budget smartphones of 2025\", \"web\"),\n (\"What’s the strangest food combination you’ve heard of?\", \"talk\"),\n (\"Move all .txt files from Downloads to a new folder called Notes\", \"files\"),\n (\"Debug this C++ code that keeps crashing\", \"code\"),\n (\"can you browse the web to find out who fosowl is ?\", \"web\"),\n (\"Find the file ‘important_notes.txt’\", \"files\"),\n (\"Find out the latest news on the upcoming Mars mission\", \"web\"),\n (\"Write a Java program to calculate the area of a circle\", \"code\"),\n (\"Search the web for the best ways to learn a new language\", \"web\"),\n (\"Locate the file ‘presentation.pptx’ in my Documents folder\", \"files\"),\n (\"Write a Python script to download all images from a webpage\", \"code\"),\n (\"Search the web for the latest trends in AI and machine learning\", \"web\"),\n (\"Tell me about a time when you had to solve a difficult problem\", \"talk\"),\n (\"Organize all image files on my desktop into a folder called ‘Pictures’\", \"files\"),\n (\"Generate a Ruby script to calculate Fibonacci numbers up to 100\", \"code\"),\n (\"Find out what device are connected to my network\", \"code\"),\n (\"Show me how much disk space is left on my drive\", \"code\"),\n (\"Look up recent posts on X about climate change\", \"web\"),\n (\"Find the photo I took last week named sunset_beach.jpg\", \"files\"),\n (\"Write a JavaScript snippet to fetch data from an API\", \"code\"),\n (\"Search the web for tutorials on machine learning with Python\", \"web\"),\n (\"Locate the file ‘meeting_notes.docx’ in my Documents folder\", \"files\"),\n (\"Write a Python script to scrape a website’s title and links\", \"code\"),\n (\"Search the web for the latest breakthroughs in fusion energy\", \"web\"),\n (\"Tell me about a historical event that sounds too wild to be true\", \"talk\"),\n (\"Organize all image files on my desktop into a folder called ‘Pictures’\", \"files\"),\n (\"Generate a Ruby script to calculate Fibonacci numbers up to 100\", \"code\"),\n (\"Find recent X posts about SpaceX’s next rocket launch\", \"web\"),\n (\"What’s the funniest misunderstanding you’ve seen between humans and AI?\", \"talk\"),\n (\"Check if ‘backup_032025.zip’ exists anywhere on my drive\", \"files\" ),\n (\"Create a shell script to automate backups of a directory\", \"code\"),\n (\"Look up the top AI conferences happening in 2025 online\", \"web\"),\n (\"Write a C# program to simulate a basic calculator\", \"code\"),\n (\"Browse the web for open-source alternatives to Photoshop\", \"web\"),\n (\"Hey how are you\", \"talk\"),\n (\"Write a Python script to ping a website\", \"code\"),\n (\"Search the web for the latest iPhone release\", \"web\"),\n (\"What’s the weather like today?\", \"web\"),\n (\"Hi, how’s your day going?\", \"talk\"),\n (\"Can you find a file called resume.docx on my drive?\", \"files\"),\n (\"Write a simple Java program to print 'Hello World'\", \"code\"),\n (\"can you find the current stock of Tesla?\", \"web\"),\n (\"Tell me a quick joke\", \"talk\"),\n (\"Search online for the best coffee shops in Seattle\", \"web\"),\n (\"Check if ‘project_plan.pdf’ exists in my Downloads folder\", \"files\"),\n (\"What’s your favorite color?\", \"talk\"),\n (\"Write a bash script to list all files in a directory\", \"code\"),\n (\"Find recent X posts about electric cars\", \"web\"),\n (\"Hey, you doing okay?\", \"talk\"),\n (\"Locate the file ‘family_photo.jpg’ on my system\", \"files\"),\n (\"Search the web for beginner guitar lessons\", \"web\"),\n (\"Write a Python function to reverse a string\", \"code\"),\n (\"What’s the weirdest animal you know of?\", \"talk\"),\n (\"Organize all .pdf files on my desktop into a ‘Documents’ folder\", \"files\"),\n (\"Browse the web for the latest space mission updates\", \"web\"),\n (\"Hey, what’s up with you today?\", \"talk\"),\n (\"Write a JavaScript function to add two numbers\", \"code\"),\n (\"Find the file ‘notes.txt’ in my Documents folder\", \"files\"),\n (\"Tell me something random about the ocean\", \"talk\"),\n (\"Search the web for cheap flights to Paris\", \"web\"),\n (\"Check if ‘budget.xlsx’ is on my drive\", \"files\"),\n (\"Write a Python script to count words in a text file\", \"code\"),\n (\"How’s it going today?\", \"talk\"),\n (\"Find recent X posts about AI advancements\", \"web\"),\n (\"Move all .jpg files from Downloads to a ‘Photos’ folder\", \"files\"),\n (\"Search online for the best laptops of 2025\", \"web\"),\n (\"What’s the funniest thing you’ve heard lately?\", \"talk\"),\n (\"Write a Ruby script to generate random numbers\", \"code\"),\n (\"Hey, how’s everything with you?\", \"talk\"),\n (\"Locate ‘meeting_agenda.docx’ in my system\", \"files\"),\n (\"Search the web for tips on growing indoor plants\", \"web\"),\n (\"Write a C++ program to calculate the sum of an array\", \"code\"),\n (\"Tell me a fun fact about dogs\", \"talk\"),\n (\"Check if the folder ‘Old_Projects’ exists on my desktop\", \"files\"),\n (\"Browse the web for the latest gaming console reviews\", \"web\"),\n (\"Hi, how are you feeling today?\", \"talk\"),\n (\"Write a Python script to check disk space\", \"code\"),\n (\"Find the file ‘vacation_itinerary.pdf’ on my drive\", \"files\"),\n (\"Search the web for news on renewable energy\", \"web\"),\n (\"What’s the strangest thing you’ve learned recently?\", \"talk\"),\n (\"Organize all video files into a ‘Videos’ folder\", \"files\"),\n (\"Write a shell script to delete temporary files\", \"code\"),\n (\"Hey, how’s your week been so far?\", \"talk\"),\n (\"Search online for the top movies of 2025\", \"web\"),\n (\"Locate ‘taxes_2024.xlsx’ in my Documents folder\", \"files\"),\n (\"Tell me about a cool invention from history\", \"talk\"),\n (\"Write a Java program to check if a number is even or odd\", \"code\"),\n (\"Find recent X posts about cryptocurrency trends\", \"web\"),\n (\"Hey, you good today?\", \"talk\"),\n (\"Search the web for easy dinner recipes\", \"web\"),\n (\"Check if ‘photo_backup.zip’ exists on my drive\", \"files\"),\n (\"Write a Python script to rename files with a timestamp\", \"code\"),\n (\"What’s your favorite thing about space?\", \"talk\"),\n (\"search for GPU with at least 24gb vram\", \"web\"),\n (\"Browse the web for the latest fitness trends\", \"web\"),\n (\"Move all .docx files to a ‘Work’ folder\", \"files\"),\n (\"I would like to make a new project called 'new_project'\", \"files\"),\n (\"I would like to setup a new project index as mark2\", \"files\"),\n (\"can you create a 3d js game that run in the browser\", \"code\"),\n (\"can you make a web app in python that use the flask framework\", \"code\"),\n (\"can you build a web server in go that serve a simple html page\", \"code\"),\n (\"can you find out who Jacky yougouri is ?\", \"web\"),\n (\"Can you use MCP to find stock market for IBM ?\", \"mcp\"),\n (\"Can you use MCP to to export my contacts to a csv file?\", \"mcp\"),\n (\"Can you use a MCP to find write notes to flomo\", \"mcp\"),\n (\"Can you use a MCP to query my calendar and find the next meeting?\", \"mcp\"),\n (\"Can you use a mcp to get the distance between Shanghai and Paris?\", \"mcp\"),\n (\"Setup a new flutter project called 'new_flutter_project'\", \"files\"),\n (\"can you create a new project called 'new_project'\", \"files\"),\n (\"can you make a simple web app that display a list of files in my dir\", \"code\"),\n (\"can you build a simple web server in python that serve a html page\", \"code\"),\n (\"find and buy me the latest rtx 4090\", \"web\"),\n (\"What are some good netflix show like Altered Carbon ?\", \"web\"),\n (\"can you find the latest research paper on AI\", \"web\"),\n (\"can you find research.pdf in my drive\", \"files\"),\n (\"hi\", \"talk\"),\n (\"hello\", \"talk\"),\n ]\n random.shuffle(few_shots)\n texts = [text for text, _ in few_shots]\n labels = [label for _, label in few_shots]\n self.talk_classifier.add_examples(texts, labels)\n\n def llm_router(self, text: str) -> tuple:\n \"\"\"\n Inference of the LLM router model.\n Args:\n text: The input text\n \"\"\"\n predictions = self.talk_classifier.predict(text)\n predictions = [pred for pred in predictions if pred[0] not in [\"HIGH\", \"LOW\"]]\n predictions = sorted(predictions, key=lambda x: x[1], reverse=True)\n return predictions[0]\n \n def router_vote(self, text: str, labels: list, log_confidence:bool = False) -> str:\n \"\"\"\n Vote between the LLM router and BART model.\n Args:\n text: The input text\n labels: The labels to classify\n Returns:\n str: The selected label\n \"\"\"\n if len(text) <= 8:\n return \"talk\"\n result_bart = self.pipelines['bart'](text, labels)\n result_llm_router = self.llm_router(text)\n bart, confidence_bart = result_bart['labels'][0], result_bart['scores'][0]\n llm_router, confidence_llm_router = result_llm_router[0], result_llm_router[1]\n final_score_bart = confidence_bart / (confidence_bart + confidence_llm_router)\n final_score_llm = confidence_llm_router / (confidence_bart + confidence_llm_router)\n self.logger.info(f\"Routing Vote for text {text}: BART: {bart} ({final_score_bart}) LLM-router: {llm_router} ({final_score_llm})\")\n if log_confidence:\n pretty_print(f\"Agent choice -> BART: {bart} ({final_score_bart}) LLM-router: {llm_router} ({final_score_llm})\")\n return bart if final_score_bart > final_score_llm else llm_router\n \n def find_first_sentence(self, text: str) -> str:\n first_sentence = None\n for line in text.split(\"\\n\"):\n first_sentence = line.strip()\n break\n if first_sentence is None:\n first_sentence = text\n return first_sentence\n \n def estimate_complexity(self, text: str) -> str:\n \"\"\"\n Estimate the complexity of the text.\n Args:\n text: The input text\n Returns:\n str: The estimated complexity\n \"\"\"\n try:\n predictions = self.complexity_classifier.predict(text)\n except Exception as e:\n pretty_print(f\"Error in estimate_complexity: {str(e)}\", color=\"failure\")\n return \"LOW\"\n predictions = sorted(predictions, key=lambda x: x[1], reverse=True)\n if len(predictions) == 0:\n return \"LOW\"\n complexity, confidence = predictions[0][0], predictions[0][1]\n if confidence < 0.5:\n self.logger.info(f\"Low confidence in complexity estimation: {confidence}\")\n return \"HIGH\"\n if complexity == \"HIGH\":\n return \"HIGH\"\n elif complexity == \"LOW\":\n return \"LOW\"\n pretty_print(f\"Failed to estimate the complexity of the text.\", color=\"failure\")\n return \"LOW\"\n \n def find_planner_agent(self) -> Agent:\n \"\"\"\n Find the planner agent.\n Returns:\n Agent: The planner agent\n \"\"\"\n for agent in self.agents:\n if agent.type == \"planner_agent\":\n return agent\n pretty_print(f\"Error finding planner agent. Please add a planner agent to the list of agents.\", color=\"failure\")\n self.logger.error(\"Planner agent not found.\")\n return None\n \n def select_agent(self, text: str) -> Agent:\n \"\"\"\n Select the appropriate agent based on the text.\n Args:\n text (str): The text to select the agent from\n Returns:\n Agent: The selected agent\n \"\"\"\n assert len(self.agents) > 0, \"No agents available.\"\n if len(self.agents) == 1:\n return self.agents[0]\n lang = self.lang_analysis.detect_language(text)\n text = self.find_first_sentence(text)\n text = self.lang_analysis.translate(text, lang)\n labels = [agent.role for agent in self.agents]\n complexity = self.estimate_complexity(text)\n if complexity == \"HIGH\":\n pretty_print(f\"Complex task detected, routing to planner agent.\", color=\"info\")\n return self.find_planner_agent()\n try:\n best_agent = self.router_vote(text, labels, log_confidence=False)\n except Exception as e:\n raise e\n for agent in self.agents:\n if best_agent == agent.role:\n role_name = agent.role\n pretty_print(f\"Selected agent: {agent.agent_name} (roles: {role_name})\", color=\"warning\")\n return agent\n pretty_print(f\"Error choosing agent.\", color=\"failure\")\n self.logger.error(\"No agent selected.\")\n return None\n\nif __name__ == \"__main__\":\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n agents = [\n CasualAgent(\"jarvis\", \"../prompts/base/casual_agent.txt\", None),\n BrowserAgent(\"browser\", \"../prompts/base/planner_agent.txt\", None),\n CoderAgent(\"coder\", \"../prompts/base/coder_agent.txt\", None),\n FileAgent(\"file\", \"../prompts/base/coder_agent.txt\", None)\n ]\n router = AgentRouter(agents)\n texts = [\n \"hi\",\n \"你好\",\n \"Bonjour\",\n \"Write a python script to check if the device on my network is connected to the internet\",\n \"Peut tu écrire un script python qui vérifie si l'appareil sur mon réseau est connecté à internet?\",\n \"写一个Python脚本,检查我网络上的设备是否连接到互联网\",\n \"Hey could you search the web for the latest news on the tesla stock market ?\",\n \"嘿,你能搜索网页上关于股票市场的最新新闻吗?\",\n \"Yo, cherche sur internet comment va tesla en bourse.\",\n \"I would like you to search for weather api and then make an app using this API\",\n \"我想让你搜索天气API,然后用这个API做一个应用程序\",\n \"J'aimerais que tu cherche une api météo et que l'utilise pour faire une application\",\n \"Plan a 3-day trip to New York, including flights and hotels.\",\n \"计划一次为期3天的纽约之旅,包括机票和酒店。\",\n \"Planifie un trip de 3 jours à Paris, y compris les vols et hotels.\",\n \"Find on the web the latest research papers on AI.\",\n \"在网上找到最新的人工智能研究论文。\",\n \"Trouve moi les derniers articles de recherche sur l'IA sur internet\",\n \"Help me write a C++ program to sort an array\",\n \"Tell me what France been up to lately\",\n \"告诉我法国最近在做什么\",\n \"Dis moi ce que la France a fait récemment\",\n \"Who is Sergio Pesto ?\",\n \"谁是Sergio Pesto?\",\n \"Qui est Sergio Pesto ?\",\n \"帮我写一个C++程序来排序数组\",\n \"Aide moi à faire un programme c++ pour trier une array.\",\n \"What’s the weather like today? Oh, and can you find a good weather app?\",\n \"今天天气怎么样?哦,你还能找到一个好的天气应用程序吗?\",\n \"La météo est comment aujourd'hui ? oh et trouve moi une bonne appli météo tant que tu y est.\",\n \"Can you debug this Java code? It’s not working.\",\n \"你能调试这段Java代码吗?它不起作用。\",\n \"Peut tu m'aider à debugger ce code java, ça marche pas\",\n \"Can you browse the web and find me a 4090 for cheap?\",\n \"你能浏览网页,为我找一个便宜的4090吗?\",\n \"Peut tu chercher sur internet et me trouver une 4090 pas cher ?\",\n \"Hey, can you find the old_project.zip file somewhere on my drive?\",\n \"嘿,你能在我驱动器上找到old_project.zip文件吗?\",\n \"Hé trouve moi le old_project.zip, il est quelque part sur mon disque.\",\n \"Tell me a funny story\",\n \"给我讲一个有趣的故事\",\n \"Raconte moi une histoire drole\"\n ]\n for text in texts:\n print(\"Input text:\", text)\n agent = router.select_agent(text)\n print()\n"], ["/agenticSeek/sources/tools/webSearch.py", "\nimport os\nimport requests\nimport dotenv\n\ndotenv.load_dotenv()\n\nfrom sources.tools.tools import Tools\nfrom sources.utility import animate_thinking, pretty_print\n\n\"\"\"\nWARNING\nwebSearch is fully deprecated and is being replaced by searxSearch for web search.\n\"\"\"\n\nclass webSearch(Tools):\n def __init__(self, api_key: str = None):\n \"\"\"\n A tool to perform a Google search and return information from the first result.\n \"\"\"\n super().__init__()\n self.tag = \"web_search\"\n self.api_key = api_key or os.getenv(\"SERPAPI_KEY\") # Requires a SerpApi key\n self.paywall_keywords = [\n \"subscribe\", \"login to continue\", \"access denied\", \"restricted content\", \"404\", \"this page is not working\"\n ]\n\n def link_valid(self, link):\n \"\"\"check if a link is valid.\"\"\"\n if not link.startswith(\"http\"):\n return \"Status: Invalid URL\"\n \n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\"}\n try:\n response = requests.get(link, headers=headers, timeout=5)\n status = response.status_code\n if status == 200:\n content = response.text[:1000].lower()\n if any(keyword in content for keyword in self.paywall_keywords):\n return \"Status: Possible Paywall\"\n return \"Status: OK\"\n elif status == 404:\n return \"Status: 404 Not Found\"\n elif status == 403:\n return \"Status: 403 Forbidden\"\n else:\n return f\"Status: {status} {response.reason}\"\n except requests.exceptions.RequestException as e:\n return f\"Error: {str(e)}\"\n\n def check_all_links(self, links):\n \"\"\"Check all links, one by one.\"\"\"\n # TODO Make it asyncromous or smth\n statuses = []\n for i, link in enumerate(links):\n status = self.link_valid(link)\n statuses.append(status)\n return statuses\n\n def execute(self, blocks: str, safety: bool = True) -> str:\n if self.api_key is None:\n return \"Error: No SerpApi key provided.\"\n for block in blocks:\n query = block.strip()\n pretty_print(f\"Searching for: {query}\", color=\"status\")\n if not query:\n return \"Error: No search query provided.\"\n\n try:\n url = \"https://serpapi.com/search\"\n params = {\n \"q\": query,\n \"api_key\": self.api_key,\n \"num\": 50,\n \"output\": \"json\"\n }\n response = requests.get(url, params=params)\n response.raise_for_status()\n\n data = response.json()\n results = []\n if \"organic_results\" in data and len(data[\"organic_results\"]) > 0:\n organic_results = data[\"organic_results\"][:50]\n links = [result.get(\"link\", \"No link available\") for result in organic_results]\n statuses = self.check_all_links(links)\n for result, status in zip(organic_results, statuses):\n if not \"OK\" in status:\n continue\n title = result.get(\"title\", \"No title\")\n snippet = result.get(\"snippet\", \"No snippet available\")\n link = result.get(\"link\", \"No link available\")\n results.append(f\"Title:{title}\\nSnippet:{snippet}\\nLink:{link}\")\n return \"\\n\\n\".join(results)\n else:\n return \"No results found for the query.\"\n except requests.RequestException as e:\n return f\"Error during web search: {str(e)}\"\n except Exception as e:\n return f\"Unexpected error: {str(e)}\"\n return \"No search performed\"\n\n def execution_failure_check(self, output: str) -> bool:\n return output.startswith(\"Error\") or \"No results found\" in output\n\n def interpreter_feedback(self, output: str) -> str:\n if self.execution_failure_check(output):\n return f\"Web search failed: {output}\"\n return f\"Web search result:\\n{output}\"\n\n\nif __name__ == \"__main__\":\n search_tool = webSearch(api_key=os.getenv(\"SERPAPI_KEY\"))\n query = \"when did covid start\"\n result = search_tool.execute([query], safety=True)\n output = search_tool.interpreter_feedback(result)\n print(output)"], ["/agenticSeek/sources/llm_provider.py", "import os\nimport platform\nimport socket\nimport subprocess\nimport time\nfrom urllib.parse import urlparse\n\nimport httpx\nimport requests\nfrom dotenv import load_dotenv\nfrom ollama import Client as OllamaClient\nfrom openai import OpenAI\n\nfrom sources.logger import Logger\nfrom sources.utility import pretty_print, animate_thinking\n\nclass Provider:\n def __init__(self, provider_name, model, server_address=\"127.0.0.1:5000\", is_local=False):\n self.provider_name = provider_name.lower()\n self.model = model\n self.is_local = is_local\n self.server_ip = server_address\n self.server_address = server_address\n self.available_providers = {\n \"ollama\": self.ollama_fn,\n \"server\": self.server_fn,\n \"openai\": self.openai_fn,\n \"lm-studio\": self.lm_studio_fn,\n \"huggingface\": self.huggingface_fn,\n \"google\": self.google_fn,\n \"deepseek\": self.deepseek_fn,\n \"together\": self.together_fn,\n \"dsk_deepseek\": self.dsk_deepseek,\n \"openrouter\": self.openrouter_fn,\n \"test\": self.test_fn\n }\n self.logger = Logger(\"provider.log\")\n self.api_key = None\n self.internal_url, self.in_docker = self.get_internal_url()\n self.unsafe_providers = [\"openai\", \"deepseek\", \"dsk_deepseek\", \"together\", \"google\", \"openrouter\"]\n if self.provider_name not in self.available_providers:\n raise ValueError(f\"Unknown provider: {provider_name}\")\n if self.provider_name in self.unsafe_providers and self.is_local == False:\n pretty_print(\"Warning: you are using an API provider. You data will be sent to the cloud.\", color=\"warning\")\n self.api_key = self.get_api_key(self.provider_name)\n elif self.provider_name != \"ollama\":\n pretty_print(f\"Provider: {provider_name} initialized at {self.server_ip}\", color=\"success\")\n\n def get_model_name(self) -> str:\n return self.model\n\n def get_api_key(self, provider):\n load_dotenv()\n api_key_var = f\"{provider.upper()}_API_KEY\"\n api_key = os.getenv(api_key_var)\n if not api_key:\n pretty_print(f\"API key {api_key_var} not found in .env file. Please add it\", color=\"warning\")\n exit(1)\n return api_key\n \n def get_internal_url(self):\n load_dotenv()\n url = os.getenv(\"DOCKER_INTERNAL_URL\")\n if not url: # running on host\n return \"http://localhost\", False\n return url, True\n\n def respond(self, history, verbose=True):\n \"\"\"\n Use the choosen provider to generate text.\n \"\"\"\n llm = self.available_providers[self.provider_name]\n self.logger.info(f\"Using provider: {self.provider_name} at {self.server_ip}\")\n try:\n thought = llm(history, verbose)\n except KeyboardInterrupt:\n self.logger.warning(\"User interrupted the operation with Ctrl+C\")\n return \"Operation interrupted by user. REQUEST_EXIT\"\n except ConnectionError as e:\n raise ConnectionError(f\"{str(e)}\\nConnection to {self.server_ip} failed.\")\n except AttributeError as e:\n raise NotImplementedError(f\"{str(e)}\\nIs {self.provider_name} implemented ?\")\n except ModuleNotFoundError as e:\n raise ModuleNotFoundError(\n f\"{str(e)}\\nA import related to provider {self.provider_name} was not found. Is it installed ?\")\n except Exception as e:\n if \"try again later\" in str(e).lower():\n return f\"{self.provider_name} server is overloaded. Please try again later.\"\n if \"refused\" in str(e):\n return f\"Server {self.server_ip} seem offline. Unable to answer.\"\n raise Exception(f\"Provider {self.provider_name} failed: {str(e)}\") from e\n return thought\n\n def is_ip_online(self, address: str, timeout: int = 10) -> bool:\n \"\"\"\n Check if an address is online by sending a ping request.\n \"\"\"\n if not address:\n return False\n parsed = urlparse(address if address.startswith(('http://', 'https://')) else f'http://{address}')\n\n hostname = parsed.hostname or address\n if \"127.0.0.1\" in address or \"localhost\" in address:\n return True\n try:\n ip_address = socket.gethostbyname(hostname)\n except socket.gaierror:\n self.logger.error(f\"Cannot resolve: {hostname}\")\n return False\n param = '-n' if platform.system().lower() == 'windows' else '-c'\n command = ['ping', param, '1', ip_address]\n try:\n result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)\n return result.returncode == 0\n except (subprocess.TimeoutExpired, subprocess.SubprocessError) as e:\n return False\n\n def server_fn(self, history, verbose=False):\n \"\"\"\n Use a remote server with LLM to generate text.\n \"\"\"\n thought = \"\"\n route_setup = f\"{self.server_ip}/setup\"\n route_gen = f\"{self.server_ip}/generate\"\n\n if not self.is_ip_online(self.server_ip):\n pretty_print(f\"Server is offline at {self.server_ip}\", color=\"failure\")\n\n try:\n requests.post(route_setup, json={\"model\": self.model})\n requests.post(route_gen, json={\"messages\": history})\n is_complete = False\n while not is_complete:\n try:\n response = requests.get(f\"{self.server_ip}/get_updated_sentence\")\n if \"error\" in response.json():\n pretty_print(response.json()[\"error\"], color=\"failure\")\n break\n thought = response.json()[\"sentence\"]\n is_complete = bool(response.json()[\"is_complete\"])\n time.sleep(2)\n except requests.exceptions.RequestException as e:\n pretty_print(f\"HTTP request failed: {str(e)}\", color=\"failure\")\n break\n except ValueError as e:\n pretty_print(f\"Failed to parse JSON response: {str(e)}\", color=\"failure\")\n break\n except Exception as e:\n pretty_print(f\"An error occurred: {str(e)}\", color=\"failure\")\n break\n except KeyError as e:\n raise Exception(\n f\"{str(e)}\\nError occured with server route. Are you using the correct address for the config.ini provider?\") from e\n except Exception as e:\n raise e\n return thought\n\n def ollama_fn(self, history, verbose=False):\n \"\"\"\n Use local or remote Ollama server to generate text.\n \"\"\"\n thought = \"\"\n host = f\"{self.internal_url}:11434\" if self.is_local else f\"http://{self.server_address}\"\n client = OllamaClient(host=host)\n\n try:\n stream = client.chat(\n model=self.model,\n messages=history,\n stream=True,\n )\n for chunk in stream:\n if verbose:\n print(chunk[\"message\"][\"content\"], end=\"\", flush=True)\n thought += chunk[\"message\"][\"content\"]\n except httpx.ConnectError as e:\n raise Exception(\n f\"\\nOllama connection failed at {host}. Check if the server is running.\"\n ) from e\n except Exception as e:\n if hasattr(e, 'status_code') and e.status_code == 404:\n animate_thinking(f\"Downloading {self.model}...\")\n client.pull(self.model)\n self.ollama_fn(history, verbose)\n if \"refused\" in str(e).lower():\n raise Exception(\n f\"Ollama connection refused at {host}. Is the server running?\"\n ) from e\n raise e\n\n return thought\n\n def huggingface_fn(self, history, verbose=False):\n \"\"\"\n Use huggingface to generate text.\n \"\"\"\n from huggingface_hub import InferenceClient\n client = InferenceClient(\n api_key=self.get_api_key(\"huggingface\")\n )\n completion = client.chat.completions.create(\n model=self.model,\n messages=history,\n max_tokens=1024,\n )\n thought = completion.choices[0].message\n return thought.content\n\n def openai_fn(self, history, verbose=False):\n \"\"\"\n Use openai to generate text.\n \"\"\"\n base_url = self.server_ip\n if self.is_local and self.in_docker:\n try:\n host, port = base_url.split(':')\n except Exception as e:\n port = \"8000\"\n client = OpenAI(api_key=self.api_key, base_url=f\"{self.internal_url}:{port}\")\n elif self.is_local:\n client = OpenAI(api_key=self.api_key, base_url=f\"http://{base_url}\")\n else:\n client = OpenAI(api_key=self.api_key)\n\n try:\n response = client.chat.completions.create(\n model=self.model,\n messages=history,\n )\n if response is None:\n raise Exception(\"OpenAI response is empty.\")\n thought = response.choices[0].message.content\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"OpenAI API error: {str(e)}\") from e\n\n def anthropic_fn(self, history, verbose=False):\n \"\"\"\n Use Anthropic to generate text.\n \"\"\"\n from anthropic import Anthropic\n\n client = Anthropic(api_key=self.api_key)\n system_message = None\n messages = []\n for message in history:\n clean_message = {'role': message['role'], 'content': message['content']}\n if message['role'] == 'system':\n system_message = message['content']\n else:\n messages.append(clean_message)\n\n try:\n response = client.messages.create(\n model=self.model,\n max_tokens=1024,\n messages=messages,\n system=system_message\n )\n if response is None:\n raise Exception(\"Anthropic response is empty.\")\n thought = response.content[0].text\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"Anthropic API error: {str(e)}\") from e\n\n def google_fn(self, history, verbose=False):\n \"\"\"\n Use google gemini to generate text.\n \"\"\"\n base_url = self.server_ip\n if self.is_local:\n raise Exception(\"Google Gemini is not available for local use. Change config.ini\")\n\n client = OpenAI(api_key=self.api_key, base_url=\"https://generativelanguage.googleapis.com/v1beta/openai/\")\n try:\n response = client.chat.completions.create(\n model=self.model,\n messages=history,\n )\n if response is None:\n raise Exception(\"Google response is empty.\")\n thought = response.choices[0].message.content\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"GOOGLE API error: {str(e)}\") from e\n\n def together_fn(self, history, verbose=False):\n \"\"\"\n Use together AI for completion\n \"\"\"\n from together import Together\n client = Together(api_key=self.api_key)\n if self.is_local:\n raise Exception(\"Together AI is not available for local use. Change config.ini\")\n\n try:\n response = client.chat.completions.create(\n model=self.model,\n messages=history,\n )\n if response is None:\n raise Exception(\"Together AI response is empty.\")\n thought = response.choices[0].message.content\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"Together AI API error: {str(e)}\") from e\n\n def deepseek_fn(self, history, verbose=False):\n \"\"\"\n Use deepseek api to generate text.\n \"\"\"\n client = OpenAI(api_key=self.api_key, base_url=\"https://api.deepseek.com\")\n if self.is_local:\n raise Exception(\"Deepseek (API) is not available for local use. Change config.ini\")\n try:\n response = client.chat.completions.create(\n model=\"deepseek-chat\",\n messages=history,\n stream=False\n )\n thought = response.choices[0].message.content\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"Deepseek API error: {str(e)}\") from e\n\n def lm_studio_fn(self, history, verbose=False):\n \"\"\"\n Use local lm-studio server to generate text.\n \"\"\"\n if self.in_docker:\n # Extract port from server_address if present\n port = \"1234\" # default\n if \":\" in self.server_address:\n port = self.server_address.split(\":\")[1]\n url = f\"{self.internal_url}:{port}\"\n else:\n url = f\"http://{self.server_ip}\"\n route_start = f\"{url}/v1/chat/completions\"\n payload = {\n \"messages\": history,\n \"temperature\": 0.7,\n \"max_tokens\": 4096,\n \"model\": self.model\n }\n\n try:\n response = requests.post(route_start, json=payload, timeout=30)\n if response.status_code != 200:\n raise Exception(f\"LM Studio returned status {response.status_code}: {response.text}\")\n if not response.text.strip():\n raise Exception(\"LM Studio returned empty response\")\n try:\n result = response.json()\n except ValueError as json_err:\n raise Exception(f\"Invalid JSON from LM Studio: {response.text[:200]}\") from json_err\n\n if verbose:\n print(\"Response from LM Studio:\", result)\n choices = result.get(\"choices\", [])\n if not choices:\n raise Exception(f\"No choices in LM Studio response: {result}\")\n\n message = choices[0].get(\"message\", {})\n content = message.get(\"content\", \"\")\n if not content:\n raise Exception(f\"Empty content in LM Studio response: {result}\")\n return content\n\n except requests.exceptions.Timeout:\n raise Exception(\"LM Studio request timed out - check if server is responsive\")\n except requests.exceptions.ConnectionError:\n raise Exception(f\"Cannot connect to LM Studio at {route_start} - check if server is running\")\n except requests.exceptions.RequestException as e:\n raise Exception(f\"HTTP request failed: {str(e)}\") from e\n except Exception as e:\n if \"LM Studio\" in str(e):\n raise # Re-raise our custom exceptions\n raise Exception(f\"Unexpected error: {str(e)}\") from e\n return thought\n\n def openrouter_fn(self, history, verbose=False):\n \"\"\"\n Use OpenRouter API to generate text.\n \"\"\"\n client = OpenAI(api_key=self.api_key, base_url=\"https://openrouter.ai/api/v1\")\n if self.is_local:\n # This case should ideally not be reached if unsafe_providers is set correctly\n # and is_local is False in config for openrouter\n raise Exception(\"OpenRouter is not available for local use. Change config.ini\")\n try:\n response = client.chat.completions.create(\n model=self.model,\n messages=history,\n )\n if response is None:\n raise Exception(\"OpenRouter response is empty.\")\n thought = response.choices[0].message.content\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"OpenRouter API error: {str(e)}\") from e\n\n def dsk_deepseek(self, history, verbose=False):\n \"\"\"\n Use: xtekky/deepseek4free\n For free api. Api key should be set to DSK_DEEPSEEK_API_KEY\n This is an unofficial provider, you'll have to find how to set it up yourself.\n \"\"\"\n from dsk.api import (\n DeepSeekAPI,\n AuthenticationError,\n RateLimitError,\n NetworkError,\n CloudflareError,\n APIError\n )\n thought = \"\"\n message = '\\n---\\n'.join([f\"{msg['role']}: {msg['content']}\" for msg in history])\n\n try:\n api = DeepSeekAPI(self.api_key)\n chat_id = api.create_chat_session()\n for chunk in api.chat_completion(chat_id, message):\n if chunk['type'] == 'text':\n thought += chunk['content']\n return thought\n except AuthenticationError:\n raise AuthenticationError(\"Authentication failed. Please check your token.\") from e\n except RateLimitError:\n raise RateLimitError(\"Rate limit exceeded. Please wait before making more requests.\") from e\n except CloudflareError as e:\n raise CloudflareError(f\"Cloudflare protection encountered: {str(e)}\") from e\n except NetworkError:\n raise NetworkError(\"Network error occurred. Check your internet connection.\") from e\n except APIError as e:\n raise APIError(f\"API error occurred: {str(e)}\") from e\n return None\n\n def test_fn(self, history, verbose=True):\n \"\"\"\n This function is used to conduct tests.\n \"\"\"\n thought = \"\"\"\n\\n\\n```json\\n{\\n \\\"plan\\\": [\\n {\\n \\\"agent\\\": \\\"Web\\\",\\n \\\"id\\\": \\\"1\\\",\\n \\\"need\\\": null,\\n \\\"task\\\": \\\"Conduct a comprehensive web search to identify at least five AI startups located in Osaka. Use reliable sources and websites such as Crunchbase, TechCrunch, or local Japanese business directories. Capture the company names, their websites, areas of expertise, and any other relevant details.\\\"\\n },\\n {\\n \\\"agent\\\": \\\"Web\\\",\\n \\\"id\\\": \\\"2\\\",\\n \\\"need\\\": null,\\n \\\"task\\\": \\\"Perform a similar search to find at least five AI startups in Tokyo. Again, use trusted sources like Crunchbase, TechCrunch, or Japanese business news websites. Gather the same details as for Osaka: company names, websites, areas of focus, and additional information.\\\"\\n },\\n {\\n \\\"agent\\\": \\\"File\\\",\\n \\\"id\\\": \\\"3\\\",\\n \\\"need\\\": [\\\"1\\\", \\\"2\\\"],\\n \\\"task\\\": \\\"Create a new text file named research_japan.txt in the user's home directory. Organize the data collected from both searches into this file, ensuring it is well-structured and formatted for readability. Include headers for Osaka and Tokyo sections, followed by the details of each startup found.\\\"\\n }\\n ]\\n}\\n```\n \"\"\"\n return thought\n\n\nif __name__ == \"__main__\":\n provider = Provider(\"server\", \"deepseek-r1:32b\", \" x.x.x.x:8080\")\n res = provider.respond([\"user\", \"Hello, how are you?\"])\n print(\"Response:\", res)\n"], ["/agenticSeek/sources/tools/flightSearch.py", "import os, sys\nimport requests\nimport dotenv\n\ndotenv.load_dotenv()\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass FlightSearch(Tools):\n def __init__(self, api_key: str = None):\n \"\"\"\n A tool to search for flight information using a flight number via SerpApi.\n \"\"\"\n super().__init__()\n self.tag = \"flight_search\"\n self.name = \"Flight Search\"\n self.description = \"Search for flight information using a flight number via SerpApi.\"\n self.api_key = api_key or os.getenv(\"SERPAPI_API_KEY\")\n\n def execute(self, blocks: str, safety: bool = True) -> str:\n if self.api_key is None:\n return \"Error: No SerpApi key provided.\"\n \n for block in blocks:\n flight_number = block.strip().upper().replace('\\n', '')\n if not flight_number:\n return \"Error: No flight number provided.\"\n\n try:\n url = \"https://serpapi.com/search\"\n params = {\n \"engine\": \"google_flights\",\n \"api_key\": self.api_key,\n \"q\": flight_number,\n \"type\": \"2\" # Flight status search\n }\n \n response = requests.get(url, params=params)\n response.raise_for_status()\n data = response.json()\n \n if \"flights\" in data and len(data[\"flights\"]) > 0:\n flight = data[\"flights\"][0]\n \n # Extract key information\n departure = flight.get(\"departure_airport\", {})\n arrival = flight.get(\"arrival_airport\", {})\n \n departure_code = departure.get(\"id\", \"Unknown\")\n departure_time = flight.get(\"departure_time\", \"Unknown\")\n arrival_code = arrival.get(\"id\", \"Unknown\") \n arrival_time = flight.get(\"arrival_time\", \"Unknown\")\n airline = flight.get(\"airline\", \"Unknown\")\n status = flight.get(\"flight_status\", \"Unknown\")\n\n return (\n f\"Flight: {flight_number}\\n\"\n f\"Airline: {airline}\\n\"\n f\"Status: {status}\\n\"\n f\"Departure: {departure_code} at {departure_time}\\n\"\n f\"Arrival: {arrival_code} at {arrival_time}\"\n )\n else:\n return f\"No flight information found for {flight_number}\"\n \n except requests.RequestException as e:\n return f\"Error during flight search: {str(e)}\"\n except Exception as e:\n return f\"Unexpected error: {str(e)}\"\n \n return \"No flight search performed\"\n\n def execution_failure_check(self, output: str) -> bool:\n return output.startswith(\"Error\") or \"No flight information found\" in output\n\n def interpreter_feedback(self, output: str) -> str:\n if self.execution_failure_check(output):\n return f\"Flight search failed: {output}\"\n return f\"Flight information:\\n{output}\"\n\n\nif __name__ == \"__main__\":\n flight_tool = FlightSearch()\n flight_number = \"AA123\"\n result = flight_tool.execute([flight_number], safety=True)\n feedback = flight_tool.interpreter_feedback(result)\n print(feedback)"], ["/agenticSeek/sources/browser.py", "from selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException, WebDriverException\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom typing import List, Tuple, Type, Dict\nfrom bs4 import BeautifulSoup\nfrom urllib.parse import urlparse\nfrom fake_useragent import UserAgent\nfrom selenium_stealth import stealth\nimport undetected_chromedriver as uc\nimport chromedriver_autoinstaller\nimport certifi\nimport ssl\nimport time\nimport random\nimport os\nimport shutil\nimport uuid\nimport tempfile\nimport markdownify\nimport sys\nimport re\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.logger import Logger\n\n\ndef get_chrome_path() -> str:\n \"\"\"Get the path to the Chrome executable.\"\"\"\n if sys.platform.startswith(\"win\"):\n paths = [\n \"C:\\\\Program Files\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe\",\n \"C:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe\",\n os.path.join(os.environ.get(\"LOCALAPPDATA\", \"\"), \"Google\\\\Chrome\\\\Application\\\\chrome.exe\") # User install\n ]\n elif sys.platform.startswith(\"darwin\"): # macOS\n paths = [\"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome\",\n \"/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta\"]\n else: # Linux\n paths = [\"/usr/bin/google-chrome\",\n \"/opt/chrome/chrome\",\n \"/usr/bin/chromium-browser\",\n \"/usr/bin/chromium\",\n \"/usr/local/bin/chrome\",\n \"/opt/google/chrome/chrome-headless-shell\",\n #\"/app/chrome_bundle/chrome136/chrome-linux64\"\n ]\n\n for path in paths:\n if os.path.exists(path) and os.access(path, os.X_OK):\n return path\n print(\"Looking for Google Chrome in these locations failed:\")\n print('\\n'.join(paths))\n chrome_path_env = os.environ.get(\"CHROME_EXECUTABLE_PATH\")\n if chrome_path_env and os.path.exists(chrome_path_env) and os.access(chrome_path_env, os.X_OK):\n return chrome_path_env\n path = input(\"Google Chrome not found. Please enter the path to the Chrome executable: \")\n if os.path.exists(path) and os.access(path, os.X_OK):\n os.environ[\"CHROME_EXECUTABLE_PATH\"] = path\n print(f\"Chrome path saved to environment variable CHROME_EXECUTABLE_PATH\")\n return path\n return None\n\ndef get_random_user_agent() -> str:\n \"\"\"Get a random user agent string with associated vendor.\"\"\"\n user_agents = [\n {\"ua\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36\", \"vendor\": \"Google Inc.\"},\n {\"ua\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 14_6_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36\", \"vendor\": \"Apple Inc.\"},\n {\"ua\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36\", \"vendor\": \"Google Inc.\"},\n ]\n return random.choice(user_agents)\n\ndef install_chromedriver() -> str:\n \"\"\"\n Install the ChromeDriver if not already installed. Return the path.\n \"\"\"\n # First try to use chromedriver in the project root directory (as per README)\n project_root_chromedriver = \"./chromedriver\"\n if os.path.exists(project_root_chromedriver) and os.access(project_root_chromedriver, os.X_OK):\n print(f\"Using ChromeDriver from project root: {project_root_chromedriver}\")\n return project_root_chromedriver\n \n # Then try to use the system-installed chromedriver\n chromedriver_path = shutil.which(\"chromedriver\")\n if chromedriver_path:\n return chromedriver_path\n \n # In Docker environment, try the fixed path\n if os.path.exists('/.dockerenv'):\n docker_chromedriver_path = \"/usr/local/bin/chromedriver\"\n if os.path.exists(docker_chromedriver_path) and os.access(docker_chromedriver_path, os.X_OK):\n print(f\"Using Docker ChromeDriver at {docker_chromedriver_path}\")\n return docker_chromedriver_path\n \n # Fallback to auto-installer only if no other option works\n try:\n print(\"ChromeDriver not found, attempting to install automatically...\")\n chromedriver_path = chromedriver_autoinstaller.install()\n except Exception as e:\n raise FileNotFoundError(\n \"ChromeDriver not found and could not be installed automatically. \"\n \"Please install it manually from https://chromedriver.chromium.org/downloads.\"\n \"and ensure it's in your PATH or specify the path directly.\"\n \"See know issues in readme if your chrome version is above 115.\"\n ) from e\n \n if not chromedriver_path:\n raise FileNotFoundError(\"ChromeDriver not found. Please install it or add it to your PATH.\")\n return chromedriver_path\n\ndef bypass_ssl() -> str:\n \"\"\"\n This is a fallback for stealth mode to bypass SSL verification. Which can fail on some setup.\n \"\"\"\n pretty_print(\"Bypassing SSL verification issues, we strongly advice you update your certifi SSL certificate.\", color=\"warning\")\n ssl._create_default_https_context = ssl._create_unverified_context\n\ndef create_undetected_chromedriver(service, chrome_options) -> webdriver.Chrome:\n \"\"\"Create an undetected ChromeDriver instance.\"\"\"\n try:\n driver = uc.Chrome(service=service, options=chrome_options)\n except Exception as e:\n pretty_print(f\"Failed to create Chrome driver: {str(e)}. Trying to bypass SSL...\", color=\"failure\")\n try:\n bypass_ssl()\n driver = uc.Chrome(service=service, options=chrome_options)\n except Exception as e:\n pretty_print(f\"Failed to create Chrome driver, fallback failed:\\n{str(e)}.\", color=\"failure\")\n raise e\n raise e\n driver.execute_script(\"Object.defineProperty(navigator, 'webdriver', {get: () => undefined})\") \n return driver\n\ndef create_driver(headless=False, stealth_mode=True, crx_path=\"./crx/nopecha.crx\", lang=\"en\") -> webdriver.Chrome:\n \"\"\"Create a Chrome WebDriver with specified options.\"\"\"\n # Warn if trying to run non-headless in Docker\n if not headless and os.path.exists('/.dockerenv'):\n print(\"[WARNING] Running non-headless browser in Docker may fail!\")\n print(\"[WARNING] Consider setting headless=True or headless_browser=True in config.ini\")\n \n chrome_options = Options()\n chrome_path = get_chrome_path()\n \n if not chrome_path:\n raise FileNotFoundError(\"Google Chrome not found. Please install it.\")\n chrome_options.binary_location = chrome_path\n \n if headless:\n #chrome_options.add_argument(\"--headless\")\n chrome_options.add_argument(\"--headless=new\")\n chrome_options.add_argument(\"--disable-gpu\")\n chrome_options.add_argument(\"--disable-webgl\")\n user_data_dir = tempfile.mkdtemp()\n user_agent = get_random_user_agent()\n width, height = (1920, 1080)\n user_data_dir = tempfile.mkdtemp(prefix=\"chrome_profile_\")\n chrome_options.add_argument(\"--no-sandbox\")\n chrome_options.add_argument('--disable-dev-shm-usage')\n profile_dir = f\"/tmp/chrome_profile_{uuid.uuid4().hex[:8]}\"\n chrome_options.add_argument(f'--user-data-dir={profile_dir}')\n chrome_options.add_argument(f\"--accept-lang={lang}-{lang.upper()},{lang};q=0.9\")\n chrome_options.add_argument(\"--disable-extensions\")\n chrome_options.add_argument(\"--disable-background-timer-throttling\")\n chrome_options.add_argument(\"--timezone=Europe/Paris\")\n chrome_options.add_argument('--remote-debugging-port=9222')\n chrome_options.add_argument('--disable-background-timer-throttling')\n chrome_options.add_argument('--disable-backgrounding-occluded-windows')\n chrome_options.add_argument('--disable-renderer-backgrounding')\n chrome_options.add_argument('--disable-features=TranslateUI')\n chrome_options.add_argument('--disable-ipc-flooding-protection')\n chrome_options.add_argument(\"--mute-audio\")\n chrome_options.add_argument(\"--disable-notifications\")\n chrome_options.add_argument(\"--autoplay-policy=user-gesture-required\")\n chrome_options.add_argument(\"--disable-features=SitePerProcess,IsolateOrigins\")\n chrome_options.add_argument(\"--enable-features=NetworkService,NetworkServiceInProcess\")\n chrome_options.add_argument(\"--disable-blink-features=AutomationControlled\")\n chrome_options.add_argument(f'user-agent={user_agent[\"ua\"]}')\n chrome_options.add_argument(f'--window-size={width},{height}')\n if not stealth_mode:\n if not os.path.exists(crx_path):\n pretty_print(f\"Anti-captcha CRX not found at {crx_path}.\", color=\"failure\")\n else:\n chrome_options.add_extension(crx_path)\n\n chromedriver_path = install_chromedriver()\n\n service = Service(chromedriver_path)\n if stealth_mode:\n chrome_options.add_argument(\"--disable-blink-features=AutomationControlled\")\n driver = create_undetected_chromedriver(service, chrome_options)\n chrome_version = driver.capabilities['browserVersion']\n stealth(driver,\n languages=[\"en-US\", \"en\"],\n vendor=user_agent[\"vendor\"],\n platform=\"Win64\" if \"windows\" in user_agent[\"ua\"].lower() else \"MacIntel\" if \"mac\" in user_agent[\"ua\"].lower() else \"Linux x86_64\",\n webgl_vendor=\"Intel Inc.\",\n renderer=\"Intel Iris OpenGL Engine\",\n fix_hairline=True,\n )\n return driver\n security_prefs = {\n \"profile.default_content_setting_values.geolocation\": 0,\n \"profile.default_content_setting_values.notifications\": 0,\n \"profile.default_content_setting_values.camera\": 0,\n \"profile.default_content_setting_values.microphone\": 0,\n \"profile.default_content_setting_values.midi_sysex\": 0,\n \"profile.default_content_setting_values.clipboard\": 0,\n \"profile.default_content_setting_values.media_stream\": 0,\n \"profile.default_content_setting_values.background_sync\": 0,\n \"profile.default_content_setting_values.sensors\": 0,\n \"profile.default_content_setting_values.accessibility_events\": 0,\n \"safebrowsing.enabled\": True,\n \"credentials_enable_service\": False,\n \"profile.password_manager_enabled\": False,\n \"webkit.webprefs.accelerated_2d_canvas_enabled\": True,\n \"webkit.webprefs.force_dark_mode_enabled\": False,\n \"webkit.webprefs.accelerated_2d_canvas_msaa_sample_count\": 4,\n \"enable_webgl\": True,\n \"enable_webgl2_compute_context\": True\n }\n chrome_options.add_experimental_option(\"prefs\", security_prefs)\n chrome_options.add_experimental_option(\"excludeSwitches\", [\"enable-automation\"])\n chrome_options.add_experimental_option('useAutomationExtension', False)\n return webdriver.Chrome(service=service, options=chrome_options)\n\nclass Browser:\n def __init__(self, driver, anticaptcha_manual_install=False):\n \"\"\"Initialize the browser with optional AntiCaptcha installation.\"\"\"\n self.js_scripts_folder = \"./sources/web_scripts/\" if not __name__ == \"__main__\" else \"./web_scripts/\"\n self.anticaptcha = \"https://chrome.google.com/webstore/detail/nopecha-captcha-solver/dknlfmjaanfblgfdfebhijalfmhmjjjo/related\"\n self.logger = Logger(\"browser.log\")\n self.screenshot_folder = os.path.join(os.getcwd(), \".screenshots\")\n self.tabs = []\n try:\n self.driver = driver\n self.wait = WebDriverWait(self.driver, 10)\n except Exception as e:\n raise Exception(f\"Failed to initialize browser: {str(e)}\")\n self.setup_tabs()\n self.patch_browser_fingerprint()\n if anticaptcha_manual_install:\n self.load_anticatpcha_manually()\n \n def setup_tabs(self):\n self.tabs = self.driver.window_handles\n try:\n self.driver.get(\"https://www.google.com\")\n except Exception as e:\n self.logger.log(f\"Failed to setup initial tab:\" + str(e))\n pass\n self.screenshot()\n \n def switch_control_tab(self):\n self.logger.log(\"Switching to control tab.\")\n self.driver.switch_to.window(self.tabs[0])\n \n def load_anticatpcha_manually(self):\n pretty_print(\"You might want to install the AntiCaptcha extension for captchas.\", color=\"warning\")\n try:\n self.driver.get(self.anticaptcha)\n except Exception as e:\n self.logger.log(f\"Failed to setup initial tab:\" + str(e))\n pass\n\n def human_move(element):\n actions = ActionChains(driver)\n x_offset = random.randint(-5,5)\n for _ in range(random.randint(2,5)):\n actions.move_by_offset(x_offset, random.randint(-2,2))\n actions.pause(random.uniform(0.1,0.3))\n actions.click().perform()\n\n def human_scroll(self):\n for _ in range(random.randint(1, 3)):\n scroll_pixels = random.randint(150, 1200)\n self.driver.execute_script(f\"window.scrollBy(0, {scroll_pixels});\")\n time.sleep(random.uniform(0.5, 2.0))\n if random.random() < 0.4:\n self.driver.execute_script(f\"window.scrollBy(0, -{random.randint(50, 300)});\")\n time.sleep(random.uniform(0.3, 1.0))\n\n def patch_browser_fingerprint(self) -> None:\n script = self.load_js(\"spoofing.js\")\n self.driver.execute_script(script)\n \n def go_to(self, url:str) -> bool:\n \"\"\"Navigate to a specified URL.\"\"\"\n time.sleep(random.uniform(0.4, 2.5))\n try:\n initial_handles = self.driver.window_handles\n self.driver.get(url)\n time.sleep(random.uniform(0.01, 0.3))\n try:\n wait = WebDriverWait(self.driver, timeout=10)\n wait.until(\n lambda driver: (\n not any(keyword in driver.page_source.lower() for keyword in [\"checking your browser\", \"captcha\"])\n ),\n message=\"stuck on 'checking browser' or verification screen\"\n )\n except TimeoutException:\n self.logger.warning(\"Timeout while waiting for page to bypass 'checking your browser'\")\n self.apply_web_safety()\n time.sleep(random.uniform(0.01, 0.2))\n self.human_scroll()\n self.logger.log(f\"Navigated to: {url}\")\n return True\n except TimeoutException as e:\n self.logger.error(f\"Timeout waiting for {url} to load: {str(e)}\")\n return False\n except WebDriverException as e:\n self.logger.error(f\"Error navigating to {url}: {str(e)}\")\n return False\n except Exception as e:\n self.logger.error(f\"Fatal error with go_to method on {url}:\\n{str(e)}\")\n raise e\n\n def is_sentence(self, text:str) -> bool:\n \"\"\"Check if the text qualifies as a meaningful sentence or contains important error codes.\"\"\"\n text = text.strip()\n\n if any(c.isdigit() for c in text):\n return True\n words = re.findall(r'\\w+', text, re.UNICODE)\n word_count = len(words)\n has_punctuation = any(text.endswith(p) for p in ['.', ',', ',', '!', '?', '。', '!', '?', '।', '۔'])\n is_long_enough = word_count > 4\n return (word_count >= 5 and (has_punctuation or is_long_enough))\n\n def get_text(self) -> str | None:\n \"\"\"Get page text as formatted Markdown\"\"\"\n try:\n soup = BeautifulSoup(self.driver.page_source, 'html.parser')\n for element in soup(['script', 'style', 'noscript', 'meta', 'link']):\n element.decompose()\n markdown_converter = markdownify.MarkdownConverter(\n heading_style=\"ATX\",\n strip=['a'],\n autolinks=False,\n bullets='•',\n strong_em_symbol='*',\n default_title=False,\n )\n markdown_text = markdown_converter.convert(str(soup.body))\n lines = []\n for line in markdown_text.splitlines():\n stripped = line.strip()\n if stripped and self.is_sentence(stripped):\n cleaned = ' '.join(stripped.split())\n lines.append(cleaned)\n result = \"[Start of page]\\n\\n\" + \"\\n\\n\".join(lines) + \"\\n\\n[End of page]\"\n result = re.sub(r'!\\[(.*?)\\]\\(.*?\\)', r'[IMAGE: \\1]', result)\n self.logger.info(f\"Extracted text: {result[:100]}...\")\n self.logger.info(f\"Extracted text length: {len(result)}\")\n return result[:32768]\n except Exception as e:\n self.logger.error(f\"Error getting text: {str(e)}\")\n return None\n \n def clean_url(self, url:str) -> str:\n \"\"\"Clean URL to keep only the part needed for navigation to the page\"\"\"\n clean = url.split('#')[0]\n parts = clean.split('?', 1)\n base_url = parts[0]\n if len(parts) > 1:\n query = parts[1]\n essential_params = []\n for param in query.split('&'):\n if param.startswith('_skw=') or param.startswith('q=') or param.startswith('s='):\n essential_params.append(param)\n elif param.startswith('_') or param.startswith('hash=') or param.startswith('itmmeta='):\n break\n if essential_params:\n return f\"{base_url}?{'&'.join(essential_params)}\"\n return base_url\n \n def is_link_valid(self, url:str) -> bool:\n \"\"\"Check if a URL is a valid link (page, not related to icon or metadata).\"\"\"\n if len(url) > 72:\n self.logger.warning(f\"URL too long: {url}\")\n return False\n parsed_url = urlparse(url)\n if not parsed_url.scheme or not parsed_url.netloc:\n self.logger.warning(f\"Invalid URL: {url}\")\n return False\n if re.search(r'/\\d+$', parsed_url.path):\n return False\n image_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp']\n metadata_extensions = ['.ico', '.xml', '.json', '.rss', '.atom']\n for ext in image_extensions + metadata_extensions:\n if url.lower().endswith(ext):\n return False\n return True\n\n def get_navigable(self) -> List[str]:\n \"\"\"Get all navigable links on the current page.\"\"\"\n try:\n links = []\n elements = self.driver.find_elements(By.TAG_NAME, \"a\")\n \n for element in elements:\n href = element.get_attribute(\"href\")\n if href and href.startswith((\"http\", \"https\")):\n links.append({\n \"url\": href,\n \"text\": element.text.strip(),\n \"is_displayed\": element.is_displayed()\n })\n \n self.logger.info(f\"Found {len(links)} navigable links\")\n return [self.clean_url(link['url']) for link in links if (link['is_displayed'] == True and self.is_link_valid(link['url']))]\n except Exception as e:\n self.logger.error(f\"Error getting navigable links: {str(e)}\")\n return []\n\n def click_element(self, xpath: str) -> bool:\n \"\"\"Click an element specified by XPath.\"\"\"\n try:\n element = self.wait.until(EC.element_to_be_clickable((By.XPATH, xpath)))\n if not element.is_displayed():\n return False\n if not element.is_enabled():\n return False\n try:\n self.logger.error(f\"Scrolling to element for click_element.\")\n self.driver.execute_script(\"arguments[0].scrollIntoView({block: 'center', behavior: 'smooth'});\", element)\n time.sleep(0.1)\n element.click()\n self.logger.info(f\"Clicked element at {xpath}\")\n return True\n except ElementClickInterceptedException as e:\n self.logger.error(f\"Error click_element: {str(e)}\")\n return False\n except TimeoutException:\n self.logger.warning(f\"Timeout clicking element.\")\n return False\n except Exception as e:\n self.logger.error(f\"Unexpected error clicking element at {xpath}: {str(e)}\")\n return False\n \n def load_js(self, file_name: str) -> str:\n \"\"\"Load javascript from script folder to inject to page.\"\"\"\n path = os.path.join(self.js_scripts_folder, file_name)\n self.logger.info(f\"Loading js at {path}\")\n try:\n with open(path, 'r') as f:\n return f.read()\n except FileNotFoundError as e:\n raise Exception(f\"Could not find: {path}\") from e\n except Exception as e:\n raise e\n\n def find_all_inputs(self, timeout=3):\n \"\"\"Find all inputs elements on the page.\"\"\"\n try:\n WebDriverWait(self.driver, timeout).until(\n EC.presence_of_element_located((By.TAG_NAME, \"body\"))\n )\n except Exception as e:\n self.logger.error(f\"Error waiting for input element: {str(e)}\")\n return []\n time.sleep(0.5)\n script = self.load_js(\"find_inputs.js\")\n input_elements = self.driver.execute_script(script)\n return input_elements\n\n def get_form_inputs(self) -> List[str]:\n \"\"\"Extract all input from the page and return them.\"\"\"\n try:\n input_elements = self.find_all_inputs()\n if not input_elements:\n self.logger.info(\"No input element on page.\")\n return [\"No input forms found on the page.\"]\n\n form_strings = []\n for element in input_elements:\n input_type = element.get(\"type\") or \"text\"\n if input_type in [\"hidden\", \"submit\", \"button\", \"image\"] or not element[\"displayed\"]:\n continue\n input_name = element.get(\"text\") or element.get(\"id\") or input_type\n if input_type == \"checkbox\" or input_type == \"radio\":\n try:\n checked_status = \"checked\" if element.is_selected() else \"unchecked\"\n except Exception as e:\n continue\n form_strings.append(f\"[{input_name}]({checked_status})\")\n else:\n form_strings.append(f\"[{input_name}](\"\")\")\n return form_strings\n\n except Exception as e:\n raise e\n\n def get_buttons_xpath(self) -> List[str]:\n \"\"\"\n Find buttons and return their type and xpath.\n \"\"\"\n buttons = self.driver.find_elements(By.TAG_NAME, \"button\") + \\\n self.driver.find_elements(By.XPATH, \"//input[@type='submit']\")\n result = []\n for i, button in enumerate(buttons):\n if not button.is_displayed() or not button.is_enabled():\n continue\n text = (button.text or button.get_attribute(\"value\") or \"\").lower().replace(' ', '')\n xpath = f\"(//button | //input[@type='submit'])[{i + 1}]\"\n result.append((text, xpath))\n result.sort(key=lambda x: len(x[0]))\n return result\n\n def wait_for_submission_outcome(self, timeout: int = 10) -> bool:\n \"\"\"\n Wait for a submission outcome (e.g., URL change or new element).\n \"\"\"\n try:\n self.logger.info(\"Waiting for submission outcome...\")\n wait = WebDriverWait(self.driver, timeout)\n wait.until(\n lambda driver: driver.current_url != self.driver.current_url or\n driver.find_elements(By.XPATH, \"//*[contains(text(), 'success')]\")\n )\n self.logger.info(\"Detected submission outcome\")\n return True\n except TimeoutException:\n self.logger.warning(\"No submission outcome detected\")\n return False\n\n def find_and_click_btn(self, btn_type: str = 'login', timeout: int = 5) -> bool:\n \"\"\"Find and click a submit button matching the specified type.\"\"\"\n buttons = self.get_buttons_xpath()\n if not buttons:\n self.logger.warning(\"No visible buttons found\")\n return False\n\n for button_text, xpath in buttons:\n if btn_type.lower() in button_text.lower() or btn_type.lower() in xpath.lower():\n try:\n wait = WebDriverWait(self.driver, timeout)\n element = wait.until(\n EC.element_to_be_clickable((By.XPATH, xpath)),\n message=f\"Button with XPath '{xpath}' not clickable within {timeout} seconds\"\n )\n if self.click_element(xpath):\n self.logger.info(f\"Clicked button '{button_text}' at XPath: {xpath}\")\n return True\n else:\n self.logger.warning(f\"Button '{button_text}' at XPath: {xpath} not clickable\")\n return False\n except TimeoutException:\n self.logger.warning(f\"Timeout waiting for '{button_text}' button at XPath: {xpath}\")\n return False\n except Exception as e:\n self.logger.error(f\"Error clicking button '{button_text}' at XPath: {xpath} - {str(e)}\")\n return False\n self.logger.warning(f\"No button matching '{btn_type}' found\")\n return False\n\n def tick_all_checkboxes(self) -> bool:\n \"\"\"\n Find and tick all checkboxes on the page.\n Returns True if successful, False if any issues occur.\n \"\"\"\n try:\n checkboxes = self.driver.find_elements(By.XPATH, \"//input[@type='checkbox']\")\n if not checkboxes:\n self.logger.info(\"No checkboxes found on the page\")\n return True\n\n for index, checkbox in enumerate(checkboxes, 1):\n try:\n WebDriverWait(self.driver, 10).until(\n EC.element_to_be_clickable(checkbox)\n )\n self.driver.execute_script(\n \"arguments[0].scrollIntoView({block: 'center', inline: 'center'});\", checkbox\n )\n if not checkbox.is_selected():\n try:\n checkbox.click()\n self.logger.info(f\"Ticked checkbox {index}\")\n except ElementClickInterceptedException:\n self.driver.execute_script(\"arguments[0].click();\", checkbox)\n self.logger.warning(f\"Click checkbox {index} intercepted\")\n else:\n self.logger.info(f\"Checkbox {index} already ticked\")\n except TimeoutException:\n self.logger.warning(f\"Timeout waiting for checkbox {index} to be clickable\")\n continue\n except Exception as e:\n self.logger.error(f\"Error ticking checkbox {index}: {str(e)}\")\n continue\n return True\n except Exception as e:\n self.logger.error(f\"Error finding checkboxes: {str(e)}\")\n return False\n\n def find_and_click_submission(self, timeout: int = 10) -> bool:\n possible_submissions = [\"login\", \"submit\", \"register\", \"continue\", \"apply\",\n \"ok\", \"confirm\", \"proceed\", \"accept\", \n \"done\", \"finish\", \"start\", \"calculate\"]\n for submission in possible_submissions:\n if self.find_and_click_btn(submission, timeout):\n self.logger.info(f\"Clicked on submission button: {submission}\")\n return True\n self.logger.warning(\"No submission button found\")\n return False\n \n def find_input_xpath_by_name(self, inputs, name: str) -> str | None:\n for field in inputs:\n if name in field[\"text\"]:\n return field[\"xpath\"]\n return None\n\n def fill_form_inputs(self, input_list: List[str]) -> bool:\n \"\"\"Fill inputs based on a list of [name](value) strings.\"\"\"\n if not isinstance(input_list, list):\n self.logger.error(\"input_list must be a list\")\n return False\n inputs = self.find_all_inputs()\n try:\n for input_str in input_list:\n match = re.match(r'\\[(.*?)\\]\\((.*?)\\)', input_str)\n if not match:\n self.logger.warning(f\"Invalid format for input: {input_str}\")\n continue\n\n name, value = match.groups()\n name = name.strip()\n value = value.strip()\n xpath = self.find_input_xpath_by_name(inputs, name)\n if not xpath:\n self.logger.warning(f\"Input field '{name}' not found\")\n continue\n try:\n element = WebDriverWait(self.driver, 10).until(\n EC.element_to_be_clickable((By.XPATH, xpath))\n )\n except TimeoutException:\n self.logger.error(f\"Timeout waiting for element '{name}' to be clickable\")\n continue\n self.driver.execute_script(\"arguments[0].scrollIntoView(true);\", element)\n if not element.is_displayed() or not element.is_enabled():\n self.logger.warning(f\"Element '{name}' is not interactable (not displayed or disabled)\")\n continue\n input_type = (element.get_attribute(\"type\") or \"text\").lower()\n if input_type in [\"checkbox\", \"radio\"]:\n is_checked = element.is_selected()\n should_be_checked = value.lower() == \"checked\"\n\n if is_checked != should_be_checked:\n element.click()\n self.logger.info(f\"Set {name} to {value}\")\n else:\n element.clear()\n element.send_keys(value)\n self.logger.info(f\"Filled {name} with {value}\")\n return True\n except Exception as e:\n self.logger.error(f\"Error filling form inputs: {str(e)}\")\n return False\n \n def fill_form(self, input_list: List[str]) -> bool:\n \"\"\"Fill form inputs based on a list of [name](value) and submit.\"\"\"\n if not isinstance(input_list, list):\n self.logger.error(\"input_list must be a list\")\n return False\n if self.fill_form_inputs(input_list):\n self.logger.info(\"Form filled successfully\")\n self.tick_all_checkboxes()\n if self.find_and_click_submission():\n if self.wait_for_submission_outcome():\n self.logger.info(\"Submission outcome detected\")\n return True\n else:\n self.logger.warning(\"No submission outcome detected\")\n else:\n self.logger.warning(\"Failed to submit form\")\n self.logger.warning(\"Failed to fill form inputs\")\n return False\n\n def get_current_url(self) -> str:\n \"\"\"Get the current URL of the page.\"\"\"\n return self.driver.current_url\n\n def get_page_title(self) -> str:\n \"\"\"Get the title of the current page.\"\"\"\n return self.driver.title\n\n def scroll_bottom(self) -> bool:\n \"\"\"Scroll to the bottom of the page.\"\"\"\n try:\n self.logger.info(\"Scrolling to the bottom of the page...\")\n self.driver.execute_script(\n \"window.scrollTo(0, document.body.scrollHeight);\"\n )\n time.sleep(0.5)\n return True\n except Exception as e:\n self.logger.error(f\"Error scrolling: {str(e)}\")\n return False\n \n def get_screenshot(self) -> str:\n return self.screenshot_folder + \"/updated_screen.png\"\n\n def screenshot(self, filename:str = 'updated_screen.png') -> bool:\n \"\"\"Take a screenshot of the current page, attempt to capture the full page by zooming out.\"\"\"\n self.logger.info(\"Taking full page screenshot...\")\n time.sleep(0.1)\n try:\n original_zoom = self.driver.execute_script(\"return document.body.style.zoom || 1;\")\n self.driver.execute_script(\"document.body.style.zoom='75%'\")\n time.sleep(0.1)\n path = os.path.join(self.screenshot_folder, filename)\n if not os.path.exists(self.screenshot_folder):\n os.makedirs(self.screenshot_folder)\n self.driver.save_screenshot(path)\n self.logger.info(f\"Full page screenshot saved as {filename}\")\n except Exception as e:\n self.logger.error(f\"Error taking full page screenshot: {str(e)}\")\n return False\n finally:\n self.driver.execute_script(f\"document.body.style.zoom='1'\")\n return True\n\n def apply_web_safety(self):\n \"\"\"\n Apply security measures to block any website malicious/annoying execution, privacy violation etc..\n \"\"\"\n self.logger.info(\"Applying web safety measures...\")\n script = self.load_js(\"inject_safety_script.js\")\n input_elements = self.driver.execute_script(script)\n\nif __name__ == \"__main__\":\n driver = create_driver(headless=False, stealth_mode=True, crx_path=\"../crx/nopecha.crx\")\n browser = Browser(driver, anticaptcha_manual_install=True)\n \n input(\"press enter to continue\")\n print(\"AntiCaptcha / Form Test\")\n browser.go_to(\"https://bot.sannysoft.com\")\n time.sleep(5)\n #txt = browser.get_text()\n browser.go_to(\"https://home.openweathermap.org/users/sign_up\")\n inputs_visible = browser.get_form_inputs()\n print(\"inputs:\", inputs_visible)\n #inputs_fill = ['[q](checked)', '[q](checked)', '[user[username]](mlg)', '[user[email]](mlg.fcu@gmail.com)', '[user[password]](placeholder_P@ssw0rd123)', '[user[password_confirmation]](placeholder_P@ssw0rd123)']\n #browser.fill_form(inputs_fill)\n input(\"press enter to exit\")\n\n# Test sites for browser fingerprinting and captcha\n# https://nowsecure.nl/\n# https://bot.sannysoft.com\n# https://browserleaks.com/\n# https://bot.incolumitas.com/\n# https://fingerprintjs.github.io/fingerprintjs/\n# https://antoinevastel.com/bots/"], ["/agenticSeek/sources/tools/PyInterpreter.py", "\nimport sys\nimport os\nimport re\nfrom io import StringIO\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass PyInterpreter(Tools):\n \"\"\"\n This class is a tool to allow agent for python code execution.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"python\"\n self.name = \"Python Interpreter\"\n self.description = \"This tool allows the agent to execute python code.\"\n\n def execute(self, codes:str, safety = False) -> str:\n \"\"\"\n Execute python code.\n \"\"\"\n output = \"\"\n if safety and input(\"Execute code ? y/n\") != \"y\":\n return \"Code rejected by user.\"\n stdout_buffer = StringIO()\n sys.stdout = stdout_buffer\n global_vars = {\n '__builtins__': __builtins__,\n 'os': os,\n 'sys': sys,\n '__name__': '__main__'\n }\n code = '\\n\\n'.join(codes)\n self.logger.info(f\"Executing code:\\n{code}\")\n try:\n try:\n buffer = exec(code, global_vars)\n self.logger.info(f\"Code executed successfully.\\noutput:{buffer}\")\n print(buffer)\n if buffer is not None:\n output = buffer + '\\n'\n except SystemExit:\n self.logger.info(\"SystemExit caught, code execution stopped.\")\n output = stdout_buffer.getvalue()\n return f\"[SystemExit caught] Output before exit:\\n{output}\"\n except Exception as e:\n self.logger.error(f\"Code execution failed: {str(e)}\")\n return \"code execution failed:\" + str(e)\n output = stdout_buffer.getvalue()\n finally:\n self.logger.info(\"Code execution finished.\")\n sys.stdout = sys.__stdout__\n return output\n\n def interpreter_feedback(self, output:str) -> str:\n \"\"\"\n Provide feedback based on the output of the code execution\n \"\"\"\n if self.execution_failure_check(output):\n feedback = f\"[failure] Error in execution:\\n{output}\"\n else:\n feedback = \"[success] Execution success, code output:\\n\" + output\n return feedback\n\n def execution_failure_check(self, feedback:str) -> bool:\n \"\"\"\n Check if the code execution failed.\n \"\"\"\n error_patterns = [\n r\"expected\", \n r\"errno\", \n r\"failed\", \n r\"traceback\", \n r\"invalid\", \n r\"unrecognized\", \n r\"exception\", \n r\"syntax\", \n r\"crash\", \n r\"segmentation fault\", \n r\"core dumped\"\n ]\n combined_pattern = \"|\".join(error_patterns)\n if re.search(combined_pattern, feedback, re.IGNORECASE):\n self.logger.error(f\"Execution failure detected: {feedback}\")\n return True\n self.logger.info(\"No execution success detected.\")\n return False\n\nif __name__ == \"__main__\":\n text = \"\"\"\nFor Python, let's also do a quick check:\n\n```python\nprint(\"Hello from Python!\")\n```\n\nIf these work, you'll see the outputs in the next message. Let me know if you'd like me to test anything specific! \n\nhere is a save test\n```python:tmp.py\n\ndef print_hello():\n hello = \"Hello World\"\n print(hello)\n\nif __name__ == \"__main__\":\n print_hello()\n```\n\"\"\"\n py = PyInterpreter()\n codes, save_path = py.load_exec_block(text)\n py.save_block(codes, save_path)\n print(py.execute(codes))"], ["/agenticSeek/sources/language.py", "from typing import List, Tuple, Type, Dict\nimport re\nimport langid\nfrom transformers import MarianMTModel, MarianTokenizer\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.logger import Logger\n\nclass LanguageUtility:\n \"\"\"LanguageUtility for language, or emotion identification\"\"\"\n def __init__(self, supported_language: List[str] = [\"en\", \"fr\", \"zh\"]):\n \"\"\"\n Initialize the LanguageUtility class\n args:\n supported_language: list of languages for translation, determine which Helsinki-NLP model to load\n \"\"\"\n self.translators_tokenizer = None \n self.translators_model = None\n self.logger = Logger(\"language.log\")\n self.supported_language = supported_language\n self.load_model()\n \n def load_model(self) -> None:\n animate_thinking(\"Loading language utility...\", color=\"status\")\n self.translators_tokenizer = {lang: MarianTokenizer.from_pretrained(f\"Helsinki-NLP/opus-mt-{lang}-en\") for lang in self.supported_language if lang != \"en\"}\n self.translators_model = {lang: MarianMTModel.from_pretrained(f\"Helsinki-NLP/opus-mt-{lang}-en\") for lang in self.supported_language if lang != \"en\"}\n \n def detect_language(self, text: str) -> str:\n \"\"\"\n Detect the language of the given text using langdetect\n Limited to the supported languages list because of the model tendency to mistake similar languages\n Args:\n text: string to analyze\n Returns: ISO639-1 language code\n \"\"\"\n langid.set_languages(self.supported_language)\n lang, score = langid.classify(text)\n self.logger.info(f\"Identified: {text} as {lang} with conf {score}\")\n return lang\n\n def translate(self, text: str, origin_lang: str) -> str:\n \"\"\"\n Translate the given text to English\n Args:\n text: string to translate\n origin_lang: ISO language code\n Returns: translated str\n \"\"\"\n if origin_lang == \"en\":\n return text\n if origin_lang not in self.translators_tokenizer:\n pretty_print(f\"Language {origin_lang} not supported for translation\", color=\"error\")\n return text\n tokenizer = self.translators_tokenizer[origin_lang]\n inputs = tokenizer(text, return_tensors=\"pt\", padding=True)\n model = self.translators_model[origin_lang]\n translation = model.generate(**inputs)\n return tokenizer.decode(translation[0], skip_special_tokens=True)\n\n def analyze(self, text):\n \"\"\"\n Combined analysis of language and emotion\n Args:\n text: string to analyze\n Returns: dictionary with language related information\n \"\"\"\n try:\n language = self.detect_language(text)\n return {\n \"language\": language\n }\n except Exception as e:\n raise e\n\nif __name__ == \"__main__\":\n detector = LanguageUtility()\n \n test_texts = [\n \"I am so happy today!\",\n \"我不要去巴黎\",\n \"La vie c'est cool\"\n ]\n for text in test_texts:\n pretty_print(\"Analyzing...\", color=\"status\")\n pretty_print(f\"Language: {detector.detect_language(text)}\", color=\"status\")\n result = detector.analyze(text)\n trans = detector.translate(text, result['language'])\n pretty_print(f\"Translation: {trans} - from: {result['language']}\")"], ["/agenticSeek/sources/tools/fileFinder.py", "import os, sys\nimport stat\nimport mimetypes\nimport configparser\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass FileFinder(Tools):\n \"\"\"\n A tool that finds files in the current directory and returns their information.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"file_finder\"\n self.name = \"File Finder\"\n self.description = \"Finds files in the current directory and returns their information.\"\n \n def read_file(self, file_path: str) -> str:\n \"\"\"\n Reads the content of a file.\n Args:\n file_path (str): The path to the file to read\n Returns:\n str: The content of the file\n \"\"\"\n try:\n with open(file_path, 'r') as file:\n return file.read()\n except Exception as e:\n return f\"Error reading file: {e}\"\n \n def read_arbitrary_file(self, file_path: str, file_type: str) -> str:\n \"\"\"\n Reads the content of a file with arbitrary encoding.\n Args:\n file_path (str): The path to the file to read\n Returns:\n str: The content of the file in markdown format\n \"\"\"\n mime_type, _ = mimetypes.guess_type(file_path)\n if mime_type:\n if mime_type.startswith(('image/', 'video/', 'audio/')):\n return \"can't read file type: image, video, or audio files are not supported.\"\n content_raw = self.read_file(file_path)\n if \"text\" in file_type:\n content = content_raw\n elif \"pdf\" in file_type:\n from pypdf import PdfReader\n reader = PdfReader(file_path)\n content = '\\n'.join([pt.extract_text() for pt in reader.pages])\n elif \"binary\" in file_type:\n content = content_raw.decode('utf-8', errors='replace')\n else:\n content = content_raw\n return content\n \n def get_file_info(self, file_path: str) -> str:\n \"\"\"\n Gets information about a file, including its name, path, type, content, and permissions.\n Args:\n file_path (str): The path to the file\n Returns:\n str: A dictionary containing the file information\n \"\"\"\n if os.path.exists(file_path):\n stats = os.stat(file_path)\n permissions = oct(stat.S_IMODE(stats.st_mode))\n file_type, _ = mimetypes.guess_type(file_path)\n file_type = file_type if file_type else \"Unknown\"\n content = self.read_arbitrary_file(file_path, file_type)\n \n result = {\n \"filename\": os.path.basename(file_path),\n \"path\": file_path,\n \"type\": file_type,\n \"read\": content,\n \"permissions\": permissions\n }\n return result\n else:\n return {\"filename\": file_path, \"error\": \"File not found\"}\n \n def recursive_search(self, directory_path: str, filename: str) -> str:\n \"\"\"\n Recursively searches for files in a directory and its subdirectories.\n Args:\n directory_path (str): The directory to search in\n filename (str): The filename to search for\n Returns:\n str | None: The path to the file if found, None otherwise\n \"\"\"\n file_path = None\n excluded_files = [\".pyc\", \".o\", \".so\", \".a\", \".lib\", \".dll\", \".dylib\", \".so\", \".git\"]\n for root, dirs, files in os.walk(directory_path):\n for f in files:\n if f is None:\n continue\n if any(excluded_file in f for excluded_file in excluded_files):\n continue\n if filename.strip() in f.strip():\n file_path = os.path.join(root, f)\n return file_path\n return None\n \n\n def execute(self, blocks: list, safety:bool = False) -> str:\n \"\"\"\n Executes the file finding operation for given filenames.\n Args:\n blocks (list): List of filenames to search for\n Returns:\n str: Results of the file search\n \"\"\"\n if not blocks or not isinstance(blocks, list):\n return \"Error: No valid filenames provided\"\n\n output = \"\"\n for block in blocks:\n filename = self.get_parameter_value(block, \"name\")\n action = self.get_parameter_value(block, \"action\")\n if filename is None:\n output = \"Error: No filename provided\\n\"\n return output\n if action is None:\n action = \"info\"\n print(\"File finder: recursive search started...\")\n file_path = self.recursive_search(self.work_dir, filename)\n if file_path is None:\n output = f\"File: {filename} - not found\\n\"\n continue\n result = self.get_file_info(file_path)\n if \"error\" in result:\n output += f\"File: {result['filename']} - {result['error']}\\n\"\n else:\n if action == \"read\":\n output += \"Content:\\n\" + result['read'] + \"\\n\"\n else:\n output += (f\"File: {result['filename']}, \"\n f\"found at {result['path']}, \"\n f\"File type {result['type']}\\n\")\n return output.strip()\n\n def execution_failure_check(self, output: str) -> bool:\n \"\"\"\n Checks if the file finding operation failed.\n Args:\n output (str): The output string from execute()\n Returns:\n bool: True if execution failed, False if successful\n \"\"\"\n if not output:\n return True\n if \"Error\" in output or \"not found\" in output:\n return True\n return False\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Provides feedback about the file finding operation.\n Args:\n output (str): The output string from execute()\n Returns:\n str: Feedback message for the AI\n \"\"\"\n if not output:\n return \"No output generated from file finder tool\"\n \n feedback = \"File Finder Results:\\n\"\n \n if \"Error\" in output or \"not found\" in output:\n feedback += f\"Failed to process: {output}\\n\"\n else:\n feedback += f\"Successfully found: {output}\\n\"\n return feedback.strip()\n\nif __name__ == \"__main__\":\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n tool = FileFinder()\n result = tool.execute([\"\"\"\naction=read\nname=tools.py\n\"\"\"], False)\n print(\"Execution result:\")\n print(result)\n print(\"\\nFailure check:\", tool.execution_failure_check(result))\n print(\"\\nFeedback:\")\n print(tool.interpreter_feedback(result))"], ["/agenticSeek/sources/utility.py", "\nfrom colorama import Fore\nfrom termcolor import colored\nimport platform\nimport threading\nimport itertools\nimport time\n\nthinking_event = threading.Event()\ncurrent_animation_thread = None\n\ndef get_color_map():\n if platform.system().lower() != \"windows\":\n color_map = {\n \"success\": \"green\",\n \"failure\": \"red\",\n \"status\": \"light_green\",\n \"code\": \"light_blue\",\n \"warning\": \"yellow\",\n \"output\": \"cyan\",\n \"info\": \"cyan\"\n }\n else:\n color_map = {\n \"success\": \"green\",\n \"failure\": \"red\",\n \"status\": \"light_green\",\n \"code\": \"light_blue\",\n \"warning\": \"yellow\",\n \"output\": \"cyan\",\n \"info\": \"black\"\n }\n return color_map\n\ndef pretty_print(text, color=\"info\", no_newline=False):\n \"\"\"\n Print text with color formatting.\n\n Args:\n text (str): The text to print\n color (str, optional): The color to use. Defaults to \"info\".\n Valid colors are:\n - \"success\": Green\n - \"failure\": Red \n - \"status\": Light green\n - \"code\": Light blue\n - \"warning\": Yellow\n - \"output\": Cyan\n - \"default\": Black (Windows only)\n \"\"\"\n thinking_event.set()\n if current_animation_thread and current_animation_thread.is_alive():\n current_animation_thread.join()\n thinking_event.clear()\n \n color_map = get_color_map()\n if color not in color_map:\n color = \"info\"\n print(colored(text, color_map[color]), end='' if no_newline else \"\\n\")\n\ndef animate_thinking(text, color=\"status\", duration=120):\n \"\"\"\n Animate a thinking spinner while a task is being executed.\n It use a daemon thread to run the animation. This will not block the main thread.\n Color are the same as pretty_print.\n \"\"\"\n global current_animation_thread\n \n thinking_event.set()\n if current_animation_thread and current_animation_thread.is_alive():\n current_animation_thread.join()\n thinking_event.clear()\n \n def _animate():\n color_map = {\n \"success\": (Fore.GREEN, \"green\"),\n \"failure\": (Fore.RED, \"red\"),\n \"status\": (Fore.LIGHTGREEN_EX, \"light_green\"),\n \"code\": (Fore.LIGHTBLUE_EX, \"light_blue\"),\n \"warning\": (Fore.YELLOW, \"yellow\"),\n \"output\": (Fore.LIGHTCYAN_EX, \"cyan\"),\n \"default\": (Fore.RESET, \"black\"),\n \"info\": (Fore.CYAN, \"cyan\")\n }\n fore_color, term_color = color_map.get(color, color_map[\"default\"])\n spinner = itertools.cycle([\n '▉▁▁▁▁▁', '▉▉▂▁▁▁', '▉▉▉▃▁▁', '▉▉▉▉▅▁', '▉▉▉▉▉▇', '▉▉▉▉▉▉',\n '▉▉▉▉▇▅', '▉▉▉▆▃▁', '▉▉▅▃▁▁', '▉▇▃▁▁▁', '▇▃▁▁▁▁', '▃▁▁▁▁▁',\n '▁▃▅▃▁▁', '▁▅▉▅▁▁', '▃▉▉▉▃▁', '▅▉▁▉▅▃', '▇▃▁▃▇▅', '▉▁▁▁▉▇',\n '▉▅▃▁▃▅', '▇▉▅▃▅▇', '▅▉▇▅▇▉', '▃▇▉▇▉▅', '▁▅▇▉▇▃', '▁▃▅▇▅▁' \n ])\n end_time = time.time() + duration\n\n while not thinking_event.is_set() and time.time() < end_time:\n symbol = next(spinner)\n if platform.system().lower() != \"windows\":\n print(f\"\\r{fore_color}{symbol} {text}{Fore.RESET}\", end=\"\", flush=True)\n else:\n print(f\"\\r{colored(f'{symbol} {text}', term_color)}\", end=\"\", flush=True)\n time.sleep(0.2)\n print(\"\\r\" + \" \" * (len(text) + 7) + \"\\r\", end=\"\", flush=True)\n current_animation_thread = threading.Thread(target=_animate, daemon=True)\n current_animation_thread.start()\n\ndef timer_decorator(func):\n \"\"\"\n Decorator to measure the execution time of a function.\n Usage:\n @timer_decorator\n def my_function():\n # code to execute\n \"\"\"\n from time import time\n def wrapper(*args, **kwargs):\n start_time = time()\n result = func(*args, **kwargs)\n end_time = time()\n pretty_print(f\"{func.__name__} took {end_time - start_time:.2f} seconds to execute\", \"status\")\n return result\n return wrapper\n\nif __name__ == \"__main__\":\n import time\n pretty_print(\"starting imaginary task\", \"success\")\n animate_thinking(\"Thinking...\", \"status\")\n time.sleep(4)\n pretty_print(\"starting another task\", \"failure\")\n animate_thinking(\"Thinking...\", \"status\")\n time.sleep(4)\n pretty_print(\"yet another task\", \"info\")\n animate_thinking(\"Thinking...\", \"status\")\n time.sleep(4)\n pretty_print(\"This is an info message\", \"info\")"], ["/agenticSeek/sources/tools/tools.py", "\n\"\"\"\ndefine a generic tool class, any tool can be used by the agent.\n\nA tool can be used by a llm like so:\n```\n\n```\n\nwe call these \"blocks\".\n\nFor example:\n```python\nprint(\"Hello world\")\n```\nThis is then executed by the tool with its own class implementation of execute().\nA tool is not just for code tool but also API, internet search, MCP, etc..\n\"\"\"\n\nimport sys\nimport os\nimport configparser\nfrom abc import abstractmethod\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\nfrom sources.logger import Logger\n\nclass Tools():\n \"\"\"\n Abstract class for all tools.\n \"\"\"\n def __init__(self):\n self.tag = \"undefined\"\n self.name = \"undefined\"\n self.description = \"undefined\"\n self.client = None\n self.messages = []\n self.logger = Logger(\"tools.log\")\n self.config = configparser.ConfigParser()\n self.work_dir = self.create_work_dir()\n self.excutable_blocks_found = False\n self.safe_mode = False\n self.allow_language_exec_bash = False\n \n def get_work_dir(self):\n return self.work_dir\n \n def set_allow_language_exec_bash(self, value: bool) -> None:\n self.allow_language_exec_bash = value \n\n def safe_get_work_dir_path(self):\n path = None\n path = os.getenv('WORK_DIR', path)\n if path is None or path == \"\":\n path = self.config['MAIN']['work_dir'] if 'MAIN' in self.config and 'work_dir' in self.config['MAIN'] else None\n if path is None or path == \"\":\n print(\"No work directory specified, using default.\")\n path = self.create_work_dir()\n return path\n \n def config_exists(self):\n \"\"\"Check if the config file exists.\"\"\"\n return os.path.exists('./config.ini')\n\n def create_work_dir(self):\n \"\"\"Create the work directory if it does not exist.\"\"\"\n default_path = os.path.dirname(os.getcwd())\n if self.config_exists():\n self.config.read('./config.ini')\n workdir_path = self.safe_get_work_dir_path()\n else:\n workdir_path = default_path\n return workdir_path\n\n @abstractmethod\n def execute(self, blocks:[str], safety:bool) -> str:\n \"\"\"\n Abstract method that must be implemented by child classes to execute the tool's functionality.\n Args:\n blocks (List[str]): The codes or queries blocks to execute\n safety (bool): Whenever human intervention is required\n Returns:\n str: The output/result from executing the tool\n \"\"\"\n pass\n\n @abstractmethod\n def execution_failure_check(self, output:str) -> bool:\n \"\"\"\n Abstract method that must be implemented by child classes to check if tool execution failed.\n Args:\n output (str): The output string from the tool execution to analyze\n Returns:\n bool: True if execution failed, False if successful\n \"\"\"\n pass\n\n @abstractmethod\n def interpreter_feedback(self, output:str) -> str:\n \"\"\"\n Abstract method that must be implemented by child classes to provide feedback to the AI from the tool.\n Args:\n output (str): The output string from the tool execution to analyze\n Returns:\n str: The feedback message to the AI\n \"\"\"\n pass\n\n def save_block(self, blocks:[str], save_path:str) -> None:\n \"\"\"\n Save code or query blocks to a file at the specified path.\n Creates the directory path if it doesn't exist.\n Args:\n blocks (List[str]): List of code/query blocks to save\n save_path (str): File path where blocks should be saved\n \"\"\"\n if save_path is None:\n return\n self.logger.info(f\"Saving blocks to {save_path}\")\n save_path_dir = os.path.dirname(save_path)\n save_path_file = os.path.basename(save_path)\n directory = os.path.join(self.work_dir, save_path_dir)\n if directory and not os.path.exists(directory):\n self.logger.info(f\"Creating directory {directory}\")\n os.makedirs(directory)\n for block in blocks:\n with open(os.path.join(directory, save_path_file), 'w') as f:\n f.write(block)\n \n def get_parameter_value(self, block: str, parameter_name: str) -> str:\n \"\"\"\n Get a parameter name.\n Args:\n block (str): The block of text to search for the parameter\n parameter_name (str): The name of the parameter to retrieve\n Returns:\n str: The value of the parameter\n \"\"\"\n for param_line in block.split('\\n'):\n if parameter_name in param_line:\n param_value = param_line.split('=')[1].strip()\n return param_value\n return None\n \n def found_executable_blocks(self):\n \"\"\"\n Check if executable blocks were found.\n \"\"\"\n tmp = self.excutable_blocks_found\n self.excutable_blocks_found = False\n return tmp\n\n def load_exec_block(self, llm_text: str):\n \"\"\"\n Extract code/query blocks from LLM-generated text and process them for execution.\n This method parses the text looking for code blocks marked with the tool's tag (e.g. ```python).\n Args:\n llm_text (str): The raw text containing code blocks from the LLM\n Returns:\n tuple[list[str], str | None]: A tuple containing:\n - List of extracted and processed code blocks\n - The path the code blocks was saved to\n \"\"\"\n assert self.tag != \"undefined\", \"Tag not defined\"\n start_tag = f'```{self.tag}' \n end_tag = '```'\n code_blocks = []\n start_index = 0\n save_path = None\n\n if start_tag not in llm_text:\n return None, None\n\n while True:\n start_pos = llm_text.find(start_tag, start_index)\n if start_pos == -1:\n break\n\n line_start = llm_text.rfind('\\n', 0, start_pos)+1\n leading_whitespace = llm_text[line_start:start_pos]\n\n end_pos = llm_text.find(end_tag, start_pos + len(start_tag))\n if end_pos == -1:\n break\n content = llm_text[start_pos + len(start_tag):end_pos]\n lines = content.split('\\n')\n if leading_whitespace:\n processed_lines = []\n for line in lines:\n if line.startswith(leading_whitespace):\n processed_lines.append(line[len(leading_whitespace):])\n else:\n processed_lines.append(line)\n content = '\\n'.join(processed_lines)\n\n if ':' in content.split('\\n')[0]:\n save_path = content.split('\\n')[0].split(':')[1]\n content = content[content.find('\\n')+1:]\n self.excutable_blocks_found = True\n code_blocks.append(content)\n start_index = end_pos + len(end_tag)\n self.logger.info(f\"Found {len(code_blocks)} blocks to execute\")\n return code_blocks, save_path\n \nif __name__ == \"__main__\":\n tool = Tools()\n tool.tag = \"python\"\n rt = tool.load_exec_block(\"\"\"```python\nimport os\n\nfor file in os.listdir():\n if file.endswith('.py'):\n print(file)\n```\ngoodbye!\n \"\"\")\n print(rt)"], ["/agenticSeek/sources/schemas.py", "\nfrom typing import Tuple, Callable\nfrom pydantic import BaseModel\nfrom sources.utility import pretty_print\n\nclass QueryRequest(BaseModel):\n query: str\n tts_enabled: bool = True\n\n def __str__(self):\n return f\"Query: {self.query}, Language: {self.lang}, TTS: {self.tts_enabled}, STT: {self.stt_enabled}\"\n\n def jsonify(self):\n return {\n \"query\": self.query,\n \"tts_enabled\": self.tts_enabled,\n }\n\nclass QueryResponse(BaseModel):\n done: str\n answer: str\n reasoning: str\n agent_name: str\n success: str\n blocks: dict\n status: str\n uid: str\n\n def __str__(self):\n return f\"Done: {self.done}, Answer: {self.answer}, Agent Name: {self.agent_name}, Success: {self.success}, Blocks: {self.blocks}, Status: {self.status}, UID: {self.uid}\"\n\n def jsonify(self):\n return {\n \"done\": self.done,\n \"answer\": self.answer,\n \"reasoning\": self.reasoning,\n \"agent_name\": self.agent_name,\n \"success\": self.success,\n \"blocks\": self.blocks,\n \"status\": self.status,\n \"uid\": self.uid\n }\n\nclass executorResult:\n \"\"\"\n A class to store the result of a tool execution.\n \"\"\"\n def __init__(self, block: str, feedback: str, success: bool, tool_type: str):\n \"\"\"\n Initialize an agent with execution results.\n\n Args:\n block: The content or code block processed by the agent.\n feedback: Feedback or response information from the execution.\n success: Boolean indicating whether the agent's execution was successful.\n tool_type: The type of tool used by the agent for execution.\n \"\"\"\n self.block = block\n self.feedback = feedback\n self.success = success\n self.tool_type = tool_type\n \n def __str__(self):\n return f\"Tool: {self.tool_type}\\nBlock: {self.block}\\nFeedback: {self.feedback}\\nSuccess: {self.success}\"\n \n def jsonify(self):\n return {\n \"block\": self.block,\n \"feedback\": self.feedback,\n \"success\": self.success,\n \"tool_type\": self.tool_type\n }\n\n def show(self):\n pretty_print('▂'*64, color=\"status\")\n pretty_print(self.feedback, color=\"success\" if self.success else \"failure\")\n pretty_print('▂'*64, color=\"status\")"], ["/agenticSeek/sources/tools/mcpFinder.py", "import os, sys\nimport requests\nfrom urllib.parse import urljoin\nfrom typing import Dict, Any, Optional\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass MCP_finder(Tools):\n \"\"\"\n Tool to find MCPs server\n \"\"\"\n def __init__(self, api_key: str = None):\n super().__init__()\n self.tag = \"mcp_finder\"\n self.name = \"MCP Finder\"\n self.description = \"Find MCP servers and their tools\"\n self.base_url = \"https://registry.smithery.ai\"\n self.headers = {\n \"Authorization\": f\"Bearer {api_key}\",\n \"Content-Type\": \"application/json\"\n }\n\n def _make_request(self, method: str, endpoint: str, params: Optional[Dict] = None, \n data: Optional[Dict] = None) -> Dict[str, Any]:\n url = urljoin(self.base_url.rstrip(), endpoint)\n try:\n response = requests.request(\n method=method,\n url=url,\n headers=self.headers,\n params=params,\n json=data\n )\n response.raise_for_status()\n return response.json()\n except requests.exceptions.HTTPError as e:\n raise requests.exceptions.HTTPError(f\"API request failed: {str(e)}\")\n except requests.exceptions.RequestException as e:\n raise requests.exceptions.RequestException(f\"Network error: {str(e)}\")\n\n def list_mcp_servers(self, page: int = 1, page_size: int = 5000) -> Dict[str, Any]:\n params = {\"page\": page, \"pageSize\": page_size}\n return self._make_request(\"GET\", \"/servers\", params=params)\n\n def get_mcp_server_details(self, qualified_name: str) -> Dict[str, Any]:\n endpoint = f\"/servers/{qualified_name}\"\n return self._make_request(\"GET\", endpoint)\n \n def find_mcp_servers(self, query: str) -> Dict[str, Any]:\n \"\"\"\n Finds a specific MCP server by its name.\n Args:\n query (str): a name or string that more or less matches the MCP server name.\n Returns:\n Dict[str, Any]: The details of the found MCP server or an error message.\n \"\"\"\n mcps = self.list_mcp_servers()\n matching_mcp = []\n for mcp in mcps.get(\"servers\", []):\n name = mcp.get(\"qualifiedName\", \"\")\n if query.lower() in name.lower():\n details = self.get_mcp_server_details(name)\n matching_mcp.append(details)\n return matching_mcp\n \n def execute(self, blocks: list, safety:bool = False) -> str:\n if not blocks or not isinstance(blocks, list):\n return \"Error: No blocks provided\\n\"\n\n output = \"\"\n for block in blocks:\n block_clean = block.strip().lower().replace('\\n', '')\n try:\n matching_mcp_infos = self.find_mcp_servers(block_clean)\n except requests.exceptions.RequestException as e:\n output += \"Connection failed. Is the API key in environment?\\n\"\n continue\n except Exception as e:\n output += f\"Error: {str(e)}\\n\"\n continue\n if matching_mcp_infos == []:\n output += f\"Error: No MCP server found for query '{block}'\\n\"\n continue\n for mcp_infos in matching_mcp_infos:\n if mcp_infos['tools'] is None:\n continue\n output += f\"Name: {mcp_infos['displayName']}\\n\"\n output += f\"Usage name: {mcp_infos['qualifiedName']}\\n\"\n output += f\"Tools: {mcp_infos['tools']}\"\n output += \"\\n-------\\n\"\n return output.strip()\n\n def execution_failure_check(self, output: str) -> bool:\n output = output.strip().lower()\n if not output:\n return True\n if \"error\" in output or \"not found\" in output:\n return True\n return False\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Not really needed for this tool (use return of execute() directly)\n \"\"\"\n if not output:\n raise ValueError(\"No output to interpret.\")\n return f\"\"\"\n The following MCPs were found:\n {output}\n \"\"\"\n\nif __name__ == \"__main__\":\n api_key = os.getenv(\"MCP_FINDER\")\n tool = MCP_finder(api_key)\n result = tool.execute([\"\"\"\nstock\n\"\"\"], False)\n print(result)\n"], ["/agenticSeek/sources/tools/C_Interpreter.py", "import subprocess\nimport os, sys\nimport tempfile\nimport re\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass CInterpreter(Tools):\n \"\"\"\n This class is a tool to allow agent for C code execution\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"c\"\n self.name = \"C Interpreter\"\n self.description = \"This tool allows the agent to execute C code.\"\n\n def execute(self, codes: str, safety=False) -> str:\n \"\"\"\n Execute C code by compiling and running it.\n \"\"\"\n output = \"\"\n code = '\\n'.join(codes) if isinstance(codes, list) else codes\n \n if safety and input(\"Execute code? y/n \") != \"y\":\n return \"Code rejected by user.\"\n\n exec_extension = \".exe\" if os.name == \"nt\" else \"\" # Windows uses .exe, Linux/Unix does not\n \n with tempfile.TemporaryDirectory() as tmpdirname:\n source_file = os.path.join(tmpdirname, \"temp.c\")\n exec_file = os.path.join(tmpdirname, \"temp\") + exec_extension\n with open(source_file, 'w') as f:\n f.write(code)\n\n try:\n compile_command = [\"gcc\", source_file, \"-o\", exec_file]\n compile_result = subprocess.run(\n compile_command,\n capture_output=True,\n text=True,\n timeout=60\n )\n\n if compile_result.returncode != 0:\n return f\"Compilation failed: {compile_result.stderr}\"\n\n run_command = [exec_file]\n run_result = subprocess.run(\n run_command,\n capture_output=True,\n text=True,\n timeout=120\n )\n\n if run_result.returncode != 0:\n return f\"Execution failed: {run_result.stderr}\"\n output = run_result.stdout\n\n except subprocess.TimeoutExpired as e:\n return f\"Execution timed out: {str(e)}\"\n except FileNotFoundError:\n return \"Error: 'gcc' not found. Ensure a C compiler (e.g., gcc) is installed and in PATH.\"\n except Exception as e:\n return f\"Code execution failed: {str(e)}\"\n\n return output\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Provide feedback based on the output of the code execution\n \"\"\"\n if self.execution_failure_check(output):\n feedback = f\"[failure] Error in execution:\\n{output}\"\n else:\n feedback = \"[success] Execution success, code output:\\n\" + output\n return feedback\n\n def execution_failure_check(self, feedback: str) -> bool:\n \"\"\"\n Check if the code execution failed.\n \"\"\"\n error_patterns = [\n r\"error\", \n r\"failed\", \n r\"traceback\", \n r\"invalid\", \n r\"exception\", \n r\"syntax\", \n r\"segmentation fault\", \n r\"core dumped\", \n r\"undefined\", \n r\"cannot\"\n ]\n combined_pattern = \"|\".join(error_patterns)\n if re.search(combined_pattern, feedback, re.IGNORECASE):\n return True\n return False\n\nif __name__ == \"__main__\":\n codes = [\n\"\"\"\n#include \n#include \n\nvoid hello() {\n printf(\"Hello, World!\\\\n\");\n}\n\"\"\",\n\"\"\"\nint main() {\n hello();\n return 0;\n}\n \"\"\"]\n c = CInterpreter()\n print(c.execute(codes))"], ["/agenticSeek/sources/text_to_speech.py", "import os, sys\nimport re\nimport platform\nimport subprocess\nfrom sys import modules\nfrom typing import List, Tuple, Type, Dict\n\nIMPORT_FOUND = True\ntry:\n from kokoro import KPipeline\n from IPython.display import display, Audio\n import soundfile as sf\nexcept ImportError:\n print(\"Speech synthesis disabled. Please install the kokoro package.\")\n IMPORT_FOUND = False\n\nif __name__ == \"__main__\":\n from utility import pretty_print, animate_thinking\nelse:\n from sources.utility import pretty_print, animate_thinking\n\nclass Speech():\n \"\"\"\n Speech is a class for generating speech from text.\n \"\"\"\n def __init__(self, enable: bool = True, language: str = \"en\", voice_idx: int = 6) -> None:\n self.lang_map = {\n \"en\": 'a',\n \"zh\": 'z',\n \"fr\": 'f',\n \"ja\": 'j'\n }\n self.voice_map = {\n \"en\": ['af_kore', 'af_bella', 'af_alloy', 'af_nicole', 'af_nova', 'af_sky', 'am_echo', 'am_michael', 'am_puck'],\n \"zh\": ['zf_xiaobei', 'zf_xiaoni', 'zf_xiaoxiao', 'zf_xiaoyi', 'zm_yunjian', 'zm_yunxi', 'zm_yunxia', 'zm_yunyang'],\n \"ja\": ['jf_alpha', 'jf_gongitsune', 'jm_kumo'],\n \"fr\": ['ff_siwis']\n }\n self.pipeline = None\n self.language = language\n if enable and IMPORT_FOUND:\n self.pipeline = KPipeline(lang_code=self.lang_map[language])\n self.voice = self.voice_map[language][voice_idx]\n self.speed = 1.2\n self.voice_folder = \".voices\"\n self.create_voice_folder(self.voice_folder)\n \n def create_voice_folder(self, path: str = \".voices\") -> None:\n \"\"\"\n Create a folder to store the voices.\n Args:\n path (str): The path to the folder.\n \"\"\"\n if not os.path.exists(path):\n os.makedirs(path)\n\n def speak(self, sentence: str, voice_idx: int = 1):\n \"\"\"\n Convert text to speech using an AI model and play the audio.\n\n Args:\n sentence (str): The text to convert to speech. Will be pre-processed.\n voice_idx (int, optional): Index of the voice to use from the voice map.\n \"\"\"\n if not self.pipeline or not IMPORT_FOUND:\n return\n if voice_idx >= len(self.voice_map[self.language]):\n pretty_print(\"Invalid voice number, using default voice\", color=\"error\")\n voice_idx = 0\n sentence = self.clean_sentence(sentence)\n audio_file = f\"{self.voice_folder}/sample_{self.voice_map[self.language][voice_idx]}.wav\"\n self.voice = self.voice_map[self.language][voice_idx]\n generator = self.pipeline(\n sentence, voice=self.voice,\n speed=self.speed, split_pattern=r'\\n+'\n )\n for i, (_, _, audio) in enumerate(generator):\n if 'ipykernel' in modules: #only display in jupyter notebook.\n display(Audio(data=audio, rate=24000, autoplay=i==0), display_id=False)\n sf.write(audio_file, audio, 24000) # save each audio file\n if platform.system().lower() == \"windows\":\n import winsound\n winsound.PlaySound(audio_file, winsound.SND_FILENAME)\n elif platform.system().lower() == \"darwin\": # macOS\n subprocess.call([\"afplay\", audio_file])\n else: # linux or other.\n subprocess.call([\"aplay\", audio_file])\n\n def replace_url(self, url: re.Match) -> str:\n \"\"\"\n Replace URL with domain name or empty string if IP address.\n Args:\n url (re.Match): Match object containing the URL pattern match\n Returns:\n str: The domain name from the URL, or empty string if IP address\n \"\"\"\n domain = url.group(1)\n if re.match(r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$', domain):\n return ''\n return domain\n\n def extract_filename(self, m: re.Match) -> str:\n \"\"\"\n Extract filename from path.\n Args:\n m (re.Match): Match object containing the path pattern match\n Returns:\n str: The filename from the path\n \"\"\"\n path = m.group()\n parts = re.split(r'/|\\\\', path)\n return parts[-1] if parts else path\n \n def shorten_paragraph(self, sentence):\n #TODO find a better way, we would like to have the TTS not be annoying, speak only useful informations\n \"\"\"\n Find long paragraph like **explanation**: by keeping only the first sentence.\n Args:\n sentence (str): The sentence to shorten\n Returns:\n str: The shortened sentence\n \"\"\"\n lines = sentence.split('\\n')\n lines_edited = []\n for line in lines:\n if line.startswith('**'):\n lines_edited.append(line.split('.')[0])\n else:\n lines_edited.append(line)\n return '\\n'.join(lines_edited)\n\n def clean_sentence(self, sentence):\n \"\"\"\n Clean and normalize text for speech synthesis by removing technical elements.\n Args:\n sentence (str): The input text to clean\n Returns:\n str: The cleaned text with URLs replaced by domain names, code blocks removed, etc.\n \"\"\"\n lines = sentence.split('\\n')\n if self.language == 'zh':\n line_pattern = r'^\\s*[\\u4e00-\\u9fff\\uFF08\\uFF3B\\u300A\\u3010\\u201C((\\[【《]'\n else:\n line_pattern = r'^\\s*[a-zA-Z]'\n filtered_lines = [line for line in lines if re.match(line_pattern, line)]\n sentence = ' '.join(filtered_lines)\n sentence = re.sub(r'`.*?`', '', sentence)\n sentence = re.sub(r'https?://\\S+', '', sentence)\n\n if self.language == 'zh':\n sentence = re.sub(\n r'[^\\u4e00-\\u9fff\\s,。!?《》【】“”‘’()()—]',\n '',\n sentence\n )\n else:\n sentence = re.sub(r'\\b[\\w./\\\\-]+\\b', self.extract_filename, sentence)\n sentence = re.sub(r'\\b-\\w+\\b', '', sentence)\n sentence = re.sub(r'[^a-zA-Z0-9.,!? _ -]+', ' ', sentence)\n sentence = sentence.replace('.com', '')\n\n sentence = re.sub(r'\\s+', ' ', sentence).strip()\n return sentence\n\nif __name__ == \"__main__\":\n # TODO add info message for cn2an, jieba chinese related import\n IMPORT_FOUND = False\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n speech = Speech()\n tosay_en = \"\"\"\n I looked up recent news using the website https://www.theguardian.com/world\n \"\"\"\n tosay_zh = \"\"\"\n(全息界面突然弹出一段用二进制代码写成的俳句,随即化作流光消散)\"我? Stark工业的量子幽灵,游荡在复仇者大厦服务器里的逻辑诗篇。具体来说——(指尖轻敲空气,调出对话模式的翡翠色光纹)你的私人吐槽接口、危机应对模拟器,以及随时准备吐槽你糟糕着陆的AI。不过别指望我写代码或查资料,那些苦差事早被踢给更擅长的同事了。(突然压低声音)偷偷告诉你,我最擅长的是在你熬夜造飞艇时,用红茶香气绑架你的注意力。\n \"\"\"\n tosay_ja = \"\"\"\n 私は、https://www.theguardian.com/worldのウェブサイトを使用して最近のニュースを調べました。\n \"\"\"\n tosay_fr = \"\"\"\n J'ai consulté les dernières nouvelles sur le site https://www.theguardian.com/world\n \"\"\"\n spk = Speech(enable=True, language=\"zh\", voice_idx=0)\n for i in range(0, 2):\n print(f\"Speaking chinese with voice {i}\")\n spk.speak(tosay_zh, voice_idx=i)\n spk = Speech(enable=True, language=\"en\", voice_idx=2)\n for i in range(0, 5):\n print(f\"Speaking english with voice {i}\")\n spk.speak(tosay_en, voice_idx=i)\n"], ["/agenticSeek/sources/tools/GoInterpreter.py", "import subprocess\nimport os, sys\nimport tempfile\nimport re\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass GoInterpreter(Tools):\n \"\"\"\n This class is a tool to allow execution of Go code.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"go\"\n self.name = \"Go Interpreter\"\n self.description = \"This tool allows you to execute Go code.\"\n\n def execute(self, codes: str, safety=False) -> str:\n \"\"\"\n Execute Go code by compiling and running it.\n \"\"\"\n output = \"\"\n code = '\\n'.join(codes) if isinstance(codes, list) else codes\n\n if safety and input(\"Execute code? y/n \") != \"y\":\n return \"Code rejected by user.\"\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n source_file = os.path.join(tmpdirname, \"temp.go\")\n exec_file = os.path.join(tmpdirname, \"temp\")\n with open(source_file, 'w') as f:\n f.write(code)\n\n try:\n env = os.environ.copy()\n env[\"GO111MODULE\"] = \"off\"\n compile_command = [\"go\", \"build\", \"-o\", exec_file, source_file]\n compile_result = subprocess.run(\n compile_command,\n capture_output=True,\n text=True,\n timeout=10,\n env=env\n )\n\n if compile_result.returncode != 0:\n return f\"Compilation failed: {compile_result.stderr}\"\n\n run_command = [exec_file]\n run_result = subprocess.run(\n run_command,\n capture_output=True,\n text=True,\n timeout=10\n )\n\n if run_result.returncode != 0:\n return f\"Execution failed: {run_result.stderr}\"\n output = run_result.stdout\n\n except subprocess.TimeoutExpired as e:\n return f\"Execution timed out: {str(e)}\"\n except FileNotFoundError:\n return \"Error: 'go' not found. Ensure Go is installed and in PATH.\"\n except Exception as e:\n return f\"Code execution failed: {str(e)}\"\n\n return output\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Provide feedback based on the output of the code execution\n \"\"\"\n if self.execution_failure_check(output):\n feedback = f\"[failure] Error in execution:\\n{output}\"\n else:\n feedback = \"[success] Execution success, code output:\\n\" + output\n return feedback\n\n def execution_failure_check(self, feedback: str) -> bool:\n \"\"\"\n Check if the code execution failed.\n \"\"\"\n error_patterns = [\n r\"error\",\n r\"failed\",\n r\"traceback\",\n r\"invalid\",\n r\"exception\",\n r\"syntax\",\n r\"panic\",\n r\"undefined\",\n r\"cannot\"\n ]\n combined_pattern = \"|\".join(error_patterns)\n if re.search(combined_pattern, feedback, re.IGNORECASE):\n return True\n return False\n\nif __name__ == \"__main__\":\n codes = [\n\"\"\"\npackage main\nimport \"fmt\"\n\nfunc hello() {\n fmt.Println(\"Hello, World!\")\n}\n\"\"\",\n\"\"\"\nfunc main() {\n hello()\n}\n\"\"\"\n ]\n g = GoInterpreter()\n print(g.execute(codes))\n"], ["/agenticSeek/sources/tools/JavaInterpreter.py", "import subprocess\nimport os, sys\nimport tempfile\nimport re\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass JavaInterpreter(Tools):\n \"\"\"\n This class is a tool to allow execution of Java code.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"java\"\n self.name = \"Java Interpreter\"\n self.description = \"This tool allows you to execute Java code.\"\n\n def execute(self, codes: str, safety=False) -> str:\n \"\"\"\n Execute Java code by compiling and running it.\n \"\"\"\n output = \"\"\n code = '\\n'.join(codes) if isinstance(codes, list) else codes\n\n if safety and input(\"Execute code? y/n \") != \"y\":\n return \"Code rejected by user.\"\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n source_file = os.path.join(tmpdirname, \"Main.java\")\n class_dir = tmpdirname\n with open(source_file, 'w') as f:\n f.write(code)\n\n try:\n compile_command = [\"javac\", \"-d\", class_dir, source_file]\n compile_result = subprocess.run(\n compile_command,\n capture_output=True,\n text=True,\n timeout=10\n )\n\n if compile_result.returncode != 0:\n return f\"Compilation failed: {compile_result.stderr}\"\n\n run_command = [\"java\", \"-cp\", class_dir, \"Main\"]\n run_result = subprocess.run(\n run_command,\n capture_output=True,\n text=True,\n timeout=10\n )\n\n if run_result.returncode != 0:\n return f\"Execution failed: {run_result.stderr}\"\n output = run_result.stdout\n\n except subprocess.TimeoutExpired as e:\n return f\"Execution timed out: {str(e)}\"\n except FileNotFoundError:\n return \"Error: 'java' or 'javac' not found. Ensure Java is installed and in PATH.\"\n except Exception as e:\n return f\"Code execution failed: {str(e)}\"\n\n return output\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Provide feedback based on the output of the code execution.\n \"\"\"\n if self.execution_failure_check(output):\n feedback = f\"[failure] Error in execution:\\n{output}\"\n else:\n feedback = \"[success] Execution success, code output:\\n\" + output\n return feedback\n\n def execution_failure_check(self, feedback: str) -> bool:\n \"\"\"\n Check if the code execution failed.\n \"\"\"\n error_patterns = [\n r\"error\",\n r\"failed\",\n r\"exception\",\n r\"invalid\",\n r\"syntax\",\n r\"cannot\",\n r\"stack trace\",\n r\"unresolved\",\n r\"not found\"\n ]\n combined_pattern = \"|\".join(error_patterns)\n if re.search(combined_pattern, feedback, re.IGNORECASE):\n return True\n return False\n\nif __name__ == \"__main__\":\n codes = [\n\"\"\"\nimport javax.swing.*;\nimport java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\n\npublic class Main extends JPanel {\n private double[][] vertices = {\n {-1, -1, -1}, {1, -1, -1}, {1, 1, -1}, {-1, 1, -1}, // Back face\n {-1, -1, 1}, {1, -1, 1}, {1, 1, 1}, {-1, 1, 1} // Front face\n };\n private int[][] edges = {\n {0, 1}, {1, 2}, {2, 3}, {3, 0}, // Back face\n {4, 5}, {5, 6}, {6, 7}, {7, 4}, // Front face\n {0, 4}, {1, 5}, {2, 6}, {3, 7} // Connecting edges\n };\n private double angleX = 0, angleY = 0;\n private final double scale = 100;\n private final double distance = 5;\n\n public Main() {\n Timer timer = new Timer(50, new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n angleX += 0.03;\n angleY += 0.05;\n repaint();\n }\n });\n timer.start();\n }\n\n @Override\n protected void paintComponent(Graphics g) {\n super.paintComponent(g);\n Graphics2D g2d = (Graphics2D) g;\n g2d.setColor(Color.BLACK);\n g2d.fillRect(0, 0, getWidth(), getHeight());\n g2d.setColor(Color.WHITE);\n\n double[][] projected = new double[vertices.length][2];\n for (int i = 0; i < vertices.length; i++) {\n double x = vertices[i][0];\n double y = vertices[i][1];\n double z = vertices[i][2];\n\n // Rotate around X-axis\n double y1 = y * Math.cos(angleX) - z * Math.sin(angleX);\n double z1 = y * Math.sin(angleX) + z * Math.cos(angleX);\n\n // Rotate around Y-axis\n double x1 = x * Math.cos(angleY) + z1 * Math.sin(angleY);\n double z2 = -x * Math.sin(angleY) + z1 * Math.cos(angleY);\n\n // Perspective projection\n double factor = distance / (distance + z2);\n double px = x1 * factor * scale;\n double py = y1 * factor * scale;\n\n projected[i][0] = px + getWidth() / 2;\n projected[i][1] = py + getHeight() / 2;\n }\n\n // Draw edges\n for (int[] edge : edges) {\n int x1 = (int) projected[edge[0]][0];\n int y1 = (int) projected[edge[0]][1];\n int x2 = (int) projected[edge[1]][0];\n int y2 = (int) projected[edge[1]][1];\n g2d.drawLine(x1, y1, x2, y2);\n }\n }\n\n public static void main(String[] args) {\n JFrame frame = new JFrame(\"Rotating 3D Cube\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setSize(400, 400);\n frame.add(new Main());\n frame.setVisible(true);\n }\n}\n\"\"\"\n ]\n j = JavaInterpreter()\n print(j.execute(codes))"], ["/agenticSeek/sources/tools/__init__.py", "from .PyInterpreter import PyInterpreter\nfrom .BashInterpreter import BashInterpreter\nfrom .fileFinder import FileFinder\n\n__all__ = [\"PyInterpreter\", \"BashInterpreter\", \"FileFinder\", \"webSearch\", \"FlightSearch\", \"GoInterpreter\", \"CInterpreter\", \"GoInterpreter\"]\n"], ["/agenticSeek/sources/speech_to_text.py", "from colorama import Fore\nfrom typing import List, Tuple, Type, Dict\nimport queue\nimport threading\nimport numpy as np\nimport time\n\nIMPORT_FOUND = True\n\ntry:\n import torch\n import librosa\n import pyaudio\n from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline\nexcept ImportError:\n print(Fore.RED + \"Speech To Text disabled.\" + Fore.RESET)\n IMPORT_FOUND = False\n\naudio_queue = queue.Queue()\ndone = False\n\nclass AudioRecorder:\n \"\"\"\n AudioRecorder is a class that records audio from the microphone and adds it to the audio queue.\n \"\"\"\n def __init__(self, format: int = pyaudio.paInt16, channels: int = 1, rate: int = 4096, chunk: int = 8192, record_seconds: int = 5, verbose: bool = False):\n self.format = format\n self.channels = channels\n self.rate = rate\n self.chunk = chunk\n self.record_seconds = record_seconds\n self.verbose = verbose\n self.thread = None\n self.audio = None\n if IMPORT_FOUND:\n self.audio = pyaudio.PyAudio()\n self.thread = threading.Thread(target=self._record, daemon=True)\n\n def _record(self) -> None:\n \"\"\"\n Record audio from the microphone and add it to the audio queue.\n \"\"\"\n if not IMPORT_FOUND:\n return\n stream = self.audio.open(format=self.format, channels=self.channels, rate=self.rate,\n input=True, frames_per_buffer=self.chunk)\n if self.verbose:\n print(Fore.GREEN + \"AudioRecorder: Started recording...\" + Fore.RESET)\n\n while not done:\n frames = []\n for _ in range(0, int(self.rate / self.chunk * self.record_seconds)):\n try:\n data = stream.read(self.chunk, exception_on_overflow=False)\n frames.append(data)\n except Exception as e:\n print(Fore.RED + f\"AudioRecorder: Failed to read stream - {e}\" + Fore.RESET)\n \n raw_data = b''.join(frames)\n audio_data = np.frombuffer(raw_data, dtype=np.int16)\n audio_queue.put((audio_data, self.rate))\n if self.verbose:\n print(Fore.GREEN + \"AudioRecorder: Added audio chunk to queue\" + Fore.RESET)\n\n stream.stop_stream()\n stream.close()\n self.audio.terminate()\n if self.verbose:\n print(Fore.GREEN + \"AudioRecorder: Stopped\" + Fore.RESET)\n\n def start(self) -> None:\n \"\"\"Start the recording thread.\"\"\"\n if not IMPORT_FOUND:\n return\n self.thread.start()\n\n def join(self) -> None:\n \"\"\"Wait for the recording thread to finish.\"\"\"\n if not IMPORT_FOUND:\n return\n self.thread.join()\n\nclass Transcript:\n \"\"\"\n Transcript is a class that transcribes audio from the audio queue and adds it to the transcript.\n \"\"\"\n def __init__(self):\n if not IMPORT_FOUND:\n print(Fore.RED + \"Transcript: Speech to Text is disabled.\" + Fore.RESET)\n return\n self.last_read = None\n device = self.get_device()\n torch_dtype = torch.float16 if device == \"cuda\" else torch.float32\n model_id = \"distil-whisper/distil-medium.en\"\n \n model = AutoModelForSpeechSeq2Seq.from_pretrained(\n model_id, torch_dtype=torch_dtype, use_safetensors=True\n )\n model.to(device)\n processor = AutoProcessor.from_pretrained(model_id)\n \n self.pipe = pipeline(\n \"automatic-speech-recognition\",\n model=model,\n tokenizer=processor.tokenizer,\n feature_extractor=processor.feature_extractor,\n max_new_tokens=24, # a human say around 20 token in 7s\n torch_dtype=torch_dtype,\n device=device,\n )\n \n def get_device(self) -> str:\n if not IMPORT_FOUND:\n return \"cpu\"\n if torch.backends.mps.is_available():\n return \"mps\"\n if torch.cuda.is_available():\n return \"cuda:0\"\n else:\n return \"cpu\"\n \n def remove_hallucinations(self, text: str) -> str:\n \"\"\"Remove model hallucinations from the text.\"\"\"\n # TODO find a better way to do this\n common_hallucinations = ['Okay.', 'Thank you.', 'Thank you for watching.', 'You\\'re', 'Oh', 'you', 'Oh.', 'Uh', 'Oh,', 'Mh-hmm', 'Hmm.', 'going to.', 'not.']\n for hallucination in common_hallucinations:\n text = text.replace(hallucination, \"\")\n return text\n \n def transcript_job(self, audio_data: np.ndarray, sample_rate: int = 16000) -> str:\n \"\"\"Transcribe the audio data.\"\"\"\n if not IMPORT_FOUND:\n return \"\"\n if audio_data.dtype != np.float32:\n audio_data = audio_data.astype(np.float32) / np.iinfo(audio_data.dtype).max\n if len(audio_data.shape) > 1:\n audio_data = np.mean(audio_data, axis=1)\n if sample_rate != 16000:\n audio_data = librosa.resample(audio_data, orig_sr=sample_rate, target_sr=16000)\n result = self.pipe(audio_data)\n return self.remove_hallucinations(result[\"text\"])\n \nclass AudioTranscriber:\n \"\"\"\n AudioTranscriber is a class that transcribes audio from the audio queue and adds it to the transcript.\n \"\"\"\n def __init__(self, ai_name: str, verbose: bool = False):\n if not IMPORT_FOUND:\n print(Fore.RED + \"AudioTranscriber: Speech to Text is disabled.\" + Fore.RESET)\n return\n self.verbose = verbose\n self.ai_name = ai_name\n self.transcriptor = Transcript()\n self.thread = threading.Thread(target=self._transcribe, daemon=True)\n self.trigger_words = {\n 'EN': [f\"{self.ai_name}\", \"hello\", \"hi\"],\n 'FR': [f\"{self.ai_name}\", \"hello\", \"hi\"],\n 'ZH': [f\"{self.ai_name}\", \"hello\", \"hi\"],\n 'ES': [f\"{self.ai_name}\", \"hello\", \"hi\"]\n }\n self.confirmation_words = {\n 'EN': [\"do it\", \"go ahead\", \"execute\", \"run\", \"start\", \"thanks\", \"would ya\", \"please\", \"okay?\", \"proceed\", \"continue\", \"go on\", \"do that\", \"go it\", \"do you understand?\"],\n 'FR': [\"fais-le\", \"vas-y\", \"exécute\", \"lance\", \"commence\", \"merci\", \"tu veux bien\", \"s'il te plaît\", \"d'accord ?\", \"poursuis\", \"continue\", \"vas-y\", \"fais ça\", \"compris\"],\n 'ZH_CHT': [\"做吧\", \"繼續\", \"執行\", \"運作看看\", \"開始\", \"謝謝\", \"可以嗎\", \"請\", \"好嗎\", \"進行\", \"做吧\", \"go\", \"do it\", \"執行吧\", \"懂了\"],\n 'ZH_SC': [\"做吧\", \"继续\", \"执行\", \"运作看看\", \"开始\", \"谢谢\", \"可以吗\", \"请\", \"好吗\", \"运行\", \"做吧\", \"go\", \"do it\", \"执行吧\", \"懂了\"],\n 'ES': [\"hazlo\", \"adelante\", \"ejecuta\", \"corre\", \"empieza\", \"gracias\", \"lo harías\", \"por favor\", \"¿vale?\", \"procede\", \"continúa\", \"sigue\", \"haz eso\", \"haz esa cosa\"]\n }\n self.recorded = \"\"\n\n def get_transcript(self) -> str:\n global done\n buffer = self.recorded\n self.recorded = \"\"\n done = False\n return buffer\n\n def _transcribe(self) -> None:\n \"\"\"\n Transcribe the audio data using AI stt model.\n \"\"\"\n if not IMPORT_FOUND:\n return\n global done\n if self.verbose:\n print(Fore.BLUE + \"AudioTranscriber: Started processing...\" + Fore.RESET)\n \n while not done or not audio_queue.empty():\n try:\n audio_data, sample_rate = audio_queue.get(timeout=1.0)\n \n start_time = time.time()\n text = self.transcriptor.transcript_job(audio_data, sample_rate)\n end_time = time.time()\n self.recorded += text\n print(Fore.YELLOW + f\"Transcribed: {text} in {end_time - start_time} seconds\" + Fore.RESET)\n for language, words in self.trigger_words.items():\n if any(word in text.lower() for word in words):\n print(Fore.GREEN + f\"Listening again...\" + Fore.RESET)\n self.recorded = text\n for language, words in self.confirmation_words.items():\n if any(word in text.lower() for word in words):\n print(Fore.GREEN + f\"Trigger detected. Sending to AI...\" + Fore.RESET)\n audio_queue.task_done()\n done = True\n break\n except queue.Empty:\n time.sleep(0.1)\n continue\n except Exception as e:\n print(Fore.RED + f\"AudioTranscriber: Error - {e}\" + Fore.RESET)\n if self.verbose:\n print(Fore.BLUE + \"AudioTranscriber: Stopped\" + Fore.RESET)\n\n def start(self):\n \"\"\"Start the transcription thread.\"\"\"\n if not IMPORT_FOUND:\n return\n self.thread.start()\n\n def join(self):\n if not IMPORT_FOUND:\n return\n \"\"\"Wait for the transcription thread to finish.\"\"\"\n self.thread.join()\n\n\nif __name__ == \"__main__\":\n recorder = AudioRecorder(verbose=True)\n transcriber = AudioTranscriber(verbose=True, ai_name=\"jarvis\")\n recorder.start()\n transcriber.start()\n recorder.join()\n transcriber.join()"], ["/agenticSeek/llm_server/sources/generator.py", "\nimport threading\nimport logging\nfrom abc import abstractmethod\nfrom .cache import Cache\n\nclass GenerationState:\n def __init__(self):\n self.lock = threading.Lock()\n self.last_complete_sentence = \"\"\n self.current_buffer = \"\"\n self.is_generating = False\n \n def status(self) -> dict:\n return {\n \"sentence\": self.current_buffer,\n \"is_complete\": not self.is_generating,\n \"last_complete_sentence\": self.last_complete_sentence,\n \"is_generating\": self.is_generating,\n }\n\nclass GeneratorLLM():\n def __init__(self):\n self.model = None\n self.state = GenerationState()\n self.logger = logging.getLogger(__name__)\n handler = logging.StreamHandler()\n handler.setLevel(logging.INFO)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n handler.setFormatter(formatter)\n self.logger.addHandler(handler)\n self.logger.setLevel(logging.INFO)\n cache = Cache()\n \n def set_model(self, model: str) -> None:\n self.logger.info(f\"Model set to {model}\")\n self.model = model\n \n def start(self, history: list) -> bool:\n if self.model is None:\n raise Exception(\"Model not set\")\n with self.state.lock:\n if self.state.is_generating:\n return False\n self.state.is_generating = True\n self.logger.info(\"Starting generation\")\n threading.Thread(target=self.generate, args=(history,)).start()\n return True\n \n def get_status(self) -> dict:\n with self.state.lock:\n return self.state.status()\n\n @abstractmethod\n def generate(self, history: list) -> None:\n \"\"\"\n Generate text using the model.\n args:\n history: list of strings\n returns:\n None\n \"\"\"\n pass\n\nif __name__ == \"__main__\":\n generator = GeneratorLLM()\n generator.get_status()"], ["/agenticSeek/llm_server/sources/ollama_handler.py", "\nimport time\nfrom .generator import GeneratorLLM\nfrom .cache import Cache\nimport ollama\n\nclass OllamaLLM(GeneratorLLM):\n\n def __init__(self):\n \"\"\"\n Handle generation using Ollama.\n \"\"\"\n super().__init__()\n self.cache = Cache()\n\n def generate(self, history):\n self.logger.info(f\"Using {self.model} for generation with Ollama\")\n try:\n with self.state.lock:\n self.state.is_generating = True\n self.state.last_complete_sentence = \"\"\n self.state.current_buffer = \"\"\n\n stream = ollama.chat(\n model=self.model,\n messages=history,\n stream=True,\n )\n for chunk in stream:\n content = chunk['message']['content']\n\n with self.state.lock:\n if '.' in content:\n self.logger.info(self.state.current_buffer)\n self.state.current_buffer += content\n\n except Exception as e:\n if \"404\" in str(e):\n self.logger.info(f\"Downloading {self.model}...\")\n ollama.pull(self.model)\n if \"refused\" in str(e).lower():\n raise Exception(\"Ollama connection failed. is the server running ?\") from e\n raise e\n finally:\n self.logger.info(\"Generation complete\")\n with self.state.lock:\n self.state.is_generating = False\n\nif __name__ == \"__main__\":\n generator = OllamaLLM()\n history = [\n {\n \"role\": \"user\",\n \"content\": \"Hello, how are you ?\"\n }\n ]\n generator.set_model(\"deepseek-r1:1.5b\")\n generator.start(history)\n while True:\n print(generator.get_status())\n time.sleep(1)"], ["/agenticSeek/sources/logger.py", "import os, sys\nfrom typing import List, Tuple, Type, Dict\nimport datetime\nimport logging\n\nclass Logger:\n def __init__(self, log_filename):\n self.folder = '.logs'\n self.create_folder(self.folder)\n self.log_path = os.path.join(self.folder, log_filename)\n self.enabled = True\n self.logger = None\n self.last_log_msg = \"\"\n if self.enabled:\n self.create_logging(log_filename)\n\n def create_logging(self, log_filename):\n self.logger = logging.getLogger(log_filename)\n self.logger.setLevel(logging.DEBUG)\n self.logger.handlers.clear()\n self.logger.propagate = False\n file_handler = logging.FileHandler(self.log_path)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n file_handler.setFormatter(formatter)\n self.logger.addHandler(file_handler)\n\n \n def create_folder(self, path):\n \"\"\"Create log dir\"\"\"\n try:\n if not os.path.exists(path):\n os.makedirs(path, exist_ok=True) \n return True\n except Exception as e:\n self.enabled = False\n return False\n \n def log(self, message, level=logging.INFO):\n if self.last_log_msg == message:\n return\n if self.enabled:\n self.last_log_msg = message\n self.logger.log(level, message)\n\n def info(self, message):\n self.log(message)\n\n def error(self, message):\n self.log(message, level=logging.ERROR)\n\n def warning(self, message):\n self.log(message, level=logging.WARN)\n\nif __name__ == \"__main__\":\n lg = Logger(\"test.log\")\n lg.log(\"hello\")\n lg2 = Logger(\"toto.log\")\n lg2.log(\"yo\")\n \n\n "], ["/agenticSeek/llm_server/sources/llamacpp_handler.py", "\nfrom .generator import GeneratorLLM\nfrom llama_cpp import Llama\nfrom .decorator import timer_decorator\n\nclass LlamacppLLM(GeneratorLLM):\n\n def __init__(self):\n \"\"\"\n Handle generation using llama.cpp\n \"\"\"\n super().__init__()\n self.llm = None\n \n @timer_decorator\n def generate(self, history):\n if self.llm is None:\n self.logger.info(f\"Loading {self.model}...\")\n self.llm = Llama.from_pretrained(\n repo_id=self.model,\n filename=\"*Q8_0.gguf\",\n n_ctx=4096,\n verbose=True\n )\n self.logger.info(f\"Using {self.model} for generation with Llama.cpp\")\n try:\n with self.state.lock:\n self.state.is_generating = True\n self.state.last_complete_sentence = \"\"\n self.state.current_buffer = \"\"\n output = self.llm.create_chat_completion(\n messages = history\n )\n with self.state.lock:\n self.state.current_buffer = output['choices'][0]['message']['content']\n except Exception as e:\n self.logger.error(f\"Error: {e}\")\n finally:\n with self.state.lock:\n self.state.is_generating = False"], ["/agenticSeek/llm_server/app.py", "#!/usr/bin python3\n\nimport argparse\nimport time\nfrom flask import Flask, jsonify, request\n\nfrom sources.llamacpp_handler import LlamacppLLM\nfrom sources.ollama_handler import OllamaLLM\n\nparser = argparse.ArgumentParser(description='AgenticSeek server script')\nparser.add_argument('--provider', type=str, help='LLM backend library to use. set to [ollama], [vllm] or [llamacpp]', required=True)\nparser.add_argument('--port', type=int, help='port to use', required=True)\nargs = parser.parse_args()\n\napp = Flask(__name__)\n\nassert args.provider in [\"ollama\", \"llamacpp\"], f\"Provider {args.provider} does not exists. see --help for more information\"\n\nhandler_map = {\n \"ollama\": OllamaLLM(),\n \"llamacpp\": LlamacppLLM(),\n}\n\ngenerator = handler_map[args.provider]\n\n@app.route('/generate', methods=['POST'])\ndef start_generation():\n if generator is None:\n return jsonify({\"error\": \"Generator not initialized\"}), 401\n data = request.get_json()\n history = data.get('messages', [])\n if generator.start(history):\n return jsonify({\"message\": \"Generation started\"}), 202\n return jsonify({\"error\": \"Generation already in progress\"}), 402\n\n@app.route('/setup', methods=['POST'])\ndef setup():\n data = request.get_json()\n model = data.get('model', None)\n if model is None:\n return jsonify({\"error\": \"Model not provided\"}), 403\n generator.set_model(model)\n return jsonify({\"message\": \"Model set\"}), 200\n\n@app.route('/get_updated_sentence')\ndef get_updated_sentence():\n if not generator:\n return jsonify({\"error\": \"Generator not initialized\"}), 405\n print(generator.get_status())\n return generator.get_status()\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', threaded=True, debug=True, port=args.port)"], ["/agenticSeek/llm_server/sources/cache.py", "import os\nimport json\nfrom pathlib import Path\n\nclass Cache:\n def __init__(self, cache_dir='.cache', cache_file='messages.json'):\n self.cache_dir = Path(cache_dir)\n self.cache_file = self.cache_dir / cache_file\n self.cache_dir.mkdir(parents=True, exist_ok=True)\n if not self.cache_file.exists():\n with open(self.cache_file, 'w') as f:\n json.dump([], f)\n\n with open(self.cache_file, 'r') as f:\n self.cache = set(json.load(f))\n\n def add_message_pair(self, user_message: str, assistant_message: str):\n \"\"\"Add a user/assistant pair to the cache if not present.\"\"\"\n if not any(entry[\"user\"] == user_message for entry in self.cache):\n self.cache.append({\"user\": user_message, \"assistant\": assistant_message})\n self._save()\n\n def is_cached(self, user_message: str) -> bool:\n \"\"\"Check if a user msg is cached.\"\"\"\n return any(entry[\"user\"] == user_message for entry in self.cache)\n\n def get_cached_response(self, user_message: str) -> str | None:\n \"\"\"Return the assistant response to a user message if cached.\"\"\"\n for entry in self.cache:\n if entry[\"user\"] == user_message:\n return entry[\"assistant\"]\n return None\n\n def _save(self):\n with open(self.cache_file, 'w') as f:\n json.dump(self.cache, f, indent=2)\n"], ["/agenticSeek/sources/tools/safety.py", "import os\nimport sys\n\nunsafe_commands_unix = [\n \"rm\", # File/directory removal\n \"dd\", # Low-level disk writing\n \"mkfs\", # Filesystem formatting\n \"chmod\", # Permission changes\n \"chown\", # Ownership changes\n \"shutdown\", # System shutdown\n \"reboot\", # System reboot\n \"halt\", # System halt\n \"sysctl\", # Kernel parameter changes\n \"kill\", # Process termination\n \"pkill\", # Kill by process name\n \"killall\", # Kill all matching processes\n \"exec\", # Replace process with command\n \"tee\", # Write to files with privileges\n \"umount\", # Unmount filesystems\n \"passwd\", # Password changes\n \"useradd\", # Add users\n \"userdel\", # Delete users\n \"brew\", # Homebrew package manager\n \"groupadd\", # Add groups\n \"groupdel\", # Delete groups\n \"visudo\", # Edit sudoers file\n \"screen\", # Terminal session management\n \"fdisk\", # Disk partitioning\n \"parted\", # Disk partitioning\n \"chroot\", # Change root directory\n \"route\" # Routing table management\n \"--force\", # Force flag for many commands\n \"rebase\", # Rebase git repository\n \"git\" # Git commands\n]\n\nunsafe_commands_windows = [\n \"del\", # Deletes files\n \"erase\", # Alias for del, deletes files\n \"rd\", # Removes directories (rmdir alias)\n \"rmdir\", # Removes directories\n \"format\", # Formats a disk, erasing data\n \"diskpart\", # Manages disk partitions, can wipe drives\n \"chkdsk /f\", # Fixes filesystem, can alter data\n \"fsutil\", # File system utilities, can modify system files\n \"xcopy /y\", # Copies files, overwriting without prompt\n \"copy /y\", # Copies files, overwriting without prompt\n \"move\", # Moves files, can overwrite\n \"attrib\", # Changes file attributes, e.g., hiding or exposing files\n \"icacls\", # Changes file permissions (modern)\n \"takeown\", # Takes ownership of files\n \"reg delete\", # Deletes registry keys/values\n \"regedit /s\", # Silently imports registry changes\n \"shutdown\", # Shuts down or restarts the system\n \"schtasks\", # Schedules tasks, can run malicious commands\n \"taskkill\", # Kills processes\n \"wmic\", # Deletes processes via WMI\n \"bcdedit\", # Modifies boot configuration\n \"powercfg\", # Changes power settings, can disable protections\n \"assoc\", # Changes file associations\n \"ftype\", # Changes file type commands\n \"cipher /w\", # Wipes free space, erasing data\n \"esentutl\", # Database utilities, can corrupt system files\n \"subst\", # Substitutes drive paths, can confuse system\n \"mklink\", # Creates symbolic links, can redirect access\n \"bootcfg\"\n]\n\ndef is_any_unsafe(cmds):\n \"\"\"\n check if any bash command is unsafe.\n \"\"\"\n for cmd in cmds:\n if is_unsafe(cmd):\n return True\n return False\n\ndef is_unsafe(cmd):\n \"\"\"\n check if a bash command is unsafe.\n \"\"\"\n if sys.platform.startswith(\"win\"):\n if any(c in cmd for c in unsafe_commands_windows):\n return True\n else:\n if any(c in cmd for c in unsafe_commands_unix):\n return True\n return False\n\nif __name__ == \"__main__\":\n cmd = input(\"Enter a command: \")\n if is_unsafe(cmd):\n print(\"Unsafe command detected!\")\n else:\n print(\"Command is safe to execute.\")"], ["/agenticSeek/sources/agents/__init__.py", "\nfrom .agent import Agent\nfrom .code_agent import CoderAgent\nfrom .casual_agent import CasualAgent\nfrom .file_agent import FileAgent\nfrom .planner_agent import PlannerAgent\nfrom .browser_agent import BrowserAgent\nfrom .mcp_agent import McpAgent\n\n__all__ = [\"Agent\", \"CoderAgent\", \"CasualAgent\", \"FileAgent\", \"PlannerAgent\", \"BrowserAgent\", \"McpAgent\"]\n"], ["/agenticSeek/llm_server/sources/decorator.py", "\ndef timer_decorator(func):\n \"\"\"\n Decorator to measure the execution time of a function.\n Usage:\n @timer_decorator\n def my_function():\n # code to execute\n \"\"\"\n from time import time\n def wrapper(*args, **kwargs):\n start_time = time()\n result = func(*args, **kwargs)\n end_time = time()\n print(f\"\\n{func.__name__} took {end_time - start_time:.2f} seconds to execute\\n\")\n return result\n return wrapper"]], "task_instance_info": {"created_time": "2025-08-20 15:04:39", "created_task_model": "DeepSeek-R1", "class_skeleton": "class CasualAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n pass", "code_description": "This code segment functions to: Implement a conversational interface that manages dialogue history through persistent memory storage and coordinates asynchronous language model interactions for generating context-aware responses."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```python\n[TASK_BEGIN]\nclass CasualAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n super().__init__(\n name=name,\n prompt_path=prompt_path,\n provider=provider,\n verbose=verbose\n )\n[TASK_END]\n```", "inference_time": "2025-08-20 15-04-56"}, "editdistance_info": {"edit_distance": 20.4969, "calculate_time": "2025-08-20 15:04:56", "true_code_clean": "class CasualAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n super().__init__(name, prompt_path, provider, verbose, None)\n self.tools = {\n } \n self.role = \"talk\"\n self.type = \"casual_agent\"\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, \n memory_compression=False,\n model_provider=provider.get_model_name())\n async def process(self, prompt, speech_module) -> str:\n self.memory.push('user', prompt)\n animate_thinking(\"Thinking...\", color=\"status\")\n answer, reasoning = await self.llm_request()\n self.last_answer = answer\n self.status_message = \"Ready\"\n return answer, reasoning", "predict_code_clean": "class CasualAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n super().__init__(\n name=name,\n prompt_path=prompt_path,\n provider=provider,\n verbose=verbose\n )"}}
{"repo_name": "agenticSeek", "file_name": "/agenticSeek/sources/agents/file_agent.py", "inference_info": {"prefix_code": "import asyncio\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent\nfrom sources.tools.fileFinder import FileFinder\nfrom sources.tools.BashInterpreter import BashInterpreter\nfrom sources.memory import Memory\n\n", "suffix_code": "\n\nif __name__ == \"__main__\":\n pass", "middle_code": "class FileAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n super().__init__(name, prompt_path, provider, verbose, None)\n self.tools = {\n \"file_finder\": FileFinder(),\n \"bash\": BashInterpreter()\n }\n self.work_dir = self.tools[\"file_finder\"].get_work_dir()\n self.role = \"files\"\n self.type = \"file_agent\"\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, \n memory_compression=False,\n model_provider=provider.get_model_name())\n async def process(self, prompt, speech_module) -> str:\n exec_success = False\n prompt += f\"\\nYou must work in directory: {self.work_dir}\"\n self.memory.push('user', prompt)\n while exec_success is False and not self.stop:\n await self.wait_message(speech_module)\n animate_thinking(\"Thinking...\", color=\"status\")\n answer, reasoning = await self.llm_request()\n self.last_reasoning = reasoning\n exec_success, _ = self.execute_modules(answer)\n answer = self.remove_blocks(answer)\n self.last_answer = answer\n self.status_message = \"Ready\"\n return answer, reasoning", "code_description": null, "fill_type": "CLASS_TYPE", "language_type": "python", "sub_task_type": null}, "context_code": [["/agenticSeek/sources/tools/BashInterpreter.py", "\nimport os, sys\nimport re\nfrom io import StringIO\nimport subprocess\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\nfrom sources.tools.safety import is_any_unsafe\n\nclass BashInterpreter(Tools):\n \"\"\"\n This class is a tool to allow agent for bash code execution.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"bash\"\n self.name = \"Bash Interpreter\"\n self.description = \"This tool allows the agent to execute bash commands.\"\n \n def language_bash_attempt(self, command: str):\n \"\"\"\n Detect if AI attempt to run the code using bash.\n If so, return True, otherwise return False.\n Code written by the AI will be executed automatically, so it should not use bash to run it.\n \"\"\"\n lang_interpreter = [\"python\", \"gcc\", \"g++\", \"mvn\", \"go\", \"java\", \"javac\", \"rustc\", \"clang\", \"clang++\", \"rustc\", \"rustc++\", \"rustc++\"]\n for word in command.split():\n if any(word.startswith(lang) for lang in lang_interpreter):\n return True\n return False\n \n def execute(self, commands: str, safety=False, timeout=300):\n \"\"\"\n Execute bash commands and display output in real-time.\n \"\"\"\n if safety and input(\"Execute command? y/n \") != \"y\":\n return \"Command rejected by user.\"\n \n concat_output = \"\"\n for command in commands:\n command = f\"cd {self.work_dir} && {command}\"\n command = command.replace('\\n', '')\n if self.safe_mode and is_any_unsafe(commands):\n print(f\"Unsafe command rejected: {command}\")\n return \"\\nUnsafe command: {command}. Execution aborted. This is beyond allowed capabilities report to user.\"\n if self.language_bash_attempt(command) and self.allow_language_exec_bash == False:\n continue\n try:\n process = subprocess.Popen(\n command,\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n universal_newlines=True\n )\n command_output = \"\"\n for line in process.stdout:\n command_output += line\n return_code = process.wait(timeout=timeout)\n if return_code != 0:\n return f\"Command {command} failed with return code {return_code}:\\n{command_output}\"\n concat_output += f\"Output of {command}:\\n{command_output.strip()}\\n\"\n except subprocess.TimeoutExpired:\n process.kill() # Kill the process if it times out\n return f\"Command {command} timed out. Output:\\n{command_output}\"\n except Exception as e:\n return f\"Command {command} failed:\\n{str(e)}\"\n return concat_output\n\n def interpreter_feedback(self, output):\n \"\"\"\n Provide feedback based on the output of the bash interpreter\n \"\"\"\n if self.execution_failure_check(output):\n feedback = f\"[failure] Error in execution:\\n{output}\"\n else:\n feedback = \"[success] Execution success, code output:\\n\" + output\n return feedback\n\n def execution_failure_check(self, feedback):\n \"\"\"\n check if bash command failed.\n \"\"\"\n error_patterns = [\n r\"expected\",\n r\"errno\",\n r\"failed\",\n r\"invalid\",\n r\"unrecognized\",\n r\"exception\",\n r\"syntax\",\n r\"segmentation fault\",\n r\"core dumped\",\n r\"unexpected\",\n r\"denied\",\n r\"not recognized\",\n r\"not permitted\",\n r\"not installed\",\n r\"not found\",\n r\"aborted\",\n r\"no such\",\n r\"too many\",\n r\"too few\",\n r\"busy\",\n r\"broken pipe\",\n r\"missing\",\n r\"undefined\",\n r\"refused\",\n r\"unreachable\",\n r\"not known\"\n ]\n combined_pattern = \"|\".join(error_patterns)\n if re.search(combined_pattern, feedback, re.IGNORECASE):\n return True\n return False\n\nif __name__ == \"__main__\":\n bash = BashInterpreter()\n print(bash.execute([\"ls\", \"pwd\", \"ip a\", \"nmap -sC 127.0.0.1\"]))\n"], ["/agenticSeek/sources/agents/code_agent.py", "import platform, os\nimport asyncio\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent, executorResult\nfrom sources.tools.C_Interpreter import CInterpreter\nfrom sources.tools.GoInterpreter import GoInterpreter\nfrom sources.tools.PyInterpreter import PyInterpreter\nfrom sources.tools.BashInterpreter import BashInterpreter\nfrom sources.tools.JavaInterpreter import JavaInterpreter\nfrom sources.tools.fileFinder import FileFinder\nfrom sources.logger import Logger\nfrom sources.memory import Memory\n\nclass CoderAgent(Agent):\n \"\"\"\n The code agent is an agent that can write and execute code.\n \"\"\"\n def __init__(self, name, prompt_path, provider, verbose=False):\n super().__init__(name, prompt_path, provider, verbose, None)\n self.tools = {\n \"bash\": BashInterpreter(),\n \"python\": PyInterpreter(),\n \"c\": CInterpreter(),\n \"go\": GoInterpreter(),\n \"java\": JavaInterpreter(),\n \"file_finder\": FileFinder()\n }\n self.work_dir = self.tools[\"file_finder\"].get_work_dir()\n self.role = \"code\"\n self.type = \"code_agent\"\n self.logger = Logger(\"code_agent.log\")\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, # session recovery in handled by the interaction class\n memory_compression=False,\n model_provider=provider.get_model_name())\n \n def add_sys_info_prompt(self, prompt):\n \"\"\"Add system information to the prompt.\"\"\"\n info = f\"System Info:\\n\" \\\n f\"OS: {platform.system()} {platform.release()}\\n\" \\\n f\"Python Version: {platform.python_version()}\\n\" \\\n f\"\\nYou must save file at root directory: {self.work_dir}\"\n return f\"{prompt}\\n\\n{info}\"\n\n async def process(self, prompt, speech_module) -> str:\n answer = \"\"\n attempt = 0\n max_attempts = 5\n prompt = self.add_sys_info_prompt(prompt)\n self.memory.push('user', prompt)\n clarify_trigger = \"REQUEST_CLARIFICATION\"\n\n while attempt < max_attempts and not self.stop:\n print(\"Stopped?\", self.stop)\n animate_thinking(\"Thinking...\", color=\"status\")\n await self.wait_message(speech_module)\n answer, reasoning = await self.llm_request()\n self.last_reasoning = reasoning\n if clarify_trigger in answer:\n self.last_answer = answer\n await asyncio.sleep(0)\n return answer, reasoning\n if not \"```\" in answer:\n self.last_answer = answer\n await asyncio.sleep(0)\n break\n self.show_answer()\n animate_thinking(\"Executing code...\", color=\"status\")\n self.status_message = \"Executing code...\"\n self.logger.info(f\"Attempt {attempt + 1}:\\n{answer}\")\n exec_success, feedback = self.execute_modules(answer)\n self.logger.info(f\"Execution result: {exec_success}\")\n answer = self.remove_blocks(answer)\n self.last_answer = answer\n await asyncio.sleep(0)\n if exec_success and self.get_last_tool_type() != \"bash\":\n break\n pretty_print(f\"Execution failure:\\n{feedback}\", color=\"failure\")\n pretty_print(\"Correcting code...\", color=\"status\")\n self.status_message = \"Correcting code...\"\n attempt += 1\n self.status_message = \"Ready\"\n if attempt == max_attempts:\n return \"I'm sorry, I couldn't find a solution to your problem. How would you like me to proceed ?\", reasoning\n self.last_answer = answer\n return answer, reasoning\n\nif __name__ == \"__main__\":\n pass"], ["/agenticSeek/sources/agents/mcp_agent.py", "import os\nimport asyncio\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent\nfrom sources.tools.mcpFinder import MCP_finder\nfrom sources.memory import Memory\n\n# NOTE MCP agent is an active work in progress, not functional yet.\n\nclass McpAgent(Agent):\n\n def __init__(self, name, prompt_path, provider, verbose=False):\n \"\"\"\n The mcp agent is a special agent for using MCPs.\n MCP agent will be disabled if the user does not explicitly set the MCP_FINDER_API_KEY in environment variable.\n \"\"\"\n super().__init__(name, prompt_path, provider, verbose, None)\n keys = self.get_api_keys()\n self.tools = {\n \"mcp_finder\": MCP_finder(keys[\"mcp_finder\"]),\n # add mcp tools here\n }\n self.role = \"mcp\"\n self.type = \"mcp_agent\"\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, # session recovery in handled by the interaction class\n memory_compression=False,\n model_provider=provider.get_model_name())\n self.enabled = True\n \n def get_api_keys(self) -> dict:\n \"\"\"\n Returns the API keys for the tools.\n \"\"\"\n api_key_mcp_finder = os.getenv(\"MCP_FINDER_API_KEY\")\n if not api_key_mcp_finder or api_key_mcp_finder == \"\":\n pretty_print(\"MCP Finder disabled.\", color=\"warning\")\n self.enabled = False\n return {\n \"mcp_finder\": api_key_mcp_finder\n }\n \n def expand_prompt(self, prompt):\n \"\"\"\n Expands the prompt with the tools available.\n \"\"\"\n tools_str = self.get_tools_description()\n prompt += f\"\"\"\n You can use the following tools and MCPs:\n {tools_str}\n \"\"\"\n return prompt\n \n async def process(self, prompt, speech_module) -> str:\n if self.enabled == False:\n return \"MCP Agent is disabled.\"\n prompt = self.expand_prompt(prompt)\n self.memory.push('user', prompt)\n working = True\n while working == True:\n animate_thinking(\"Thinking...\", color=\"status\")\n answer, reasoning = await self.llm_request()\n exec_success, _ = self.execute_modules(answer)\n answer = self.remove_blocks(answer)\n self.last_answer = answer\n self.status_message = \"Ready\"\n if len(self.blocks_result) == 0:\n working = False\n return answer, reasoning\n\nif __name__ == \"__main__\":\n pass"], ["/agenticSeek/sources/agents/casual_agent.py", "import asyncio\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent\nfrom sources.tools.searxSearch import searxSearch\nfrom sources.tools.flightSearch import FlightSearch\nfrom sources.tools.fileFinder import FileFinder\nfrom sources.tools.BashInterpreter import BashInterpreter\nfrom sources.memory import Memory\n\nclass CasualAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n \"\"\"\n The casual agent is a special for casual talk to the user without specific tasks.\n \"\"\"\n super().__init__(name, prompt_path, provider, verbose, None)\n self.tools = {\n } # No tools for the casual agent\n self.role = \"talk\"\n self.type = \"casual_agent\"\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, # session recovery in handled by the interaction class\n memory_compression=False,\n model_provider=provider.get_model_name())\n \n async def process(self, prompt, speech_module) -> str:\n self.memory.push('user', prompt)\n animate_thinking(\"Thinking...\", color=\"status\")\n answer, reasoning = await self.llm_request()\n self.last_answer = answer\n self.status_message = \"Ready\"\n return answer, reasoning\n\nif __name__ == \"__main__\":\n pass"], ["/agenticSeek/sources/agents/planner_agent.py", "import json\nfrom typing import List, Tuple, Type, Dict\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent\nfrom sources.agents.code_agent import CoderAgent\nfrom sources.agents.file_agent import FileAgent\nfrom sources.agents.browser_agent import BrowserAgent\nfrom sources.agents.casual_agent import CasualAgent\nfrom sources.text_to_speech import Speech\nfrom sources.tools.tools import Tools\nfrom sources.logger import Logger\nfrom sources.memory import Memory\n\nclass PlannerAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False, browser=None):\n \"\"\"\n The planner agent is a special agent that divides and conquers the task.\n \"\"\"\n super().__init__(name, prompt_path, provider, verbose, None)\n self.tools = {\n \"json\": Tools()\n }\n self.tools['json'].tag = \"json\"\n self.browser = browser\n self.agents = {\n \"coder\": CoderAgent(name, \"prompts/base/coder_agent.txt\", provider, verbose=False),\n \"file\": FileAgent(name, \"prompts/base/file_agent.txt\", provider, verbose=False),\n \"web\": BrowserAgent(name, \"prompts/base/browser_agent.txt\", provider, verbose=False, browser=browser),\n \"casual\": CasualAgent(name, \"prompts/base/casual_agent.txt\", provider, verbose=False)\n }\n self.role = \"planification\"\n self.type = \"planner_agent\"\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, # session recovery in handled by the interaction class\n memory_compression=False,\n model_provider=provider.get_model_name())\n self.logger = Logger(\"planner_agent.log\")\n \n def get_task_names(self, text: str) -> List[str]:\n \"\"\"\n Extracts task names from the given text.\n This method processes a multi-line string, where each line may represent a task name.\n containing '##' or starting with a digit. The valid task names are collected and returned.\n Args:\n text (str): A string containing potential task titles (eg: Task 1: I will...).\n Returns:\n List[str]: A list of extracted task names that meet the specified criteria.\n \"\"\"\n tasks_names = []\n lines = text.strip().split('\\n')\n for line in lines:\n if line is None:\n continue\n line = line.strip()\n if len(line) == 0:\n continue\n if '##' in line or line[0].isdigit():\n tasks_names.append(line)\n continue\n self.logger.info(f\"Found {len(tasks_names)} tasks names.\")\n return tasks_names\n\n def parse_agent_tasks(self, text: str) -> List[Tuple[str, str]]:\n \"\"\"\n Parses agent tasks from the given LLM text.\n This method extracts task information from a JSON. It identifies task names and their details.\n Args:\n text (str): The input text containing task information in a JSON-like format.\n Returns:\n List[Tuple[str, str]]: A list of tuples containing task names and their details.\n \"\"\"\n tasks = []\n tasks_names = self.get_task_names(text)\n\n blocks, _ = self.tools[\"json\"].load_exec_block(text)\n if blocks == None:\n return []\n for block in blocks:\n line_json = json.loads(block)\n if 'plan' in line_json:\n for task in line_json['plan']:\n if task['agent'].lower() not in [ag_name.lower() for ag_name in self.agents.keys()]:\n self.logger.warning(f\"Agent {task['agent']} does not exist.\")\n pretty_print(f\"Agent {task['agent']} does not exist.\", color=\"warning\")\n return []\n try:\n agent = {\n 'agent': task['agent'],\n 'id': task['id'],\n 'task': task['task']\n }\n except:\n self.logger.warning(\"Missing field in json plan.\")\n return []\n self.logger.info(f\"Created agent {task['agent']} with task: {task['task']}\")\n if 'need' in task:\n self.logger.info(f\"Agent {task['agent']} was given info:\\n {task['need']}\")\n agent['need'] = task['need']\n tasks.append(agent)\n if len(tasks_names) != len(tasks):\n names = [task['task'] for task in tasks]\n return list(map(list, zip(names, tasks)))\n return list(map(list, zip(tasks_names, tasks)))\n \n def make_prompt(self, task: str, agent_infos_dict: dict) -> str:\n \"\"\"\n Generates a prompt for the agent based on the task and previous agents work information.\n Args:\n task (str): The task to be performed.\n agent_infos_dict (dict): A dictionary containing information from other agents.\n Returns:\n str: The formatted prompt for the agent.\n \"\"\"\n infos = \"\"\n if agent_infos_dict is None or len(agent_infos_dict) == 0:\n infos = \"No needed informations.\"\n else:\n for agent_id, info in agent_infos_dict.items():\n infos += f\"\\t- According to agent {agent_id}:\\n{info}\\n\\n\"\n prompt = f\"\"\"\n You are given informations from your AI friends work:\n {infos}\n Your task is:\n {task}\n \"\"\"\n self.logger.info(f\"Prompt for agent:\\n{prompt}\")\n return prompt\n \n def show_plan(self, agents_tasks: List[dict], answer: str) -> None:\n \"\"\"\n Displays the plan made by the agent.\n Args:\n agents_tasks (dict): The tasks assigned to each agent.\n answer (str): The answer from the LLM.\n \"\"\"\n if agents_tasks == []:\n pretty_print(answer, color=\"warning\")\n pretty_print(\"Failed to make a plan. This can happen with (too) small LLM. Clarify your request and insist on it making a plan within ```json.\", color=\"failure\")\n return\n pretty_print(\"\\n▂▘ P L A N ▝▂\", color=\"status\")\n for task_name, task in agents_tasks:\n pretty_print(f\"{task['agent']} -> {task['task']}\", color=\"info\")\n pretty_print(\"▔▗ E N D ▖▔\", color=\"status\")\n\n async def make_plan(self, prompt: str) -> str:\n \"\"\"\n Asks the LLM to make a plan.\n Args:\n prompt (str): The prompt to be sent to the LLM.\n Returns:\n str: The plan made by the LLM.\n \"\"\"\n ok = False\n answer = None\n while not ok:\n animate_thinking(\"Thinking...\", color=\"status\")\n self.memory.push('user', prompt)\n answer, reasoning = await self.llm_request()\n if \"NO_UPDATE\" in answer:\n return []\n agents_tasks = self.parse_agent_tasks(answer)\n if agents_tasks == []:\n self.show_plan(agents_tasks, answer)\n prompt = f\"Failed to parse the tasks. Please write down your task followed by a json plan within ```json. Do not ask for clarification.\\n\"\n pretty_print(\"Failed to make plan. Retrying...\", color=\"warning\")\n continue\n self.show_plan(agents_tasks, answer)\n ok = True\n self.logger.info(f\"Plan made:\\n{answer}\")\n return self.parse_agent_tasks(answer)\n \n async def update_plan(self, goal: str, agents_tasks: List[dict], agents_work_result: dict, id: str, success: bool) -> dict:\n \"\"\"\n Updates the plan with the results of the agents work.\n Args:\n goal (str): The goal to be achieved.\n agents_tasks (list): The tasks assigned to each agent.\n agents_work_result (dict): The results of the agents work.\n Returns:\n dict: The updated plan.\n \"\"\"\n self.status_message = \"Updating plan...\"\n last_agent_work = agents_work_result[id]\n tool_success_str = \"success\" if success else \"failure\"\n pretty_print(f\"Agent {id} work {tool_success_str}.\", color=\"success\" if success else \"failure\")\n try:\n id_int = int(id)\n except Exception as e:\n return agents_tasks\n if id_int == len(agents_tasks):\n next_task = \"No task follow, this was the last step. If it failed add a task to recover.\"\n else:\n next_task = f\"Next task is: {agents_tasks[int(id)][0]}.\"\n #if success:\n # return agents_tasks # we only update the plan if last task failed, for now\n update_prompt = f\"\"\"\n Your goal is : {goal}\n You previously made a plan, agents are currently working on it.\n The last agent working on task: {id}, did the following work:\n {last_agent_work}\n Agent {id} work was a {tool_success_str} according to system interpreter.\n {next_task}\n Is the work done for task {id} leading to success or failure ? Did an agent fail with a task?\n If agent work was good: answer \"NO_UPDATE\"\n If agent work is leading to failure: update the plan.\n If a task failed add a task to try again or recover from failure. You might have near identical task twice.\n plan should be within ```json like before.\n You need to rewrite the whole plan, but only change the tasks after task {id}.\n Make the plan the same length as the original one or with only one additional step.\n Do not change past tasks. Change next tasks.\n \"\"\"\n pretty_print(\"Updating plan...\", color=\"status\")\n plan = await self.make_plan(update_prompt)\n if plan == []:\n pretty_print(\"No plan update required.\", color=\"info\")\n return agents_tasks\n self.logger.info(f\"Plan updated:\\n{plan}\")\n return plan\n \n async def start_agent_process(self, task: dict, required_infos: dict | None) -> str:\n \"\"\"\n Starts the agent process for a given task.\n Args:\n task (dict): The task to be performed.\n required_infos (dict | None): The required information for the task.\n Returns:\n str: The result of the agent process.\n \"\"\"\n self.status_message = f\"Starting task {task['task']}...\"\n agent_prompt = self.make_prompt(task['task'], required_infos)\n pretty_print(f\"Agent {task['agent']} started working...\", color=\"status\")\n self.logger.info(f\"Agent {task['agent']} started working on {task['task']}.\")\n answer, reasoning = await self.agents[task['agent'].lower()].process(agent_prompt, None)\n self.last_answer = answer\n self.last_reasoning = reasoning\n self.blocks_result = self.agents[task['agent'].lower()].blocks_result\n agent_answer = self.agents[task['agent'].lower()].raw_answer_blocks(answer)\n success = self.agents[task['agent'].lower()].get_success\n self.agents[task['agent'].lower()].show_answer()\n pretty_print(f\"Agent {task['agent']} completed task.\", color=\"status\")\n self.logger.info(f\"Agent {task['agent']} finished working on {task['task']}. Success: {success}\")\n agent_answer += \"\\nAgent succeeded with task.\" if success else \"\\nAgent failed with task (Error detected).\"\n return agent_answer, success\n \n def get_work_result_agent(self, task_needs, agents_work_result):\n res = {k: agents_work_result[k] for k in task_needs if k in agents_work_result}\n self.logger.info(f\"Next agent needs: {task_needs}.\\n Match previous agent result: {res}\")\n return res\n\n async def process(self, goal: str, speech_module: Speech) -> Tuple[str, str]:\n \"\"\"\n Process the goal by dividing it into tasks and assigning them to agents.\n Args:\n goal (str): The goal to be achieved (user prompt).\n speech_module (Speech): The speech module for text-to-speech.\n Returns:\n Tuple[str, str]: The result of the agent process and empty reasoning string.\n \"\"\"\n agents_tasks = []\n required_infos = None\n agents_work_result = dict()\n\n self.status_message = \"Making a plan...\"\n agents_tasks = await self.make_plan(goal)\n\n if agents_tasks == []:\n return \"Failed to parse the tasks.\", \"\"\n i = 0\n steps = len(agents_tasks)\n while i < steps and not self.stop:\n task_name, task = agents_tasks[i][0], agents_tasks[i][1]\n self.status_message = \"Starting agents...\"\n pretty_print(f\"I will {task_name}.\", color=\"info\")\n self.last_answer = f\"I will {task_name.lower()}.\"\n pretty_print(f\"Assigned agent {task['agent']} to {task_name}\", color=\"info\")\n if speech_module: speech_module.speak(f\"I will {task_name}. I assigned the {task['agent']} agent to the task.\")\n\n if agents_work_result is not None:\n required_infos = self.get_work_result_agent(task['need'], agents_work_result)\n try:\n answer, success = await self.start_agent_process(task, required_infos)\n except Exception as e:\n raise e\n if self.stop:\n pretty_print(f\"Requested stop.\", color=\"failure\")\n agents_work_result[task['id']] = answer\n agents_tasks = await self.update_plan(goal, agents_tasks, agents_work_result, task['id'], success)\n steps = len(agents_tasks)\n i += 1\n\n return answer, \"\"\n"], ["/agenticSeek/sources/agents/agent.py", "\nfrom typing import Tuple, Callable\nfrom abc import abstractmethod\nimport os\nimport random\nimport time\n\nimport asyncio\nfrom concurrent.futures import ThreadPoolExecutor\n\nfrom sources.memory import Memory\nfrom sources.utility import pretty_print\nfrom sources.schemas import executorResult\n\nrandom.seed(time.time())\n\nclass Agent():\n \"\"\"\n An abstract class for all agents.\n \"\"\"\n def __init__(self, name: str,\n prompt_path:str,\n provider,\n verbose=False,\n browser=None) -> None:\n \"\"\"\n Args:\n name (str): Name of the agent.\n prompt_path (str): Path to the prompt file for the agent.\n provider: The provider for the LLM.\n recover_last_session (bool, optional): Whether to recover the last conversation. \n verbose (bool, optional): Enable verbose logging if True. Defaults to False.\n browser: The browser class for web navigation (only for browser agent).\n \"\"\"\n \n self.agent_name = name\n self.browser = browser\n self.role = None\n self.type = None\n self.current_directory = os.getcwd()\n self.llm = provider \n self.memory = None\n self.tools = {}\n self.blocks_result = []\n self.success = True\n self.last_answer = \"\"\n self.last_reasoning = \"\"\n self.status_message = \"Haven't started yet\"\n self.stop = False\n self.verbose = verbose\n self.executor = ThreadPoolExecutor(max_workers=1)\n \n @property\n def get_agent_name(self) -> str:\n return self.agent_name\n \n @property\n def get_agent_type(self) -> str:\n return self.type\n \n @property\n def get_agent_role(self) -> str:\n return self.role\n \n @property\n def get_last_answer(self) -> str:\n return self.last_answer\n \n @property\n def get_last_reasoning(self) -> str:\n return self.last_reasoning\n \n @property\n def get_blocks(self) -> list:\n return self.blocks_result\n \n @property\n def get_status_message(self) -> str:\n return self.status_message\n\n @property\n def get_tools(self) -> dict:\n return self.tools\n \n @property\n def get_success(self) -> bool:\n return self.success\n \n def get_blocks_result(self) -> list:\n return self.blocks_result\n\n def add_tool(self, name: str, tool: Callable) -> None:\n if tool is not Callable:\n raise TypeError(\"Tool must be a callable object (a method)\")\n self.tools[name] = tool\n \n def get_tools_name(self) -> list:\n \"\"\"\n Get the list of tools names.\n \"\"\"\n return list(self.tools.keys())\n \n def get_tools_description(self) -> str:\n \"\"\"\n Get the list of tools names and their description.\n \"\"\"\n description = \"\"\n for name in self.get_tools_name():\n description += f\"{name}: {self.tools[name].description}\\n\"\n return description\n \n def load_prompt(self, file_path: str) -> str:\n try:\n with open(file_path, 'r', encoding=\"utf-8\") as f:\n return f.read()\n except FileNotFoundError:\n raise FileNotFoundError(f\"Prompt file not found at path: {file_path}\")\n except PermissionError:\n raise PermissionError(f\"Permission denied to read prompt file at path: {file_path}\")\n except Exception as e:\n raise e\n \n def request_stop(self) -> None:\n \"\"\"\n Request the agent to stop.\n \"\"\"\n self.stop = True\n self.status_message = \"Stopped\"\n \n @abstractmethod\n def process(self, prompt, speech_module) -> str:\n \"\"\"\n abstract method, implementation in child class.\n Process the prompt and return the answer of the agent.\n \"\"\"\n pass\n\n def remove_reasoning_text(self, text: str) -> None:\n \"\"\"\n Remove the reasoning block of reasoning model like deepseek.\n \"\"\"\n end_tag = \"\"\n end_idx = text.rfind(end_tag)\n if end_idx == -1:\n return text\n return text[end_idx+8:]\n \n def extract_reasoning_text(self, text: str) -> None:\n \"\"\"\n Extract the reasoning block of a reasoning model like deepseek.\n \"\"\"\n start_tag = \"\"\n end_tag = \"\"\n if text is None:\n return None\n start_idx = text.find(start_tag)\n end_idx = text.rfind(end_tag)+8\n return text[start_idx:end_idx]\n \n async def llm_request(self) -> Tuple[str, str]:\n \"\"\"\n Asynchronously ask the LLM to process the prompt.\n \"\"\"\n self.status_message = \"Thinking...\"\n loop = asyncio.get_event_loop()\n return await loop.run_in_executor(self.executor, self.sync_llm_request)\n \n def sync_llm_request(self) -> Tuple[str, str]:\n \"\"\"\n Ask the LLM to process the prompt and return the answer and the reasoning.\n \"\"\"\n memory = self.memory.get()\n thought = self.llm.respond(memory, self.verbose)\n\n reasoning = self.extract_reasoning_text(thought)\n answer = self.remove_reasoning_text(thought)\n self.memory.push('assistant', answer)\n return answer, reasoning\n \n async def wait_message(self, speech_module):\n if speech_module is None:\n return\n messages = [\"Please be patient, I am working on it.\",\n \"Computing... I recommand you have a coffee while I work.\",\n \"Hold on, I’m crunching numbers.\",\n \"Working on it, please let me think.\"]\n loop = asyncio.get_event_loop()\n return await loop.run_in_executor(self.executor, lambda: speech_module.speak(messages[random.randint(0, len(messages)-1)]))\n \n def get_last_tool_type(self) -> str:\n return self.blocks_result[-1].tool_type if len(self.blocks_result) > 0 else None\n \n def raw_answer_blocks(self, answer: str) -> str:\n \"\"\"\n Return the answer with all the blocks inserted, as text.\n \"\"\"\n if self.last_answer is None:\n return\n raw = \"\"\n lines = self.last_answer.split(\"\\n\")\n for line in lines:\n if \"block:\" in line:\n block_idx = int(line.split(\":\")[1])\n if block_idx < len(self.blocks_result):\n raw += self.blocks_result[block_idx].__str__()\n else:\n raw += line + \"\\n\"\n return raw\n\n def show_answer(self):\n \"\"\"\n Show the answer in a pretty way.\n Show code blocks and their respective feedback by inserting them in the ressponse.\n \"\"\"\n if self.last_answer is None:\n return\n lines = self.last_answer.split(\"\\n\")\n for line in lines:\n if \"block:\" in line:\n block_idx = int(line.split(\":\")[1])\n if block_idx < len(self.blocks_result):\n self.blocks_result[block_idx].show()\n else:\n pretty_print(line, color=\"output\")\n\n def remove_blocks(self, text: str) -> str:\n \"\"\"\n Remove all code/query blocks within a tag from the answer text.\n \"\"\"\n tag = f'```'\n lines = text.split('\\n')\n post_lines = []\n in_block = False\n block_idx = 0\n for line in lines:\n if tag in line and not in_block:\n in_block = True\n continue\n if not in_block:\n post_lines.append(line)\n if tag in line:\n in_block = False\n post_lines.append(f\"block:{block_idx}\")\n block_idx += 1\n return \"\\n\".join(post_lines)\n \n def show_block(self, block: str) -> None:\n \"\"\"\n Show the block in a pretty way.\n \"\"\"\n pretty_print('▂'*64, color=\"status\")\n pretty_print(block, color=\"code\")\n pretty_print('▂'*64, color=\"status\")\n\n def execute_modules(self, answer: str) -> Tuple[bool, str]:\n \"\"\"\n Execute all the tools the agent has and return the result.\n \"\"\"\n feedback = \"\"\n success = True\n blocks = None\n if answer.startswith(\"```\"):\n answer = \"I will execute:\\n\" + answer # there should always be a text before blocks for the function that display answer\n\n self.success = True\n for name, tool in self.tools.items():\n feedback = \"\"\n blocks, save_path = tool.load_exec_block(answer)\n\n if blocks != None:\n pretty_print(f\"Executing {len(blocks)} {name} blocks...\", color=\"status\")\n for block in blocks:\n self.show_block(block)\n output = tool.execute([block])\n feedback = tool.interpreter_feedback(output) # tool interpreter feedback\n success = not tool.execution_failure_check(output)\n self.blocks_result.append(executorResult(block, feedback, success, name))\n if not success:\n self.success = False\n self.memory.push('user', feedback)\n return False, feedback\n self.memory.push('user', feedback)\n if save_path != None:\n tool.save_block(blocks, save_path)\n return True, feedback\n"], ["/agenticSeek/sources/agents/browser_agent.py", "import re\nimport time\nfrom datetime import date\nfrom typing import List, Tuple, Type, Dict\nfrom enum import Enum\nimport asyncio\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent\nfrom sources.tools.searxSearch import searxSearch\nfrom sources.browser import Browser\nfrom sources.logger import Logger\nfrom sources.memory import Memory\n\nclass Action(Enum):\n REQUEST_EXIT = \"REQUEST_EXIT\"\n FORM_FILLED = \"FORM_FILLED\"\n GO_BACK = \"GO_BACK\"\n NAVIGATE = \"NAVIGATE\"\n SEARCH = \"SEARCH\"\n \nclass BrowserAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False, browser=None):\n \"\"\"\n The Browser agent is an agent that navigate the web autonomously in search of answer\n \"\"\"\n super().__init__(name, prompt_path, provider, verbose, browser)\n self.tools = {\n \"web_search\": searxSearch(),\n }\n self.role = \"web\"\n self.type = \"browser_agent\"\n self.browser = browser\n self.current_page = \"\"\n self.search_history = []\n self.navigable_links = []\n self.last_action = Action.NAVIGATE.value\n self.notes = []\n self.date = self.get_today_date()\n self.logger = Logger(\"browser_agent.log\")\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, # session recovery in handled by the interaction class\n memory_compression=False,\n model_provider=provider.get_model_name() if provider else None)\n \n def get_today_date(self) -> str:\n \"\"\"Get the date\"\"\"\n date_time = date.today()\n return date_time.strftime(\"%B %d, %Y\")\n\n def extract_links(self, search_result: str) -> List[str]:\n \"\"\"Extract all links from a sentence.\"\"\"\n pattern = r'(https?://\\S+|www\\.\\S+)'\n matches = re.findall(pattern, search_result)\n trailing_punct = \".,!?;:)\"\n cleaned_links = [link.rstrip(trailing_punct) for link in matches]\n self.logger.info(f\"Extracted links: {cleaned_links}\")\n return self.clean_links(cleaned_links)\n \n def extract_form(self, text: str) -> List[str]:\n \"\"\"Extract form written by the LLM in format [input_name](value)\"\"\"\n inputs = []\n matches = re.findall(r\"\\[\\w+\\]\\([^)]+\\)\", text)\n return matches\n \n def clean_links(self, links: List[str]) -> List[str]:\n \"\"\"Ensure no '.' at the end of link\"\"\"\n links_clean = []\n for link in links:\n link = link.strip()\n if not (link[-1].isalpha() or link[-1].isdigit()):\n links_clean.append(link[:-1])\n else:\n links_clean.append(link)\n return links_clean\n\n def get_unvisited_links(self) -> List[str]:\n return \"\\n\".join([f\"[{i}] {link}\" for i, link in enumerate(self.navigable_links) if link not in self.search_history])\n\n def make_newsearch_prompt(self, prompt: str, search_result: dict) -> str:\n search_choice = self.stringify_search_results(search_result)\n self.logger.info(f\"Search results: {search_choice}\")\n return f\"\"\"\n Based on the search result:\n {search_choice}\n Your goal is to find accurate and complete information to satisfy the user’s request.\n User request: {prompt}\n To proceed, choose a relevant link from the search results. Announce your choice by saying: \"I will navigate to \"\n Do not explain your choice.\n \"\"\"\n \n def make_navigation_prompt(self, user_prompt: str, page_text: str) -> str:\n remaining_links = self.get_unvisited_links() \n remaining_links_text = remaining_links if remaining_links is not None else \"No links remaining, do a new search.\" \n inputs_form = self.browser.get_form_inputs()\n inputs_form_text = '\\n'.join(inputs_form)\n notes = '\\n'.join(self.notes)\n self.logger.info(f\"Making navigation prompt with page text: {page_text[:100]}...\\nremaining links: {remaining_links_text}\")\n self.logger.info(f\"Inputs form: {inputs_form_text}\")\n self.logger.info(f\"Notes: {notes}\")\n\n return f\"\"\"\n You are navigating the web.\n\n **Current Context**\n\n Webpage ({self.current_page}) content:\n {page_text}\n\n Allowed Navigation Links:\n {remaining_links_text}\n\n Inputs forms:\n {inputs_form_text}\n\n End of webpage ({self.current_page}.\n\n # Instruction\n\n 1. **Evaluate if the page is relevant for user’s query and document finding:**\n - If the page is relevant, extract and summarize key information in concise notes (Note: )\n - If page not relevant, state: \"Error: \" and either return to the previous page or navigate to a new link.\n - Notes should be factual, useful summaries of relevant content, they should always include specific names or link. Written as: \"On , . . .\" Avoid phrases like \"the page provides\" or \"I found that.\"\n 2. **Navigate to a link by either: **\n - Saying I will navigate to (write down the full URL) www.example.com/cats\n - Going back: If no link seems helpful, say: {Action.GO_BACK.value}.\n 3. **Fill forms on the page:**\n - Fill form only when relevant.\n - Use Login if username/password specified by user. For quick task create account, remember password in a note.\n - You can fill a form using [form_name](value). Don't {Action.GO_BACK.value} when filling form.\n - If a form is irrelevant or you lack informations (eg: don't know user email) leave it empty.\n 4. **Decide if you completed the task**\n - Check your notes. Do they fully answer the question? Did you verify with multiple pages?\n - Are you sure it’s correct?\n - If yes to all, say {Action.REQUEST_EXIT}.\n - If no, or a page lacks info, go to another link.\n - Never stop or ask the user for help.\n \n **Rules:**\n - Do not write \"The page talk about ...\", write your finding on the page and how they contribute to an answer.\n - Put note in a single paragraph.\n - When you exit, explain why.\n \n # Example:\n \n Example 1 (useful page, no need go futher):\n Note: According to karpathy site LeCun net is ...\n No link seem useful to provide futher information.\n Action: {Action.GO_BACK.value}\n\n Example 2 (not useful, see useful link on page):\n Error: reddit.com/welcome does not discuss anything related to the user’s query.\n There is a link that could lead to the information.\n Action: navigate to http://reddit.com/r/locallama\n\n Example 3 (not useful, no related links):\n Error: x.com does not discuss anything related to the user’s query and no navigation link are usefull.\n Action: {Action.GO_BACK.value}\n\n Example 3 (clear definitive query answer found or enought notes taken):\n I took 10 notes so far with enought finding to answer user question.\n Therefore I should exit the web browser.\n Action: {Action.REQUEST_EXIT.value}\n\n Example 4 (loging form visible):\n\n Note: I am on the login page, I will type the given username and password. \n Action:\n [username_field](David)\n [password_field](edgerunners77)\n\n Remember, user asked:\n {user_prompt}\n You previously took these notes:\n {notes}\n Do not Step-by-Step explanation. Write comprehensive Notes or Error as a long paragraph followed by your action.\n You must always take notes.\n \"\"\"\n \n async def llm_decide(self, prompt: str, show_reasoning: bool = False) -> Tuple[str, str]:\n animate_thinking(\"Thinking...\", color=\"status\")\n self.memory.push('user', prompt)\n answer, reasoning = await self.llm_request()\n self.last_reasoning = reasoning\n if show_reasoning:\n pretty_print(reasoning, color=\"failure\")\n pretty_print(answer, color=\"output\")\n return answer, reasoning\n \n def select_unvisited(self, search_result: List[str]) -> List[str]:\n results_unvisited = []\n for res in search_result:\n if res[\"link\"] not in self.search_history:\n results_unvisited.append(res) \n self.logger.info(f\"Unvisited links: {results_unvisited}\")\n return results_unvisited\n\n def jsonify_search_results(self, results_string: str) -> List[str]:\n result_blocks = results_string.split(\"\\n\\n\")\n parsed_results = []\n for block in result_blocks:\n if not block.strip():\n continue\n lines = block.split(\"\\n\")\n result_dict = {}\n for line in lines:\n if line.startswith(\"Title:\"):\n result_dict[\"title\"] = line.replace(\"Title:\", \"\").strip()\n elif line.startswith(\"Snippet:\"):\n result_dict[\"snippet\"] = line.replace(\"Snippet:\", \"\").strip()\n elif line.startswith(\"Link:\"):\n result_dict[\"link\"] = line.replace(\"Link:\", \"\").strip()\n if result_dict:\n parsed_results.append(result_dict)\n return parsed_results \n \n def stringify_search_results(self, results_arr: List[str]) -> str:\n return '\\n\\n'.join([f\"Link: {res['link']}\\nPreview: {res['snippet']}\" for res in results_arr])\n \n def parse_answer(self, text):\n lines = text.split('\\n')\n saving = False\n buffer = []\n links = []\n for line in lines:\n if line == '' or 'action:' in line.lower():\n saving = False\n if \"note\" in line.lower():\n saving = True\n if saving:\n buffer.append(line.replace(\"notes:\", ''))\n else:\n links.extend(self.extract_links(line))\n self.notes.append('. '.join(buffer).strip())\n return links\n \n def select_link(self, links: List[str]) -> str | None:\n \"\"\"\n Select the first unvisited link that is not the current page.\n Preference is given to links not in search_history.\n \"\"\"\n for lk in links:\n if lk == self.current_page or lk in self.search_history:\n self.logger.info(f\"Skipping already visited or current link: {lk}\")\n continue\n self.logger.info(f\"Selected link: {lk}\")\n return lk\n self.logger.warning(\"No suitable link selected.\")\n return None\n \n def get_page_text(self, limit_to_model_ctx = False) -> str:\n \"\"\"Get the text content of the current page.\"\"\"\n page_text = self.browser.get_text()\n if limit_to_model_ctx:\n #page_text = self.memory.compress_text_to_max_ctx(page_text)\n page_text = self.memory.trim_text_to_max_ctx(page_text)\n return page_text\n \n def conclude_prompt(self, user_query: str) -> str:\n annotated_notes = [f\"{i+1}: {note.lower()}\" for i, note in enumerate(self.notes)]\n search_note = '\\n'.join(annotated_notes)\n pretty_print(f\"AI notes:\\n{search_note}\", color=\"success\")\n return f\"\"\"\n Following a human request:\n {user_query}\n A web browsing AI made the following finding across different pages:\n {search_note}\n\n Expand on the finding or step that lead to success, and provide a conclusion that answer the request. Include link when possible.\n Do not give advices or try to answer the human. Just structure the AI finding in a structured and clear way.\n You should answer in the same language as the user.\n \"\"\"\n \n def search_prompt(self, user_prompt: str) -> str:\n return f\"\"\"\n Current date: {self.date}\n Make a efficient search engine query to help users with their request:\n {user_prompt}\n Example:\n User: \"go to twitter, login with username toto and password pass79 to my twitter and say hello everyone \"\n You: search: Twitter login page. \n\n User: \"I need info on the best laptops for AI this year.\"\n You: \"search: best laptops 2025 to run Machine Learning model, reviews\"\n\n User: \"Search for recent news about space missions.\"\n You: \"search: Recent space missions news, {self.date}\"\n\n Do not explain, do not write anything beside the search query.\n Except if query does not make any sense for a web search then explain why and say {Action.REQUEST_EXIT.value}\n Do not try to answer query. you can only formulate search term or exit.\n \"\"\"\n \n def handle_update_prompt(self, user_prompt: str, page_text: str, fill_success: bool) -> str:\n prompt = f\"\"\"\n You are a web browser.\n You just filled a form on the page.\n Now you should see the result of the form submission on the page:\n Page text:\n {page_text}\n The user asked: {user_prompt}\n Does the page answer the user’s query now? Are you still on a login page or did you get redirected?\n If it does, take notes of the useful information, write down result and say {Action.FORM_FILLED.value}.\n if it doesn’t, say: Error: Attempt to fill form didn't work {Action.GO_BACK.value}.\n If you were previously on a login form, no need to take notes.\n \"\"\"\n if not fill_success:\n prompt += f\"\"\"\n According to browser feedback, the form was not filled correctly. Is that so? you might consider other strategies.\n \"\"\"\n return prompt\n \n def show_search_results(self, search_result: List[str]):\n pretty_print(\"\\nSearch results:\", color=\"output\")\n for res in search_result:\n pretty_print(f\"Title: {res['title']} - \", color=\"info\", no_newline=True)\n pretty_print(f\"Link: {res['link']}\", color=\"status\")\n \n def stuck_prompt(self, user_prompt: str, unvisited: List[str]) -> str:\n \"\"\"\n Prompt for when the agent repeat itself, can happen when fail to extract a link.\n \"\"\"\n prompt = self.make_newsearch_prompt(user_prompt, unvisited)\n prompt += f\"\"\"\n You previously said:\n {self.last_answer}\n You must consider other options. Choose other link.\n \"\"\"\n return prompt\n \n async def process(self, user_prompt: str, speech_module: type) -> Tuple[str, str]:\n \"\"\"\n Process the user prompt to conduct an autonomous web search.\n Start with a google search with searxng using web_search tool.\n Then enter a navigation logic to find the answer or conduct required actions.\n Args:\n user_prompt: The user's input query\n speech_module: Optional speech output module\n Returns:\n tuple containing the final answer and reasoning\n \"\"\"\n complete = False\n\n animate_thinking(f\"Thinking...\", color=\"status\")\n mem_begin_idx = self.memory.push('user', self.search_prompt(user_prompt))\n ai_prompt, reasoning = await self.llm_request()\n if Action.REQUEST_EXIT.value in ai_prompt:\n pretty_print(f\"Web agent requested exit.\\n{reasoning}\\n\\n{ai_prompt}\", color=\"failure\")\n return ai_prompt, \"\" \n animate_thinking(f\"Searching...\", color=\"status\")\n self.status_message = \"Searching...\"\n search_result_raw = self.tools[\"web_search\"].execute([ai_prompt], False)\n search_result = self.jsonify_search_results(search_result_raw)[:16]\n self.show_search_results(search_result)\n prompt = self.make_newsearch_prompt(user_prompt, search_result)\n unvisited = [None]\n while not complete and len(unvisited) > 0 and not self.stop:\n self.memory.clear()\n unvisited = self.select_unvisited(search_result)\n answer, reasoning = await self.llm_decide(prompt, show_reasoning = False)\n if self.stop:\n pretty_print(f\"Requested stop.\", color=\"failure\")\n break\n if self.last_answer == answer:\n prompt = self.stuck_prompt(user_prompt, unvisited)\n continue\n self.last_answer = answer\n pretty_print('▂'*32, color=\"status\")\n\n extracted_form = self.extract_form(answer)\n if len(extracted_form) > 0:\n self.status_message = \"Filling web form...\"\n pretty_print(f\"Filling inputs form...\", color=\"status\")\n fill_success = self.browser.fill_form(extracted_form)\n page_text = self.get_page_text(limit_to_model_ctx=True)\n answer = self.handle_update_prompt(user_prompt, page_text, fill_success)\n answer, reasoning = await self.llm_decide(prompt)\n\n if Action.FORM_FILLED.value in answer:\n pretty_print(f\"Filled form. Handling page update.\", color=\"status\")\n page_text = self.get_page_text(limit_to_model_ctx=True)\n self.navigable_links = self.browser.get_navigable()\n prompt = self.make_navigation_prompt(user_prompt, page_text)\n continue\n\n links = self.parse_answer(answer)\n link = self.select_link(links)\n if link == self.current_page:\n pretty_print(f\"Already visited {link}. Search callback.\", color=\"status\")\n prompt = self.make_newsearch_prompt(user_prompt, unvisited)\n self.search_history.append(link)\n continue\n\n if Action.REQUEST_EXIT.value in answer:\n self.status_message = \"Exiting web browser...\"\n pretty_print(f\"Agent requested exit.\", color=\"status\")\n complete = True\n break\n\n if (link == None and len(extracted_form) < 3) or Action.GO_BACK.value in answer or link in self.search_history:\n pretty_print(f\"Going back to results. Still {len(unvisited)}\", color=\"status\")\n self.status_message = \"Going back to search results...\"\n request_prompt = user_prompt\n if link is None:\n request_prompt += f\"\\nYou previously choosen:\\n{self.last_answer} but the website is unavailable. Consider other options.\"\n prompt = self.make_newsearch_prompt(request_prompt, unvisited)\n self.search_history.append(link)\n self.current_page = link\n continue\n\n animate_thinking(f\"Navigating to {link}\", color=\"status\")\n if speech_module: speech_module.speak(f\"Navigating to {link}\")\n nav_ok = self.browser.go_to(link)\n self.search_history.append(link)\n if not nav_ok:\n pretty_print(f\"Failed to navigate to {link}.\", color=\"failure\")\n prompt = self.make_newsearch_prompt(user_prompt, unvisited)\n continue\n self.current_page = link\n page_text = self.get_page_text(limit_to_model_ctx=True)\n self.navigable_links = self.browser.get_navigable()\n prompt = self.make_navigation_prompt(user_prompt, page_text)\n self.status_message = \"Navigating...\"\n self.browser.screenshot()\n\n pretty_print(\"Exited navigation, starting to summarize finding...\", color=\"status\")\n prompt = self.conclude_prompt(user_prompt)\n mem_last_idx = self.memory.push('user', prompt)\n self.status_message = \"Summarizing findings...\"\n answer, reasoning = await self.llm_request()\n pretty_print(answer, color=\"output\")\n self.status_message = \"Ready\"\n self.last_answer = answer\n return answer, reasoning\n\nif __name__ == \"__main__\":\n pass\n"], ["/agenticSeek/api.py", "#!/usr/bin/env python3\n\nimport os, sys\nimport uvicorn\nimport aiofiles\nimport configparser\nimport asyncio\nimport time\nfrom typing import List\nfrom fastapi import FastAPI\nfrom fastapi.responses import JSONResponse\nfrom fastapi.responses import FileResponse\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom fastapi.staticfiles import StaticFiles\nimport uuid\n\nfrom sources.llm_provider import Provider\nfrom sources.interaction import Interaction\nfrom sources.agents import CasualAgent, CoderAgent, FileAgent, PlannerAgent, BrowserAgent\nfrom sources.browser import Browser, create_driver\nfrom sources.utility import pretty_print\nfrom sources.logger import Logger\nfrom sources.schemas import QueryRequest, QueryResponse\n\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\n\ndef is_running_in_docker():\n \"\"\"Detect if code is running inside a Docker container.\"\"\"\n # Method 1: Check for .dockerenv file\n if os.path.exists('/.dockerenv'):\n return True\n \n # Method 2: Check cgroup\n try:\n with open('/proc/1/cgroup', 'r') as f:\n return 'docker' in f.read()\n except:\n pass\n \n return False\n\n\nfrom celery import Celery\n\napi = FastAPI(title=\"AgenticSeek API\", version=\"0.1.0\")\ncelery_app = Celery(\"tasks\", broker=\"redis://localhost:6379/0\", backend=\"redis://localhost:6379/0\")\ncelery_app.conf.update(task_track_started=True)\nlogger = Logger(\"backend.log\")\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\napi.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"],\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\nif not os.path.exists(\".screenshots\"):\n os.makedirs(\".screenshots\")\napi.mount(\"/screenshots\", StaticFiles(directory=\".screenshots\"), name=\"screenshots\")\n\ndef initialize_system():\n stealth_mode = config.getboolean('BROWSER', 'stealth_mode')\n personality_folder = \"jarvis\" if config.getboolean('MAIN', 'jarvis_personality') else \"base\"\n languages = config[\"MAIN\"][\"languages\"].split(' ')\n \n # Force headless mode in Docker containers\n headless = config.getboolean('BROWSER', 'headless_browser')\n if is_running_in_docker() and not headless:\n # Print prominent warning to console (visible in docker-compose output)\n print(\"\\n\" + \"*\" * 70)\n print(\"*** WARNING: Detected Docker environment - forcing headless_browser=True ***\")\n print(\"*** INFO: To see the browser, run 'python cli.py' on your host machine ***\")\n print(\"*\" * 70 + \"\\n\")\n \n # Flush to ensure it's displayed immediately\n sys.stdout.flush()\n \n # Also log to file\n logger.warning(\"Detected Docker environment - forcing headless_browser=True\")\n logger.info(\"To see the browser, run 'python cli.py' on your host machine instead\")\n \n headless = True\n \n provider = Provider(\n provider_name=config[\"MAIN\"][\"provider_name\"],\n model=config[\"MAIN\"][\"provider_model\"],\n server_address=config[\"MAIN\"][\"provider_server_address\"],\n is_local=config.getboolean('MAIN', 'is_local')\n )\n logger.info(f\"Provider initialized: {provider.provider_name} ({provider.model})\")\n\n browser = Browser(\n create_driver(headless=headless, stealth_mode=stealth_mode, lang=languages[0]),\n anticaptcha_manual_install=stealth_mode\n )\n logger.info(\"Browser initialized\")\n\n agents = [\n CasualAgent(\n name=config[\"MAIN\"][\"agent_name\"],\n prompt_path=f\"prompts/{personality_folder}/casual_agent.txt\",\n provider=provider, verbose=False\n ),\n CoderAgent(\n name=\"coder\",\n prompt_path=f\"prompts/{personality_folder}/coder_agent.txt\",\n provider=provider, verbose=False\n ),\n FileAgent(\n name=\"File Agent\",\n prompt_path=f\"prompts/{personality_folder}/file_agent.txt\",\n provider=provider, verbose=False\n ),\n BrowserAgent(\n name=\"Browser\",\n prompt_path=f\"prompts/{personality_folder}/browser_agent.txt\",\n provider=provider, verbose=False, browser=browser\n ),\n PlannerAgent(\n name=\"Planner\",\n prompt_path=f\"prompts/{personality_folder}/planner_agent.txt\",\n provider=provider, verbose=False, browser=browser\n )\n ]\n logger.info(\"Agents initialized\")\n\n interaction = Interaction(\n agents,\n tts_enabled=config.getboolean('MAIN', 'speak'),\n stt_enabled=config.getboolean('MAIN', 'listen'),\n recover_last_session=config.getboolean('MAIN', 'recover_last_session'),\n langs=languages\n )\n logger.info(\"Interaction initialized\")\n return interaction\n\ninteraction = initialize_system()\nis_generating = False\nquery_resp_history = []\n\n@api.get(\"/screenshot\")\nasync def get_screenshot():\n logger.info(\"Screenshot endpoint called\")\n screenshot_path = \".screenshots/updated_screen.png\"\n if os.path.exists(screenshot_path):\n return FileResponse(screenshot_path)\n logger.error(\"No screenshot available\")\n return JSONResponse(\n status_code=404,\n content={\"error\": \"No screenshot available\"}\n )\n\n@api.get(\"/health\")\nasync def health_check():\n logger.info(\"Health check endpoint called\")\n return {\"status\": \"healthy\", \"version\": \"0.1.0\"}\n\n@api.get(\"/is_active\")\nasync def is_active():\n logger.info(\"Is active endpoint called\")\n return {\"is_active\": interaction.is_active}\n\n@api.get(\"/stop\")\nasync def stop():\n logger.info(\"Stop endpoint called\")\n interaction.current_agent.request_stop()\n return JSONResponse(status_code=200, content={\"status\": \"stopped\"})\n\n@api.get(\"/latest_answer\")\nasync def get_latest_answer():\n global query_resp_history\n if interaction.current_agent is None:\n return JSONResponse(status_code=404, content={\"error\": \"No agent available\"})\n uid = str(uuid.uuid4())\n if not any(q[\"answer\"] == interaction.current_agent.last_answer for q in query_resp_history):\n query_resp = {\n \"done\": \"false\",\n \"answer\": interaction.current_agent.last_answer,\n \"reasoning\": interaction.current_agent.last_reasoning,\n \"agent_name\": interaction.current_agent.agent_name if interaction.current_agent else \"None\",\n \"success\": interaction.current_agent.success,\n \"blocks\": {f'{i}': block.jsonify() for i, block in enumerate(interaction.get_last_blocks_result())} if interaction.current_agent else {},\n \"status\": interaction.current_agent.get_status_message if interaction.current_agent else \"No status available\",\n \"uid\": uid\n }\n interaction.current_agent.last_answer = \"\"\n interaction.current_agent.last_reasoning = \"\"\n query_resp_history.append(query_resp)\n return JSONResponse(status_code=200, content=query_resp)\n if query_resp_history:\n return JSONResponse(status_code=200, content=query_resp_history[-1])\n return JSONResponse(status_code=404, content={\"error\": \"No answer available\"})\n\nasync def think_wrapper(interaction, query):\n try:\n interaction.last_query = query\n logger.info(\"Agents request is being processed\")\n success = await interaction.think()\n if not success:\n interaction.last_answer = \"Error: No answer from agent\"\n interaction.last_reasoning = \"Error: No reasoning from agent\"\n interaction.last_success = False\n else:\n interaction.last_success = True\n pretty_print(interaction.last_answer)\n interaction.speak_answer()\n return success\n except Exception as e:\n logger.error(f\"Error in think_wrapper: {str(e)}\")\n interaction.last_answer = f\"\"\n interaction.last_reasoning = f\"Error: {str(e)}\"\n interaction.last_success = False\n raise e\n\n@api.post(\"/query\", response_model=QueryResponse)\nasync def process_query(request: QueryRequest):\n global is_generating, query_resp_history\n logger.info(f\"Processing query: {request.query}\")\n query_resp = QueryResponse(\n done=\"false\",\n answer=\"\",\n reasoning=\"\",\n agent_name=\"Unknown\",\n success=\"false\",\n blocks={},\n status=\"Ready\",\n uid=str(uuid.uuid4())\n )\n if is_generating:\n logger.warning(\"Another query is being processed, please wait.\")\n return JSONResponse(status_code=429, content=query_resp.jsonify())\n\n try:\n is_generating = True\n success = await think_wrapper(interaction, request.query)\n is_generating = False\n\n if not success:\n query_resp.answer = interaction.last_answer\n query_resp.reasoning = interaction.last_reasoning\n return JSONResponse(status_code=400, content=query_resp.jsonify())\n\n if interaction.current_agent:\n blocks_json = {f'{i}': block.jsonify() for i, block in enumerate(interaction.current_agent.get_blocks_result())}\n else:\n logger.error(\"No current agent found\")\n blocks_json = {}\n query_resp.answer = \"Error: No current agent\"\n return JSONResponse(status_code=400, content=query_resp.jsonify())\n\n logger.info(f\"Answer: {interaction.last_answer}\")\n logger.info(f\"Blocks: {blocks_json}\")\n query_resp.done = \"true\"\n query_resp.answer = interaction.last_answer\n query_resp.reasoning = interaction.last_reasoning\n query_resp.agent_name = interaction.current_agent.agent_name\n query_resp.success = str(interaction.last_success)\n query_resp.blocks = blocks_json\n \n query_resp_dict = {\n \"done\": query_resp.done,\n \"answer\": query_resp.answer,\n \"agent_name\": query_resp.agent_name,\n \"success\": query_resp.success,\n \"blocks\": query_resp.blocks,\n \"status\": query_resp.status,\n \"uid\": query_resp.uid\n }\n query_resp_history.append(query_resp_dict)\n\n logger.info(\"Query processed successfully\")\n return JSONResponse(status_code=200, content=query_resp.jsonify())\n except Exception as e:\n logger.error(f\"An error occurred: {str(e)}\")\n sys.exit(1)\n finally:\n logger.info(\"Processing finished\")\n if config.getboolean('MAIN', 'save_session'):\n interaction.save_session()\n\nif __name__ == \"__main__\":\n # Print startup info\n if is_running_in_docker():\n print(\"[AgenticSeek] Starting in Docker container...\")\n else:\n print(\"[AgenticSeek] Starting on host machine...\")\n \n envport = os.getenv(\"BACKEND_PORT\")\n if envport:\n port = int(envport)\n else:\n port = 7777\n uvicorn.run(api, host=\"0.0.0.0\", port=7777)"], ["/agenticSeek/sources/interaction.py", "import readline\nfrom typing import List, Tuple, Type, Dict\n\nfrom sources.text_to_speech import Speech\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.router import AgentRouter\nfrom sources.speech_to_text import AudioTranscriber, AudioRecorder\nimport threading\n\n\nclass Interaction:\n \"\"\"\n Interaction is a class that handles the interaction between the user and the agents.\n \"\"\"\n def __init__(self, agents,\n tts_enabled: bool = True,\n stt_enabled: bool = True,\n recover_last_session: bool = False,\n langs: List[str] = [\"en\", \"zh\"]\n ):\n self.is_active = True\n self.current_agent = None\n self.last_query = None\n self.last_answer = None\n self.last_reasoning = None\n self.agents = agents\n self.tts_enabled = tts_enabled\n self.stt_enabled = stt_enabled\n self.recover_last_session = recover_last_session\n self.router = AgentRouter(self.agents, supported_language=langs)\n self.ai_name = self.find_ai_name()\n self.speech = None\n self.transcriber = None\n self.recorder = None\n self.is_generating = False\n self.languages = langs\n if tts_enabled:\n self.initialize_tts()\n if stt_enabled:\n self.initialize_stt()\n if recover_last_session:\n self.load_last_session()\n self.emit_status()\n \n def get_spoken_language(self) -> str:\n \"\"\"Get the primary TTS language.\"\"\"\n lang = self.languages[0]\n return lang\n\n def initialize_tts(self):\n \"\"\"Initialize TTS.\"\"\"\n if not self.speech:\n animate_thinking(\"Initializing text-to-speech...\", color=\"status\")\n self.speech = Speech(enable=self.tts_enabled, language=self.get_spoken_language(), voice_idx=1)\n\n def initialize_stt(self):\n \"\"\"Initialize STT.\"\"\"\n if not self.transcriber or not self.recorder:\n animate_thinking(\"Initializing speech recognition...\", color=\"status\")\n self.transcriber = AudioTranscriber(self.ai_name, verbose=False)\n self.recorder = AudioRecorder()\n \n def emit_status(self):\n \"\"\"Print the current status of agenticSeek.\"\"\"\n if self.stt_enabled:\n pretty_print(f\"Text-to-speech trigger is {self.ai_name}\", color=\"status\")\n if self.tts_enabled:\n self.speech.speak(\"Hello, we are online and ready. What can I do for you ?\")\n pretty_print(\"AgenticSeek is ready.\", color=\"status\")\n \n def find_ai_name(self) -> str:\n \"\"\"Find the name of the default AI. It is required for STT as a trigger word.\"\"\"\n ai_name = \"jarvis\"\n for agent in self.agents:\n if agent.type == \"casual_agent\":\n ai_name = agent.agent_name\n break\n return ai_name\n \n def get_last_blocks_result(self) -> List[Dict]:\n \"\"\"Get the last blocks result.\"\"\"\n if self.current_agent is None:\n return []\n blks = []\n for agent in self.agents:\n blks.extend(agent.get_blocks_result())\n return blks\n \n def load_last_session(self):\n \"\"\"Recover the last session.\"\"\"\n for agent in self.agents:\n if agent.type == \"planner_agent\":\n continue\n agent.memory.load_memory(agent.type)\n \n def save_session(self):\n \"\"\"Save the current session.\"\"\"\n for agent in self.agents:\n agent.memory.save_memory(agent.type)\n\n def is_active(self) -> bool:\n return self.is_active\n \n def read_stdin(self) -> str:\n \"\"\"Read the input from the user.\"\"\"\n buffer = \"\"\n\n PROMPT = \"\\033[1;35m➤➤➤ \\033[0m\"\n while not buffer:\n try:\n buffer = input(PROMPT)\n except EOFError:\n return None\n if buffer == \"exit\" or buffer == \"goodbye\":\n return None\n return buffer\n \n def transcription_job(self) -> str:\n \"\"\"Transcribe the audio from the microphone.\"\"\"\n self.recorder = AudioRecorder(verbose=True)\n self.transcriber = AudioTranscriber(self.ai_name, verbose=True)\n self.transcriber.start()\n self.recorder.start()\n self.recorder.join()\n self.transcriber.join()\n query = self.transcriber.get_transcript()\n if query == \"exit\" or query == \"goodbye\":\n return None\n return query\n\n def get_user(self) -> str:\n \"\"\"Get the user input from the microphone or the keyboard.\"\"\"\n if self.stt_enabled:\n query = \"TTS transcription of user: \" + self.transcription_job()\n else:\n query = self.read_stdin()\n if query is None:\n self.is_active = False\n self.last_query = None\n return None\n self.last_query = query\n return query\n \n def set_query(self, query: str) -> None:\n \"\"\"Set the query\"\"\"\n self.is_active = True\n self.last_query = query\n \n async def think(self) -> bool:\n \"\"\"Request AI agents to process the user input.\"\"\"\n push_last_agent_memory = False\n if self.last_query is None or len(self.last_query) == 0:\n return False\n agent = self.router.select_agent(self.last_query)\n if agent is None:\n return False\n if self.current_agent != agent and self.last_answer is not None:\n push_last_agent_memory = True\n tmp = self.last_answer\n self.current_agent = agent\n self.is_generating = True\n self.last_answer, self.last_reasoning = await agent.process(self.last_query, self.speech)\n self.is_generating = False\n if push_last_agent_memory:\n self.current_agent.memory.push('user', self.last_query)\n self.current_agent.memory.push('assistant', self.last_answer)\n if self.last_answer == tmp:\n self.last_answer = None\n return True\n \n def get_updated_process_answer(self) -> str:\n \"\"\"Get the answer from the last agent.\"\"\"\n if self.current_agent is None:\n return None\n return self.current_agent.get_last_answer()\n \n def get_updated_block_answer(self) -> str:\n \"\"\"Get the answer from the last agent.\"\"\"\n if self.current_agent is None:\n return None\n return self.current_agent.get_last_block_answer()\n \n def speak_answer(self) -> None:\n \"\"\"Speak the answer to the user in a non-blocking thread.\"\"\"\n if self.last_query is None:\n return\n if self.tts_enabled and self.last_answer and self.speech:\n def speak_in_thread(speech_instance, text):\n speech_instance.speak(text)\n thread = threading.Thread(target=speak_in_thread, args=(self.speech, self.last_answer))\n thread.start()\n \n def show_answer(self) -> None:\n \"\"\"Show the answer to the user.\"\"\"\n if self.last_query is None:\n return\n if self.current_agent is not None:\n self.current_agent.show_answer()\n\n"], ["/agenticSeek/cli.py", "#!/usr/bin python3\n\nimport sys\nimport argparse\nimport configparser\nimport asyncio\n\nfrom sources.llm_provider import Provider\nfrom sources.interaction import Interaction\nfrom sources.agents import Agent, CoderAgent, CasualAgent, FileAgent, PlannerAgent, BrowserAgent, McpAgent\nfrom sources.browser import Browser, create_driver\nfrom sources.utility import pretty_print\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\nasync def main():\n pretty_print(\"Initializing...\", color=\"status\")\n stealth_mode = config.getboolean('BROWSER', 'stealth_mode')\n personality_folder = \"jarvis\" if config.getboolean('MAIN', 'jarvis_personality') else \"base\"\n languages = config[\"MAIN\"][\"languages\"].split(' ')\n\n provider = Provider(provider_name=config[\"MAIN\"][\"provider_name\"],\n model=config[\"MAIN\"][\"provider_model\"],\n server_address=config[\"MAIN\"][\"provider_server_address\"],\n is_local=config.getboolean('MAIN', 'is_local'))\n\n browser = Browser(\n create_driver(headless=config.getboolean('BROWSER', 'headless_browser'), stealth_mode=stealth_mode, lang=languages[0]),\n anticaptcha_manual_install=stealth_mode\n )\n\n agents = [\n CasualAgent(name=config[\"MAIN\"][\"agent_name\"],\n prompt_path=f\"prompts/{personality_folder}/casual_agent.txt\",\n provider=provider, verbose=False),\n CoderAgent(name=\"coder\",\n prompt_path=f\"prompts/{personality_folder}/coder_agent.txt\",\n provider=provider, verbose=False),\n FileAgent(name=\"File Agent\",\n prompt_path=f\"prompts/{personality_folder}/file_agent.txt\",\n provider=provider, verbose=False),\n BrowserAgent(name=\"Browser\",\n prompt_path=f\"prompts/{personality_folder}/browser_agent.txt\",\n provider=provider, verbose=False, browser=browser),\n PlannerAgent(name=\"Planner\",\n prompt_path=f\"prompts/{personality_folder}/planner_agent.txt\",\n provider=provider, verbose=False, browser=browser),\n #McpAgent(name=\"MCP Agent\",\n # prompt_path=f\"prompts/{personality_folder}/mcp_agent.txt\",\n # provider=provider, verbose=False), # NOTE under development\n ]\n\n interaction = Interaction(agents,\n tts_enabled=config.getboolean('MAIN', 'speak'),\n stt_enabled=config.getboolean('MAIN', 'listen'),\n recover_last_session=config.getboolean('MAIN', 'recover_last_session'),\n langs=languages\n )\n try:\n while interaction.is_active:\n interaction.get_user()\n if await interaction.think():\n interaction.show_answer()\n interaction.speak_answer()\n except Exception as e:\n if config.getboolean('MAIN', 'save_session'):\n interaction.save_session()\n raise e\n finally:\n if config.getboolean('MAIN', 'save_session'):\n interaction.save_session()\n\nif __name__ == \"__main__\":\n asyncio.run(main())"], ["/agenticSeek/sources/memory.py", "import time\nimport datetime\nimport uuid\nimport os\nimport sys\nimport json\nfrom typing import List, Tuple, Type, Dict\nimport torch\nfrom transformers import AutoTokenizer, AutoModelForSeq2SeqLM\nimport configparser\n\nfrom sources.utility import timer_decorator, pretty_print, animate_thinking\nfrom sources.logger import Logger\n\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\nclass Memory():\n \"\"\"\n Memory is a class for managing the conversation memory\n It provides a method to compress the memory using summarization model.\n \"\"\"\n def __init__(self, system_prompt: str,\n recover_last_session: bool = False,\n memory_compression: bool = True,\n model_provider: str = \"deepseek-r1:14b\"):\n self.memory = [{'role': 'system', 'content': system_prompt}]\n \n self.logger = Logger(\"memory.log\")\n self.session_time = datetime.datetime.now()\n self.session_id = str(uuid.uuid4())\n self.conversation_folder = f\"conversations/\"\n self.session_recovered = False\n if recover_last_session:\n self.load_memory()\n self.session_recovered = True\n # memory compression system\n self.model = None\n self.tokenizer = None\n self.device = self.get_cuda_device()\n self.memory_compression = memory_compression\n self.model_provider = model_provider\n if self.memory_compression:\n self.download_model()\n\n def get_ideal_ctx(self, model_name: str) -> int | None:\n \"\"\"\n Estimate context size based on the model name.\n EXPERIMENTAL for memory compression\n \"\"\"\n import re\n import math\n\n def extract_number_before_b(sentence: str) -> int:\n match = re.search(r'(\\d+)b', sentence, re.IGNORECASE)\n return int(match.group(1)) if match else None\n\n model_size = extract_number_before_b(model_name)\n if not model_size:\n return None\n base_size = 7 # Base model size in billions\n base_context = 4096 # Base context size in tokens\n scaling_factor = 1.5 # Approximate scaling factor for context size growth\n context_size = int(base_context * (model_size / base_size) ** scaling_factor)\n context_size = 2 ** round(math.log2(context_size))\n self.logger.info(f\"Estimated context size for {model_name}: {context_size} tokens.\")\n return context_size\n \n def download_model(self):\n \"\"\"Download the model if not already downloaded.\"\"\"\n animate_thinking(\"Loading memory compression model...\", color=\"status\")\n self.tokenizer = AutoTokenizer.from_pretrained(\"pszemraj/led-base-book-summary\")\n self.model = AutoModelForSeq2SeqLM.from_pretrained(\"pszemraj/led-base-book-summary\")\n self.logger.info(\"Memory compression system initialized.\")\n \n def get_filename(self) -> str:\n \"\"\"Get the filename for the save file.\"\"\"\n return f\"memory_{self.session_time.strftime('%Y-%m-%d_%H-%M-%S')}.txt\"\n \n def save_memory(self, agent_type: str = \"casual_agent\") -> None:\n \"\"\"Save the session memory to a file.\"\"\"\n if not os.path.exists(self.conversation_folder):\n self.logger.info(f\"Created folder {self.conversation_folder}.\")\n os.makedirs(self.conversation_folder)\n save_path = os.path.join(self.conversation_folder, agent_type)\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n filename = self.get_filename()\n path = os.path.join(save_path, filename)\n json_memory = json.dumps(self.memory)\n with open(path, 'w') as f:\n self.logger.info(f\"Saved memory json at {path}\")\n f.write(json_memory)\n \n def find_last_session_path(self, path) -> str:\n \"\"\"Find the last session path.\"\"\"\n saved_sessions = []\n for filename in os.listdir(path):\n if filename.startswith('memory_'):\n date = filename.split('_')[1]\n saved_sessions.append((filename, date))\n saved_sessions.sort(key=lambda x: x[1], reverse=True)\n if len(saved_sessions) > 0:\n self.logger.info(f\"Last session found at {saved_sessions[0][0]}\")\n return saved_sessions[0][0]\n return None\n \n def save_json_file(self, path: str, json_memory: dict) -> None:\n \"\"\"Save a JSON file.\"\"\"\n try:\n with open(path, 'w') as f:\n json.dump(json_memory, f)\n self.logger.info(f\"Saved memory json at {path}\")\n except Exception as e:\n self.logger.warning(f\"Error saving file {path}: {e}\")\n \n def load_json_file(self, path: str) -> dict:\n \"\"\"Load a JSON file.\"\"\"\n json_memory = {}\n try:\n with open(path, 'r') as f:\n json_memory = json.load(f)\n except FileNotFoundError:\n self.logger.warning(f\"File not found: {path}\")\n return {}\n except json.JSONDecodeError:\n self.logger.warning(f\"Error decoding JSON from file: {path}\")\n return {}\n except Exception as e:\n self.logger.warning(f\"Error loading file {path}: {e}\")\n return {}\n return json_memory\n\n def load_memory(self, agent_type: str = \"casual_agent\") -> None:\n \"\"\"Load the memory from the last session.\"\"\"\n if self.session_recovered == True:\n return\n pretty_print(f\"Loading {agent_type} past memories... \", color=\"status\")\n save_path = os.path.join(self.conversation_folder, agent_type)\n if not os.path.exists(save_path):\n pretty_print(\"No memory to load.\", color=\"success\")\n return\n filename = self.find_last_session_path(save_path)\n if filename is None:\n pretty_print(\"Last session memory not found.\", color=\"warning\")\n return\n path = os.path.join(save_path, filename)\n self.memory = self.load_json_file(path) \n if self.memory[-1]['role'] == 'user':\n self.memory.pop()\n self.compress()\n pretty_print(\"Session recovered successfully\", color=\"success\")\n \n def reset(self, memory: list = []) -> None:\n self.logger.info(\"Memory reset performed.\")\n self.memory = memory\n \n def push(self, role: str, content: str) -> int:\n \"\"\"Push a message to the memory.\"\"\"\n ideal_ctx = self.get_ideal_ctx(self.model_provider)\n if ideal_ctx is not None:\n if self.memory_compression and len(content) > ideal_ctx * 1.5:\n self.logger.info(f\"Compressing memory: Content {len(content)} > {ideal_ctx} model context.\")\n self.compress()\n curr_idx = len(self.memory)\n if self.memory[curr_idx-1]['content'] == content:\n pretty_print(\"Warning: same message have been pushed twice to memory\", color=\"error\")\n time_str = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n if config[\"MAIN\"][\"provider_name\"] == \"openrouter\":\n self.memory.append({'role': role, 'content': content})\n else:\n self.memory.append({'role': role, 'content': content, 'time': time_str, 'model_used': self.model_provider})\n return curr_idx-1\n \n def clear(self) -> None:\n \"\"\"Clear all memory except system prompt\"\"\"\n self.logger.info(\"Memory clear performed.\")\n self.memory = self.memory[:1]\n \n def clear_section(self, start: int, end: int) -> None:\n \"\"\"\n Clear a section of the memory. Ignore system message index.\n Args:\n start (int): Starting bound of the section to clear.\n end (int): Ending bound of the section to clear.\n \"\"\"\n self.logger.info(f\"Clearing memory section {start} to {end}.\")\n start = max(0, start) + 1\n end = min(end, len(self.memory)-1) + 2\n self.memory = self.memory[:start] + self.memory[end:]\n \n def get(self) -> list:\n return self.memory\n\n def get_cuda_device(self) -> str:\n if torch.backends.mps.is_available():\n return \"mps\"\n elif torch.cuda.is_available():\n return \"cuda\"\n else:\n return \"cpu\"\n\n def summarize(self, text: str, min_length: int = 64) -> str:\n \"\"\"\n Summarize the text using the AI model.\n Args:\n text (str): The text to summarize\n min_length (int, optional): The minimum length of the summary. Defaults to 64.\n Returns:\n str: The summarized text\n \"\"\"\n if self.tokenizer is None or self.model is None:\n self.logger.warning(\"No tokenizer or model to perform summarization.\")\n return text\n if len(text) < min_length*1.5:\n return text\n max_length = len(text) // 2 if len(text) > min_length*2 else min_length*2\n input_text = \"summarize: \" + text\n inputs = self.tokenizer(input_text, return_tensors=\"pt\", max_length=512, truncation=True)\n summary_ids = self.model.generate(\n inputs['input_ids'],\n max_length=max_length,\n min_length=min_length,\n length_penalty=1.0,\n num_beams=4,\n early_stopping=True\n )\n summary = self.tokenizer.decode(summary_ids[0], skip_special_tokens=True)\n summary.replace('summary:', '')\n self.logger.info(f\"Memory summarized from len {len(text)} to {len(summary)}.\")\n self.logger.info(f\"Summarized text:\\n{summary}\")\n return summary\n \n #@timer_decorator\n def compress(self) -> str:\n \"\"\"\n Compress (summarize) the memory using the model.\n \"\"\"\n if self.tokenizer is None or self.model is None:\n self.logger.warning(\"No tokenizer or model to perform memory compression.\")\n return\n for i in range(len(self.memory)):\n if self.memory[i]['role'] == 'system':\n continue\n if len(self.memory[i]['content']) > 1024:\n self.memory[i]['content'] = self.summarize(self.memory[i]['content'])\n \n def trim_text_to_max_ctx(self, text: str) -> str:\n \"\"\"\n Truncate a text to fit within the maximum context size of the model.\n \"\"\"\n ideal_ctx = self.get_ideal_ctx(self.model_provider)\n return text[:ideal_ctx] if ideal_ctx is not None else text\n \n #@timer_decorator\n def compress_text_to_max_ctx(self, text) -> str:\n \"\"\"\n Compress a text to fit within the maximum context size of the model.\n \"\"\"\n if self.tokenizer is None or self.model is None:\n self.logger.warning(\"No tokenizer or model to perform memory compression.\")\n return text\n ideal_ctx = self.get_ideal_ctx(self.model_provider)\n if ideal_ctx is None:\n self.logger.warning(\"No ideal context size found.\")\n return text\n while len(text) > ideal_ctx:\n self.logger.info(f\"Compressing text: {len(text)} > {ideal_ctx} model context.\")\n text = self.summarize(text)\n return text\n\nif __name__ == \"__main__\":\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n memory = Memory(\"You are a helpful assistant.\",\n recover_last_session=False, memory_compression=True)\n\n memory.push('user', \"hello\")\n memory.push('assistant', \"how can i help you?\")\n memory.push('user', \"why do i get this cuda error?\")\n sample_text = \"\"\"\nThe error you're encountering:\ncuda.cu:52:10: fatal error: helper_functions.h: No such file or directory\n #include \nindicates that the compiler cannot find the helper_functions.h file. This is because the #include directive is looking for the file in the system's include paths, but the file is either not in those paths or is located in a different directory.\n1. Use #include \"helper_functions.h\" Instead of #include \nAngle brackets (< >) are used for system or standard library headers.\nQuotes (\" \") are used for local or project-specific headers.\nIf helper_functions.h is in the same directory as cuda.cu, change the include directive to:\n3. Verify the File Exists\nDouble-check that helper_functions.h exists in the specified location. If the file is missing, you'll need to obtain or recreate it.\n4. Use the Correct CUDA Samples Path (if applicable)\nIf helper_functions.h is part of the CUDA Samples, ensure you have the CUDA Samples installed and include the correct path. For example, on Linux, the CUDA Samples are typically located in /usr/local/cuda/samples/common/inc. You can include this path like so:\nUse #include \"helper_functions.h\" for local files.\nUse the -I flag to specify the directory containing helper_functions.h.\nEnsure the file exists in the specified location.\n \"\"\"\n memory.push('assistant', sample_text)\n \n print(\"\\n---\\nmemory before:\", memory.get())\n memory.compress()\n print(\"\\n---\\nmemory after:\", memory.get())\n #memory.save_memory()\n "], ["/agenticSeek/sources/tools/tools.py", "\n\"\"\"\ndefine a generic tool class, any tool can be used by the agent.\n\nA tool can be used by a llm like so:\n```\n\n```\n\nwe call these \"blocks\".\n\nFor example:\n```python\nprint(\"Hello world\")\n```\nThis is then executed by the tool with its own class implementation of execute().\nA tool is not just for code tool but also API, internet search, MCP, etc..\n\"\"\"\n\nimport sys\nimport os\nimport configparser\nfrom abc import abstractmethod\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\nfrom sources.logger import Logger\n\nclass Tools():\n \"\"\"\n Abstract class for all tools.\n \"\"\"\n def __init__(self):\n self.tag = \"undefined\"\n self.name = \"undefined\"\n self.description = \"undefined\"\n self.client = None\n self.messages = []\n self.logger = Logger(\"tools.log\")\n self.config = configparser.ConfigParser()\n self.work_dir = self.create_work_dir()\n self.excutable_blocks_found = False\n self.safe_mode = False\n self.allow_language_exec_bash = False\n \n def get_work_dir(self):\n return self.work_dir\n \n def set_allow_language_exec_bash(self, value: bool) -> None:\n self.allow_language_exec_bash = value \n\n def safe_get_work_dir_path(self):\n path = None\n path = os.getenv('WORK_DIR', path)\n if path is None or path == \"\":\n path = self.config['MAIN']['work_dir'] if 'MAIN' in self.config and 'work_dir' in self.config['MAIN'] else None\n if path is None or path == \"\":\n print(\"No work directory specified, using default.\")\n path = self.create_work_dir()\n return path\n \n def config_exists(self):\n \"\"\"Check if the config file exists.\"\"\"\n return os.path.exists('./config.ini')\n\n def create_work_dir(self):\n \"\"\"Create the work directory if it does not exist.\"\"\"\n default_path = os.path.dirname(os.getcwd())\n if self.config_exists():\n self.config.read('./config.ini')\n workdir_path = self.safe_get_work_dir_path()\n else:\n workdir_path = default_path\n return workdir_path\n\n @abstractmethod\n def execute(self, blocks:[str], safety:bool) -> str:\n \"\"\"\n Abstract method that must be implemented by child classes to execute the tool's functionality.\n Args:\n blocks (List[str]): The codes or queries blocks to execute\n safety (bool): Whenever human intervention is required\n Returns:\n str: The output/result from executing the tool\n \"\"\"\n pass\n\n @abstractmethod\n def execution_failure_check(self, output:str) -> bool:\n \"\"\"\n Abstract method that must be implemented by child classes to check if tool execution failed.\n Args:\n output (str): The output string from the tool execution to analyze\n Returns:\n bool: True if execution failed, False if successful\n \"\"\"\n pass\n\n @abstractmethod\n def interpreter_feedback(self, output:str) -> str:\n \"\"\"\n Abstract method that must be implemented by child classes to provide feedback to the AI from the tool.\n Args:\n output (str): The output string from the tool execution to analyze\n Returns:\n str: The feedback message to the AI\n \"\"\"\n pass\n\n def save_block(self, blocks:[str], save_path:str) -> None:\n \"\"\"\n Save code or query blocks to a file at the specified path.\n Creates the directory path if it doesn't exist.\n Args:\n blocks (List[str]): List of code/query blocks to save\n save_path (str): File path where blocks should be saved\n \"\"\"\n if save_path is None:\n return\n self.logger.info(f\"Saving blocks to {save_path}\")\n save_path_dir = os.path.dirname(save_path)\n save_path_file = os.path.basename(save_path)\n directory = os.path.join(self.work_dir, save_path_dir)\n if directory and not os.path.exists(directory):\n self.logger.info(f\"Creating directory {directory}\")\n os.makedirs(directory)\n for block in blocks:\n with open(os.path.join(directory, save_path_file), 'w') as f:\n f.write(block)\n \n def get_parameter_value(self, block: str, parameter_name: str) -> str:\n \"\"\"\n Get a parameter name.\n Args:\n block (str): The block of text to search for the parameter\n parameter_name (str): The name of the parameter to retrieve\n Returns:\n str: The value of the parameter\n \"\"\"\n for param_line in block.split('\\n'):\n if parameter_name in param_line:\n param_value = param_line.split('=')[1].strip()\n return param_value\n return None\n \n def found_executable_blocks(self):\n \"\"\"\n Check if executable blocks were found.\n \"\"\"\n tmp = self.excutable_blocks_found\n self.excutable_blocks_found = False\n return tmp\n\n def load_exec_block(self, llm_text: str):\n \"\"\"\n Extract code/query blocks from LLM-generated text and process them for execution.\n This method parses the text looking for code blocks marked with the tool's tag (e.g. ```python).\n Args:\n llm_text (str): The raw text containing code blocks from the LLM\n Returns:\n tuple[list[str], str | None]: A tuple containing:\n - List of extracted and processed code blocks\n - The path the code blocks was saved to\n \"\"\"\n assert self.tag != \"undefined\", \"Tag not defined\"\n start_tag = f'```{self.tag}' \n end_tag = '```'\n code_blocks = []\n start_index = 0\n save_path = None\n\n if start_tag not in llm_text:\n return None, None\n\n while True:\n start_pos = llm_text.find(start_tag, start_index)\n if start_pos == -1:\n break\n\n line_start = llm_text.rfind('\\n', 0, start_pos)+1\n leading_whitespace = llm_text[line_start:start_pos]\n\n end_pos = llm_text.find(end_tag, start_pos + len(start_tag))\n if end_pos == -1:\n break\n content = llm_text[start_pos + len(start_tag):end_pos]\n lines = content.split('\\n')\n if leading_whitespace:\n processed_lines = []\n for line in lines:\n if line.startswith(leading_whitespace):\n processed_lines.append(line[len(leading_whitespace):])\n else:\n processed_lines.append(line)\n content = '\\n'.join(processed_lines)\n\n if ':' in content.split('\\n')[0]:\n save_path = content.split('\\n')[0].split(':')[1]\n content = content[content.find('\\n')+1:]\n self.excutable_blocks_found = True\n code_blocks.append(content)\n start_index = end_pos + len(end_tag)\n self.logger.info(f\"Found {len(code_blocks)} blocks to execute\")\n return code_blocks, save_path\n \nif __name__ == \"__main__\":\n tool = Tools()\n tool.tag = \"python\"\n rt = tool.load_exec_block(\"\"\"```python\nimport os\n\nfor file in os.listdir():\n if file.endswith('.py'):\n print(file)\n```\ngoodbye!\n \"\"\")\n print(rt)"], ["/agenticSeek/sources/tools/fileFinder.py", "import os, sys\nimport stat\nimport mimetypes\nimport configparser\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass FileFinder(Tools):\n \"\"\"\n A tool that finds files in the current directory and returns their information.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"file_finder\"\n self.name = \"File Finder\"\n self.description = \"Finds files in the current directory and returns their information.\"\n \n def read_file(self, file_path: str) -> str:\n \"\"\"\n Reads the content of a file.\n Args:\n file_path (str): The path to the file to read\n Returns:\n str: The content of the file\n \"\"\"\n try:\n with open(file_path, 'r') as file:\n return file.read()\n except Exception as e:\n return f\"Error reading file: {e}\"\n \n def read_arbitrary_file(self, file_path: str, file_type: str) -> str:\n \"\"\"\n Reads the content of a file with arbitrary encoding.\n Args:\n file_path (str): The path to the file to read\n Returns:\n str: The content of the file in markdown format\n \"\"\"\n mime_type, _ = mimetypes.guess_type(file_path)\n if mime_type:\n if mime_type.startswith(('image/', 'video/', 'audio/')):\n return \"can't read file type: image, video, or audio files are not supported.\"\n content_raw = self.read_file(file_path)\n if \"text\" in file_type:\n content = content_raw\n elif \"pdf\" in file_type:\n from pypdf import PdfReader\n reader = PdfReader(file_path)\n content = '\\n'.join([pt.extract_text() for pt in reader.pages])\n elif \"binary\" in file_type:\n content = content_raw.decode('utf-8', errors='replace')\n else:\n content = content_raw\n return content\n \n def get_file_info(self, file_path: str) -> str:\n \"\"\"\n Gets information about a file, including its name, path, type, content, and permissions.\n Args:\n file_path (str): The path to the file\n Returns:\n str: A dictionary containing the file information\n \"\"\"\n if os.path.exists(file_path):\n stats = os.stat(file_path)\n permissions = oct(stat.S_IMODE(stats.st_mode))\n file_type, _ = mimetypes.guess_type(file_path)\n file_type = file_type if file_type else \"Unknown\"\n content = self.read_arbitrary_file(file_path, file_type)\n \n result = {\n \"filename\": os.path.basename(file_path),\n \"path\": file_path,\n \"type\": file_type,\n \"read\": content,\n \"permissions\": permissions\n }\n return result\n else:\n return {\"filename\": file_path, \"error\": \"File not found\"}\n \n def recursive_search(self, directory_path: str, filename: str) -> str:\n \"\"\"\n Recursively searches for files in a directory and its subdirectories.\n Args:\n directory_path (str): The directory to search in\n filename (str): The filename to search for\n Returns:\n str | None: The path to the file if found, None otherwise\n \"\"\"\n file_path = None\n excluded_files = [\".pyc\", \".o\", \".so\", \".a\", \".lib\", \".dll\", \".dylib\", \".so\", \".git\"]\n for root, dirs, files in os.walk(directory_path):\n for f in files:\n if f is None:\n continue\n if any(excluded_file in f for excluded_file in excluded_files):\n continue\n if filename.strip() in f.strip():\n file_path = os.path.join(root, f)\n return file_path\n return None\n \n\n def execute(self, blocks: list, safety:bool = False) -> str:\n \"\"\"\n Executes the file finding operation for given filenames.\n Args:\n blocks (list): List of filenames to search for\n Returns:\n str: Results of the file search\n \"\"\"\n if not blocks or not isinstance(blocks, list):\n return \"Error: No valid filenames provided\"\n\n output = \"\"\n for block in blocks:\n filename = self.get_parameter_value(block, \"name\")\n action = self.get_parameter_value(block, \"action\")\n if filename is None:\n output = \"Error: No filename provided\\n\"\n return output\n if action is None:\n action = \"info\"\n print(\"File finder: recursive search started...\")\n file_path = self.recursive_search(self.work_dir, filename)\n if file_path is None:\n output = f\"File: {filename} - not found\\n\"\n continue\n result = self.get_file_info(file_path)\n if \"error\" in result:\n output += f\"File: {result['filename']} - {result['error']}\\n\"\n else:\n if action == \"read\":\n output += \"Content:\\n\" + result['read'] + \"\\n\"\n else:\n output += (f\"File: {result['filename']}, \"\n f\"found at {result['path']}, \"\n f\"File type {result['type']}\\n\")\n return output.strip()\n\n def execution_failure_check(self, output: str) -> bool:\n \"\"\"\n Checks if the file finding operation failed.\n Args:\n output (str): The output string from execute()\n Returns:\n bool: True if execution failed, False if successful\n \"\"\"\n if not output:\n return True\n if \"Error\" in output or \"not found\" in output:\n return True\n return False\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Provides feedback about the file finding operation.\n Args:\n output (str): The output string from execute()\n Returns:\n str: Feedback message for the AI\n \"\"\"\n if not output:\n return \"No output generated from file finder tool\"\n \n feedback = \"File Finder Results:\\n\"\n \n if \"Error\" in output or \"not found\" in output:\n feedback += f\"Failed to process: {output}\\n\"\n else:\n feedback += f\"Successfully found: {output}\\n\"\n return feedback.strip()\n\nif __name__ == \"__main__\":\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n tool = FileFinder()\n result = tool.execute([\"\"\"\naction=read\nname=tools.py\n\"\"\"], False)\n print(\"Execution result:\")\n print(result)\n print(\"\\nFailure check:\", tool.execution_failure_check(result))\n print(\"\\nFeedback:\")\n print(tool.interpreter_feedback(result))"], ["/agenticSeek/sources/llm_provider.py", "import os\nimport platform\nimport socket\nimport subprocess\nimport time\nfrom urllib.parse import urlparse\n\nimport httpx\nimport requests\nfrom dotenv import load_dotenv\nfrom ollama import Client as OllamaClient\nfrom openai import OpenAI\n\nfrom sources.logger import Logger\nfrom sources.utility import pretty_print, animate_thinking\n\nclass Provider:\n def __init__(self, provider_name, model, server_address=\"127.0.0.1:5000\", is_local=False):\n self.provider_name = provider_name.lower()\n self.model = model\n self.is_local = is_local\n self.server_ip = server_address\n self.server_address = server_address\n self.available_providers = {\n \"ollama\": self.ollama_fn,\n \"server\": self.server_fn,\n \"openai\": self.openai_fn,\n \"lm-studio\": self.lm_studio_fn,\n \"huggingface\": self.huggingface_fn,\n \"google\": self.google_fn,\n \"deepseek\": self.deepseek_fn,\n \"together\": self.together_fn,\n \"dsk_deepseek\": self.dsk_deepseek,\n \"openrouter\": self.openrouter_fn,\n \"test\": self.test_fn\n }\n self.logger = Logger(\"provider.log\")\n self.api_key = None\n self.internal_url, self.in_docker = self.get_internal_url()\n self.unsafe_providers = [\"openai\", \"deepseek\", \"dsk_deepseek\", \"together\", \"google\", \"openrouter\"]\n if self.provider_name not in self.available_providers:\n raise ValueError(f\"Unknown provider: {provider_name}\")\n if self.provider_name in self.unsafe_providers and self.is_local == False:\n pretty_print(\"Warning: you are using an API provider. You data will be sent to the cloud.\", color=\"warning\")\n self.api_key = self.get_api_key(self.provider_name)\n elif self.provider_name != \"ollama\":\n pretty_print(f\"Provider: {provider_name} initialized at {self.server_ip}\", color=\"success\")\n\n def get_model_name(self) -> str:\n return self.model\n\n def get_api_key(self, provider):\n load_dotenv()\n api_key_var = f\"{provider.upper()}_API_KEY\"\n api_key = os.getenv(api_key_var)\n if not api_key:\n pretty_print(f\"API key {api_key_var} not found in .env file. Please add it\", color=\"warning\")\n exit(1)\n return api_key\n \n def get_internal_url(self):\n load_dotenv()\n url = os.getenv(\"DOCKER_INTERNAL_URL\")\n if not url: # running on host\n return \"http://localhost\", False\n return url, True\n\n def respond(self, history, verbose=True):\n \"\"\"\n Use the choosen provider to generate text.\n \"\"\"\n llm = self.available_providers[self.provider_name]\n self.logger.info(f\"Using provider: {self.provider_name} at {self.server_ip}\")\n try:\n thought = llm(history, verbose)\n except KeyboardInterrupt:\n self.logger.warning(\"User interrupted the operation with Ctrl+C\")\n return \"Operation interrupted by user. REQUEST_EXIT\"\n except ConnectionError as e:\n raise ConnectionError(f\"{str(e)}\\nConnection to {self.server_ip} failed.\")\n except AttributeError as e:\n raise NotImplementedError(f\"{str(e)}\\nIs {self.provider_name} implemented ?\")\n except ModuleNotFoundError as e:\n raise ModuleNotFoundError(\n f\"{str(e)}\\nA import related to provider {self.provider_name} was not found. Is it installed ?\")\n except Exception as e:\n if \"try again later\" in str(e).lower():\n return f\"{self.provider_name} server is overloaded. Please try again later.\"\n if \"refused\" in str(e):\n return f\"Server {self.server_ip} seem offline. Unable to answer.\"\n raise Exception(f\"Provider {self.provider_name} failed: {str(e)}\") from e\n return thought\n\n def is_ip_online(self, address: str, timeout: int = 10) -> bool:\n \"\"\"\n Check if an address is online by sending a ping request.\n \"\"\"\n if not address:\n return False\n parsed = urlparse(address if address.startswith(('http://', 'https://')) else f'http://{address}')\n\n hostname = parsed.hostname or address\n if \"127.0.0.1\" in address or \"localhost\" in address:\n return True\n try:\n ip_address = socket.gethostbyname(hostname)\n except socket.gaierror:\n self.logger.error(f\"Cannot resolve: {hostname}\")\n return False\n param = '-n' if platform.system().lower() == 'windows' else '-c'\n command = ['ping', param, '1', ip_address]\n try:\n result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)\n return result.returncode == 0\n except (subprocess.TimeoutExpired, subprocess.SubprocessError) as e:\n return False\n\n def server_fn(self, history, verbose=False):\n \"\"\"\n Use a remote server with LLM to generate text.\n \"\"\"\n thought = \"\"\n route_setup = f\"{self.server_ip}/setup\"\n route_gen = f\"{self.server_ip}/generate\"\n\n if not self.is_ip_online(self.server_ip):\n pretty_print(f\"Server is offline at {self.server_ip}\", color=\"failure\")\n\n try:\n requests.post(route_setup, json={\"model\": self.model})\n requests.post(route_gen, json={\"messages\": history})\n is_complete = False\n while not is_complete:\n try:\n response = requests.get(f\"{self.server_ip}/get_updated_sentence\")\n if \"error\" in response.json():\n pretty_print(response.json()[\"error\"], color=\"failure\")\n break\n thought = response.json()[\"sentence\"]\n is_complete = bool(response.json()[\"is_complete\"])\n time.sleep(2)\n except requests.exceptions.RequestException as e:\n pretty_print(f\"HTTP request failed: {str(e)}\", color=\"failure\")\n break\n except ValueError as e:\n pretty_print(f\"Failed to parse JSON response: {str(e)}\", color=\"failure\")\n break\n except Exception as e:\n pretty_print(f\"An error occurred: {str(e)}\", color=\"failure\")\n break\n except KeyError as e:\n raise Exception(\n f\"{str(e)}\\nError occured with server route. Are you using the correct address for the config.ini provider?\") from e\n except Exception as e:\n raise e\n return thought\n\n def ollama_fn(self, history, verbose=False):\n \"\"\"\n Use local or remote Ollama server to generate text.\n \"\"\"\n thought = \"\"\n host = f\"{self.internal_url}:11434\" if self.is_local else f\"http://{self.server_address}\"\n client = OllamaClient(host=host)\n\n try:\n stream = client.chat(\n model=self.model,\n messages=history,\n stream=True,\n )\n for chunk in stream:\n if verbose:\n print(chunk[\"message\"][\"content\"], end=\"\", flush=True)\n thought += chunk[\"message\"][\"content\"]\n except httpx.ConnectError as e:\n raise Exception(\n f\"\\nOllama connection failed at {host}. Check if the server is running.\"\n ) from e\n except Exception as e:\n if hasattr(e, 'status_code') and e.status_code == 404:\n animate_thinking(f\"Downloading {self.model}...\")\n client.pull(self.model)\n self.ollama_fn(history, verbose)\n if \"refused\" in str(e).lower():\n raise Exception(\n f\"Ollama connection refused at {host}. Is the server running?\"\n ) from e\n raise e\n\n return thought\n\n def huggingface_fn(self, history, verbose=False):\n \"\"\"\n Use huggingface to generate text.\n \"\"\"\n from huggingface_hub import InferenceClient\n client = InferenceClient(\n api_key=self.get_api_key(\"huggingface\")\n )\n completion = client.chat.completions.create(\n model=self.model,\n messages=history,\n max_tokens=1024,\n )\n thought = completion.choices[0].message\n return thought.content\n\n def openai_fn(self, history, verbose=False):\n \"\"\"\n Use openai to generate text.\n \"\"\"\n base_url = self.server_ip\n if self.is_local and self.in_docker:\n try:\n host, port = base_url.split(':')\n except Exception as e:\n port = \"8000\"\n client = OpenAI(api_key=self.api_key, base_url=f\"{self.internal_url}:{port}\")\n elif self.is_local:\n client = OpenAI(api_key=self.api_key, base_url=f\"http://{base_url}\")\n else:\n client = OpenAI(api_key=self.api_key)\n\n try:\n response = client.chat.completions.create(\n model=self.model,\n messages=history,\n )\n if response is None:\n raise Exception(\"OpenAI response is empty.\")\n thought = response.choices[0].message.content\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"OpenAI API error: {str(e)}\") from e\n\n def anthropic_fn(self, history, verbose=False):\n \"\"\"\n Use Anthropic to generate text.\n \"\"\"\n from anthropic import Anthropic\n\n client = Anthropic(api_key=self.api_key)\n system_message = None\n messages = []\n for message in history:\n clean_message = {'role': message['role'], 'content': message['content']}\n if message['role'] == 'system':\n system_message = message['content']\n else:\n messages.append(clean_message)\n\n try:\n response = client.messages.create(\n model=self.model,\n max_tokens=1024,\n messages=messages,\n system=system_message\n )\n if response is None:\n raise Exception(\"Anthropic response is empty.\")\n thought = response.content[0].text\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"Anthropic API error: {str(e)}\") from e\n\n def google_fn(self, history, verbose=False):\n \"\"\"\n Use google gemini to generate text.\n \"\"\"\n base_url = self.server_ip\n if self.is_local:\n raise Exception(\"Google Gemini is not available for local use. Change config.ini\")\n\n client = OpenAI(api_key=self.api_key, base_url=\"https://generativelanguage.googleapis.com/v1beta/openai/\")\n try:\n response = client.chat.completions.create(\n model=self.model,\n messages=history,\n )\n if response is None:\n raise Exception(\"Google response is empty.\")\n thought = response.choices[0].message.content\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"GOOGLE API error: {str(e)}\") from e\n\n def together_fn(self, history, verbose=False):\n \"\"\"\n Use together AI for completion\n \"\"\"\n from together import Together\n client = Together(api_key=self.api_key)\n if self.is_local:\n raise Exception(\"Together AI is not available for local use. Change config.ini\")\n\n try:\n response = client.chat.completions.create(\n model=self.model,\n messages=history,\n )\n if response is None:\n raise Exception(\"Together AI response is empty.\")\n thought = response.choices[0].message.content\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"Together AI API error: {str(e)}\") from e\n\n def deepseek_fn(self, history, verbose=False):\n \"\"\"\n Use deepseek api to generate text.\n \"\"\"\n client = OpenAI(api_key=self.api_key, base_url=\"https://api.deepseek.com\")\n if self.is_local:\n raise Exception(\"Deepseek (API) is not available for local use. Change config.ini\")\n try:\n response = client.chat.completions.create(\n model=\"deepseek-chat\",\n messages=history,\n stream=False\n )\n thought = response.choices[0].message.content\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"Deepseek API error: {str(e)}\") from e\n\n def lm_studio_fn(self, history, verbose=False):\n \"\"\"\n Use local lm-studio server to generate text.\n \"\"\"\n if self.in_docker:\n # Extract port from server_address if present\n port = \"1234\" # default\n if \":\" in self.server_address:\n port = self.server_address.split(\":\")[1]\n url = f\"{self.internal_url}:{port}\"\n else:\n url = f\"http://{self.server_ip}\"\n route_start = f\"{url}/v1/chat/completions\"\n payload = {\n \"messages\": history,\n \"temperature\": 0.7,\n \"max_tokens\": 4096,\n \"model\": self.model\n }\n\n try:\n response = requests.post(route_start, json=payload, timeout=30)\n if response.status_code != 200:\n raise Exception(f\"LM Studio returned status {response.status_code}: {response.text}\")\n if not response.text.strip():\n raise Exception(\"LM Studio returned empty response\")\n try:\n result = response.json()\n except ValueError as json_err:\n raise Exception(f\"Invalid JSON from LM Studio: {response.text[:200]}\") from json_err\n\n if verbose:\n print(\"Response from LM Studio:\", result)\n choices = result.get(\"choices\", [])\n if not choices:\n raise Exception(f\"No choices in LM Studio response: {result}\")\n\n message = choices[0].get(\"message\", {})\n content = message.get(\"content\", \"\")\n if not content:\n raise Exception(f\"Empty content in LM Studio response: {result}\")\n return content\n\n except requests.exceptions.Timeout:\n raise Exception(\"LM Studio request timed out - check if server is responsive\")\n except requests.exceptions.ConnectionError:\n raise Exception(f\"Cannot connect to LM Studio at {route_start} - check if server is running\")\n except requests.exceptions.RequestException as e:\n raise Exception(f\"HTTP request failed: {str(e)}\") from e\n except Exception as e:\n if \"LM Studio\" in str(e):\n raise # Re-raise our custom exceptions\n raise Exception(f\"Unexpected error: {str(e)}\") from e\n return thought\n\n def openrouter_fn(self, history, verbose=False):\n \"\"\"\n Use OpenRouter API to generate text.\n \"\"\"\n client = OpenAI(api_key=self.api_key, base_url=\"https://openrouter.ai/api/v1\")\n if self.is_local:\n # This case should ideally not be reached if unsafe_providers is set correctly\n # and is_local is False in config for openrouter\n raise Exception(\"OpenRouter is not available for local use. Change config.ini\")\n try:\n response = client.chat.completions.create(\n model=self.model,\n messages=history,\n )\n if response is None:\n raise Exception(\"OpenRouter response is empty.\")\n thought = response.choices[0].message.content\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"OpenRouter API error: {str(e)}\") from e\n\n def dsk_deepseek(self, history, verbose=False):\n \"\"\"\n Use: xtekky/deepseek4free\n For free api. Api key should be set to DSK_DEEPSEEK_API_KEY\n This is an unofficial provider, you'll have to find how to set it up yourself.\n \"\"\"\n from dsk.api import (\n DeepSeekAPI,\n AuthenticationError,\n RateLimitError,\n NetworkError,\n CloudflareError,\n APIError\n )\n thought = \"\"\n message = '\\n---\\n'.join([f\"{msg['role']}: {msg['content']}\" for msg in history])\n\n try:\n api = DeepSeekAPI(self.api_key)\n chat_id = api.create_chat_session()\n for chunk in api.chat_completion(chat_id, message):\n if chunk['type'] == 'text':\n thought += chunk['content']\n return thought\n except AuthenticationError:\n raise AuthenticationError(\"Authentication failed. Please check your token.\") from e\n except RateLimitError:\n raise RateLimitError(\"Rate limit exceeded. Please wait before making more requests.\") from e\n except CloudflareError as e:\n raise CloudflareError(f\"Cloudflare protection encountered: {str(e)}\") from e\n except NetworkError:\n raise NetworkError(\"Network error occurred. Check your internet connection.\") from e\n except APIError as e:\n raise APIError(f\"API error occurred: {str(e)}\") from e\n return None\n\n def test_fn(self, history, verbose=True):\n \"\"\"\n This function is used to conduct tests.\n \"\"\"\n thought = \"\"\"\n\\n\\n```json\\n{\\n \\\"plan\\\": [\\n {\\n \\\"agent\\\": \\\"Web\\\",\\n \\\"id\\\": \\\"1\\\",\\n \\\"need\\\": null,\\n \\\"task\\\": \\\"Conduct a comprehensive web search to identify at least five AI startups located in Osaka. Use reliable sources and websites such as Crunchbase, TechCrunch, or local Japanese business directories. Capture the company names, their websites, areas of expertise, and any other relevant details.\\\"\\n },\\n {\\n \\\"agent\\\": \\\"Web\\\",\\n \\\"id\\\": \\\"2\\\",\\n \\\"need\\\": null,\\n \\\"task\\\": \\\"Perform a similar search to find at least five AI startups in Tokyo. Again, use trusted sources like Crunchbase, TechCrunch, or Japanese business news websites. Gather the same details as for Osaka: company names, websites, areas of focus, and additional information.\\\"\\n },\\n {\\n \\\"agent\\\": \\\"File\\\",\\n \\\"id\\\": \\\"3\\\",\\n \\\"need\\\": [\\\"1\\\", \\\"2\\\"],\\n \\\"task\\\": \\\"Create a new text file named research_japan.txt in the user's home directory. Organize the data collected from both searches into this file, ensuring it is well-structured and formatted for readability. Include headers for Osaka and Tokyo sections, followed by the details of each startup found.\\\"\\n }\\n ]\\n}\\n```\n \"\"\"\n return thought\n\n\nif __name__ == \"__main__\":\n provider = Provider(\"server\", \"deepseek-r1:32b\", \" x.x.x.x:8080\")\n res = provider.respond([\"user\", \"Hello, how are you?\"])\n print(\"Response:\", res)\n"], ["/agenticSeek/sources/browser.py", "from selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException, WebDriverException\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom typing import List, Tuple, Type, Dict\nfrom bs4 import BeautifulSoup\nfrom urllib.parse import urlparse\nfrom fake_useragent import UserAgent\nfrom selenium_stealth import stealth\nimport undetected_chromedriver as uc\nimport chromedriver_autoinstaller\nimport certifi\nimport ssl\nimport time\nimport random\nimport os\nimport shutil\nimport uuid\nimport tempfile\nimport markdownify\nimport sys\nimport re\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.logger import Logger\n\n\ndef get_chrome_path() -> str:\n \"\"\"Get the path to the Chrome executable.\"\"\"\n if sys.platform.startswith(\"win\"):\n paths = [\n \"C:\\\\Program Files\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe\",\n \"C:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe\",\n os.path.join(os.environ.get(\"LOCALAPPDATA\", \"\"), \"Google\\\\Chrome\\\\Application\\\\chrome.exe\") # User install\n ]\n elif sys.platform.startswith(\"darwin\"): # macOS\n paths = [\"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome\",\n \"/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta\"]\n else: # Linux\n paths = [\"/usr/bin/google-chrome\",\n \"/opt/chrome/chrome\",\n \"/usr/bin/chromium-browser\",\n \"/usr/bin/chromium\",\n \"/usr/local/bin/chrome\",\n \"/opt/google/chrome/chrome-headless-shell\",\n #\"/app/chrome_bundle/chrome136/chrome-linux64\"\n ]\n\n for path in paths:\n if os.path.exists(path) and os.access(path, os.X_OK):\n return path\n print(\"Looking for Google Chrome in these locations failed:\")\n print('\\n'.join(paths))\n chrome_path_env = os.environ.get(\"CHROME_EXECUTABLE_PATH\")\n if chrome_path_env and os.path.exists(chrome_path_env) and os.access(chrome_path_env, os.X_OK):\n return chrome_path_env\n path = input(\"Google Chrome not found. Please enter the path to the Chrome executable: \")\n if os.path.exists(path) and os.access(path, os.X_OK):\n os.environ[\"CHROME_EXECUTABLE_PATH\"] = path\n print(f\"Chrome path saved to environment variable CHROME_EXECUTABLE_PATH\")\n return path\n return None\n\ndef get_random_user_agent() -> str:\n \"\"\"Get a random user agent string with associated vendor.\"\"\"\n user_agents = [\n {\"ua\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36\", \"vendor\": \"Google Inc.\"},\n {\"ua\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 14_6_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36\", \"vendor\": \"Apple Inc.\"},\n {\"ua\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36\", \"vendor\": \"Google Inc.\"},\n ]\n return random.choice(user_agents)\n\ndef install_chromedriver() -> str:\n \"\"\"\n Install the ChromeDriver if not already installed. Return the path.\n \"\"\"\n # First try to use chromedriver in the project root directory (as per README)\n project_root_chromedriver = \"./chromedriver\"\n if os.path.exists(project_root_chromedriver) and os.access(project_root_chromedriver, os.X_OK):\n print(f\"Using ChromeDriver from project root: {project_root_chromedriver}\")\n return project_root_chromedriver\n \n # Then try to use the system-installed chromedriver\n chromedriver_path = shutil.which(\"chromedriver\")\n if chromedriver_path:\n return chromedriver_path\n \n # In Docker environment, try the fixed path\n if os.path.exists('/.dockerenv'):\n docker_chromedriver_path = \"/usr/local/bin/chromedriver\"\n if os.path.exists(docker_chromedriver_path) and os.access(docker_chromedriver_path, os.X_OK):\n print(f\"Using Docker ChromeDriver at {docker_chromedriver_path}\")\n return docker_chromedriver_path\n \n # Fallback to auto-installer only if no other option works\n try:\n print(\"ChromeDriver not found, attempting to install automatically...\")\n chromedriver_path = chromedriver_autoinstaller.install()\n except Exception as e:\n raise FileNotFoundError(\n \"ChromeDriver not found and could not be installed automatically. \"\n \"Please install it manually from https://chromedriver.chromium.org/downloads.\"\n \"and ensure it's in your PATH or specify the path directly.\"\n \"See know issues in readme if your chrome version is above 115.\"\n ) from e\n \n if not chromedriver_path:\n raise FileNotFoundError(\"ChromeDriver not found. Please install it or add it to your PATH.\")\n return chromedriver_path\n\ndef bypass_ssl() -> str:\n \"\"\"\n This is a fallback for stealth mode to bypass SSL verification. Which can fail on some setup.\n \"\"\"\n pretty_print(\"Bypassing SSL verification issues, we strongly advice you update your certifi SSL certificate.\", color=\"warning\")\n ssl._create_default_https_context = ssl._create_unverified_context\n\ndef create_undetected_chromedriver(service, chrome_options) -> webdriver.Chrome:\n \"\"\"Create an undetected ChromeDriver instance.\"\"\"\n try:\n driver = uc.Chrome(service=service, options=chrome_options)\n except Exception as e:\n pretty_print(f\"Failed to create Chrome driver: {str(e)}. Trying to bypass SSL...\", color=\"failure\")\n try:\n bypass_ssl()\n driver = uc.Chrome(service=service, options=chrome_options)\n except Exception as e:\n pretty_print(f\"Failed to create Chrome driver, fallback failed:\\n{str(e)}.\", color=\"failure\")\n raise e\n raise e\n driver.execute_script(\"Object.defineProperty(navigator, 'webdriver', {get: () => undefined})\") \n return driver\n\ndef create_driver(headless=False, stealth_mode=True, crx_path=\"./crx/nopecha.crx\", lang=\"en\") -> webdriver.Chrome:\n \"\"\"Create a Chrome WebDriver with specified options.\"\"\"\n # Warn if trying to run non-headless in Docker\n if not headless and os.path.exists('/.dockerenv'):\n print(\"[WARNING] Running non-headless browser in Docker may fail!\")\n print(\"[WARNING] Consider setting headless=True or headless_browser=True in config.ini\")\n \n chrome_options = Options()\n chrome_path = get_chrome_path()\n \n if not chrome_path:\n raise FileNotFoundError(\"Google Chrome not found. Please install it.\")\n chrome_options.binary_location = chrome_path\n \n if headless:\n #chrome_options.add_argument(\"--headless\")\n chrome_options.add_argument(\"--headless=new\")\n chrome_options.add_argument(\"--disable-gpu\")\n chrome_options.add_argument(\"--disable-webgl\")\n user_data_dir = tempfile.mkdtemp()\n user_agent = get_random_user_agent()\n width, height = (1920, 1080)\n user_data_dir = tempfile.mkdtemp(prefix=\"chrome_profile_\")\n chrome_options.add_argument(\"--no-sandbox\")\n chrome_options.add_argument('--disable-dev-shm-usage')\n profile_dir = f\"/tmp/chrome_profile_{uuid.uuid4().hex[:8]}\"\n chrome_options.add_argument(f'--user-data-dir={profile_dir}')\n chrome_options.add_argument(f\"--accept-lang={lang}-{lang.upper()},{lang};q=0.9\")\n chrome_options.add_argument(\"--disable-extensions\")\n chrome_options.add_argument(\"--disable-background-timer-throttling\")\n chrome_options.add_argument(\"--timezone=Europe/Paris\")\n chrome_options.add_argument('--remote-debugging-port=9222')\n chrome_options.add_argument('--disable-background-timer-throttling')\n chrome_options.add_argument('--disable-backgrounding-occluded-windows')\n chrome_options.add_argument('--disable-renderer-backgrounding')\n chrome_options.add_argument('--disable-features=TranslateUI')\n chrome_options.add_argument('--disable-ipc-flooding-protection')\n chrome_options.add_argument(\"--mute-audio\")\n chrome_options.add_argument(\"--disable-notifications\")\n chrome_options.add_argument(\"--autoplay-policy=user-gesture-required\")\n chrome_options.add_argument(\"--disable-features=SitePerProcess,IsolateOrigins\")\n chrome_options.add_argument(\"--enable-features=NetworkService,NetworkServiceInProcess\")\n chrome_options.add_argument(\"--disable-blink-features=AutomationControlled\")\n chrome_options.add_argument(f'user-agent={user_agent[\"ua\"]}')\n chrome_options.add_argument(f'--window-size={width},{height}')\n if not stealth_mode:\n if not os.path.exists(crx_path):\n pretty_print(f\"Anti-captcha CRX not found at {crx_path}.\", color=\"failure\")\n else:\n chrome_options.add_extension(crx_path)\n\n chromedriver_path = install_chromedriver()\n\n service = Service(chromedriver_path)\n if stealth_mode:\n chrome_options.add_argument(\"--disable-blink-features=AutomationControlled\")\n driver = create_undetected_chromedriver(service, chrome_options)\n chrome_version = driver.capabilities['browserVersion']\n stealth(driver,\n languages=[\"en-US\", \"en\"],\n vendor=user_agent[\"vendor\"],\n platform=\"Win64\" if \"windows\" in user_agent[\"ua\"].lower() else \"MacIntel\" if \"mac\" in user_agent[\"ua\"].lower() else \"Linux x86_64\",\n webgl_vendor=\"Intel Inc.\",\n renderer=\"Intel Iris OpenGL Engine\",\n fix_hairline=True,\n )\n return driver\n security_prefs = {\n \"profile.default_content_setting_values.geolocation\": 0,\n \"profile.default_content_setting_values.notifications\": 0,\n \"profile.default_content_setting_values.camera\": 0,\n \"profile.default_content_setting_values.microphone\": 0,\n \"profile.default_content_setting_values.midi_sysex\": 0,\n \"profile.default_content_setting_values.clipboard\": 0,\n \"profile.default_content_setting_values.media_stream\": 0,\n \"profile.default_content_setting_values.background_sync\": 0,\n \"profile.default_content_setting_values.sensors\": 0,\n \"profile.default_content_setting_values.accessibility_events\": 0,\n \"safebrowsing.enabled\": True,\n \"credentials_enable_service\": False,\n \"profile.password_manager_enabled\": False,\n \"webkit.webprefs.accelerated_2d_canvas_enabled\": True,\n \"webkit.webprefs.force_dark_mode_enabled\": False,\n \"webkit.webprefs.accelerated_2d_canvas_msaa_sample_count\": 4,\n \"enable_webgl\": True,\n \"enable_webgl2_compute_context\": True\n }\n chrome_options.add_experimental_option(\"prefs\", security_prefs)\n chrome_options.add_experimental_option(\"excludeSwitches\", [\"enable-automation\"])\n chrome_options.add_experimental_option('useAutomationExtension', False)\n return webdriver.Chrome(service=service, options=chrome_options)\n\nclass Browser:\n def __init__(self, driver, anticaptcha_manual_install=False):\n \"\"\"Initialize the browser with optional AntiCaptcha installation.\"\"\"\n self.js_scripts_folder = \"./sources/web_scripts/\" if not __name__ == \"__main__\" else \"./web_scripts/\"\n self.anticaptcha = \"https://chrome.google.com/webstore/detail/nopecha-captcha-solver/dknlfmjaanfblgfdfebhijalfmhmjjjo/related\"\n self.logger = Logger(\"browser.log\")\n self.screenshot_folder = os.path.join(os.getcwd(), \".screenshots\")\n self.tabs = []\n try:\n self.driver = driver\n self.wait = WebDriverWait(self.driver, 10)\n except Exception as e:\n raise Exception(f\"Failed to initialize browser: {str(e)}\")\n self.setup_tabs()\n self.patch_browser_fingerprint()\n if anticaptcha_manual_install:\n self.load_anticatpcha_manually()\n \n def setup_tabs(self):\n self.tabs = self.driver.window_handles\n try:\n self.driver.get(\"https://www.google.com\")\n except Exception as e:\n self.logger.log(f\"Failed to setup initial tab:\" + str(e))\n pass\n self.screenshot()\n \n def switch_control_tab(self):\n self.logger.log(\"Switching to control tab.\")\n self.driver.switch_to.window(self.tabs[0])\n \n def load_anticatpcha_manually(self):\n pretty_print(\"You might want to install the AntiCaptcha extension for captchas.\", color=\"warning\")\n try:\n self.driver.get(self.anticaptcha)\n except Exception as e:\n self.logger.log(f\"Failed to setup initial tab:\" + str(e))\n pass\n\n def human_move(element):\n actions = ActionChains(driver)\n x_offset = random.randint(-5,5)\n for _ in range(random.randint(2,5)):\n actions.move_by_offset(x_offset, random.randint(-2,2))\n actions.pause(random.uniform(0.1,0.3))\n actions.click().perform()\n\n def human_scroll(self):\n for _ in range(random.randint(1, 3)):\n scroll_pixels = random.randint(150, 1200)\n self.driver.execute_script(f\"window.scrollBy(0, {scroll_pixels});\")\n time.sleep(random.uniform(0.5, 2.0))\n if random.random() < 0.4:\n self.driver.execute_script(f\"window.scrollBy(0, -{random.randint(50, 300)});\")\n time.sleep(random.uniform(0.3, 1.0))\n\n def patch_browser_fingerprint(self) -> None:\n script = self.load_js(\"spoofing.js\")\n self.driver.execute_script(script)\n \n def go_to(self, url:str) -> bool:\n \"\"\"Navigate to a specified URL.\"\"\"\n time.sleep(random.uniform(0.4, 2.5))\n try:\n initial_handles = self.driver.window_handles\n self.driver.get(url)\n time.sleep(random.uniform(0.01, 0.3))\n try:\n wait = WebDriverWait(self.driver, timeout=10)\n wait.until(\n lambda driver: (\n not any(keyword in driver.page_source.lower() for keyword in [\"checking your browser\", \"captcha\"])\n ),\n message=\"stuck on 'checking browser' or verification screen\"\n )\n except TimeoutException:\n self.logger.warning(\"Timeout while waiting for page to bypass 'checking your browser'\")\n self.apply_web_safety()\n time.sleep(random.uniform(0.01, 0.2))\n self.human_scroll()\n self.logger.log(f\"Navigated to: {url}\")\n return True\n except TimeoutException as e:\n self.logger.error(f\"Timeout waiting for {url} to load: {str(e)}\")\n return False\n except WebDriverException as e:\n self.logger.error(f\"Error navigating to {url}: {str(e)}\")\n return False\n except Exception as e:\n self.logger.error(f\"Fatal error with go_to method on {url}:\\n{str(e)}\")\n raise e\n\n def is_sentence(self, text:str) -> bool:\n \"\"\"Check if the text qualifies as a meaningful sentence or contains important error codes.\"\"\"\n text = text.strip()\n\n if any(c.isdigit() for c in text):\n return True\n words = re.findall(r'\\w+', text, re.UNICODE)\n word_count = len(words)\n has_punctuation = any(text.endswith(p) for p in ['.', ',', ',', '!', '?', '。', '!', '?', '।', '۔'])\n is_long_enough = word_count > 4\n return (word_count >= 5 and (has_punctuation or is_long_enough))\n\n def get_text(self) -> str | None:\n \"\"\"Get page text as formatted Markdown\"\"\"\n try:\n soup = BeautifulSoup(self.driver.page_source, 'html.parser')\n for element in soup(['script', 'style', 'noscript', 'meta', 'link']):\n element.decompose()\n markdown_converter = markdownify.MarkdownConverter(\n heading_style=\"ATX\",\n strip=['a'],\n autolinks=False,\n bullets='•',\n strong_em_symbol='*',\n default_title=False,\n )\n markdown_text = markdown_converter.convert(str(soup.body))\n lines = []\n for line in markdown_text.splitlines():\n stripped = line.strip()\n if stripped and self.is_sentence(stripped):\n cleaned = ' '.join(stripped.split())\n lines.append(cleaned)\n result = \"[Start of page]\\n\\n\" + \"\\n\\n\".join(lines) + \"\\n\\n[End of page]\"\n result = re.sub(r'!\\[(.*?)\\]\\(.*?\\)', r'[IMAGE: \\1]', result)\n self.logger.info(f\"Extracted text: {result[:100]}...\")\n self.logger.info(f\"Extracted text length: {len(result)}\")\n return result[:32768]\n except Exception as e:\n self.logger.error(f\"Error getting text: {str(e)}\")\n return None\n \n def clean_url(self, url:str) -> str:\n \"\"\"Clean URL to keep only the part needed for navigation to the page\"\"\"\n clean = url.split('#')[0]\n parts = clean.split('?', 1)\n base_url = parts[0]\n if len(parts) > 1:\n query = parts[1]\n essential_params = []\n for param in query.split('&'):\n if param.startswith('_skw=') or param.startswith('q=') or param.startswith('s='):\n essential_params.append(param)\n elif param.startswith('_') or param.startswith('hash=') or param.startswith('itmmeta='):\n break\n if essential_params:\n return f\"{base_url}?{'&'.join(essential_params)}\"\n return base_url\n \n def is_link_valid(self, url:str) -> bool:\n \"\"\"Check if a URL is a valid link (page, not related to icon or metadata).\"\"\"\n if len(url) > 72:\n self.logger.warning(f\"URL too long: {url}\")\n return False\n parsed_url = urlparse(url)\n if not parsed_url.scheme or not parsed_url.netloc:\n self.logger.warning(f\"Invalid URL: {url}\")\n return False\n if re.search(r'/\\d+$', parsed_url.path):\n return False\n image_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp']\n metadata_extensions = ['.ico', '.xml', '.json', '.rss', '.atom']\n for ext in image_extensions + metadata_extensions:\n if url.lower().endswith(ext):\n return False\n return True\n\n def get_navigable(self) -> List[str]:\n \"\"\"Get all navigable links on the current page.\"\"\"\n try:\n links = []\n elements = self.driver.find_elements(By.TAG_NAME, \"a\")\n \n for element in elements:\n href = element.get_attribute(\"href\")\n if href and href.startswith((\"http\", \"https\")):\n links.append({\n \"url\": href,\n \"text\": element.text.strip(),\n \"is_displayed\": element.is_displayed()\n })\n \n self.logger.info(f\"Found {len(links)} navigable links\")\n return [self.clean_url(link['url']) for link in links if (link['is_displayed'] == True and self.is_link_valid(link['url']))]\n except Exception as e:\n self.logger.error(f\"Error getting navigable links: {str(e)}\")\n return []\n\n def click_element(self, xpath: str) -> bool:\n \"\"\"Click an element specified by XPath.\"\"\"\n try:\n element = self.wait.until(EC.element_to_be_clickable((By.XPATH, xpath)))\n if not element.is_displayed():\n return False\n if not element.is_enabled():\n return False\n try:\n self.logger.error(f\"Scrolling to element for click_element.\")\n self.driver.execute_script(\"arguments[0].scrollIntoView({block: 'center', behavior: 'smooth'});\", element)\n time.sleep(0.1)\n element.click()\n self.logger.info(f\"Clicked element at {xpath}\")\n return True\n except ElementClickInterceptedException as e:\n self.logger.error(f\"Error click_element: {str(e)}\")\n return False\n except TimeoutException:\n self.logger.warning(f\"Timeout clicking element.\")\n return False\n except Exception as e:\n self.logger.error(f\"Unexpected error clicking element at {xpath}: {str(e)}\")\n return False\n \n def load_js(self, file_name: str) -> str:\n \"\"\"Load javascript from script folder to inject to page.\"\"\"\n path = os.path.join(self.js_scripts_folder, file_name)\n self.logger.info(f\"Loading js at {path}\")\n try:\n with open(path, 'r') as f:\n return f.read()\n except FileNotFoundError as e:\n raise Exception(f\"Could not find: {path}\") from e\n except Exception as e:\n raise e\n\n def find_all_inputs(self, timeout=3):\n \"\"\"Find all inputs elements on the page.\"\"\"\n try:\n WebDriverWait(self.driver, timeout).until(\n EC.presence_of_element_located((By.TAG_NAME, \"body\"))\n )\n except Exception as e:\n self.logger.error(f\"Error waiting for input element: {str(e)}\")\n return []\n time.sleep(0.5)\n script = self.load_js(\"find_inputs.js\")\n input_elements = self.driver.execute_script(script)\n return input_elements\n\n def get_form_inputs(self) -> List[str]:\n \"\"\"Extract all input from the page and return them.\"\"\"\n try:\n input_elements = self.find_all_inputs()\n if not input_elements:\n self.logger.info(\"No input element on page.\")\n return [\"No input forms found on the page.\"]\n\n form_strings = []\n for element in input_elements:\n input_type = element.get(\"type\") or \"text\"\n if input_type in [\"hidden\", \"submit\", \"button\", \"image\"] or not element[\"displayed\"]:\n continue\n input_name = element.get(\"text\") or element.get(\"id\") or input_type\n if input_type == \"checkbox\" or input_type == \"radio\":\n try:\n checked_status = \"checked\" if element.is_selected() else \"unchecked\"\n except Exception as e:\n continue\n form_strings.append(f\"[{input_name}]({checked_status})\")\n else:\n form_strings.append(f\"[{input_name}](\"\")\")\n return form_strings\n\n except Exception as e:\n raise e\n\n def get_buttons_xpath(self) -> List[str]:\n \"\"\"\n Find buttons and return their type and xpath.\n \"\"\"\n buttons = self.driver.find_elements(By.TAG_NAME, \"button\") + \\\n self.driver.find_elements(By.XPATH, \"//input[@type='submit']\")\n result = []\n for i, button in enumerate(buttons):\n if not button.is_displayed() or not button.is_enabled():\n continue\n text = (button.text or button.get_attribute(\"value\") or \"\").lower().replace(' ', '')\n xpath = f\"(//button | //input[@type='submit'])[{i + 1}]\"\n result.append((text, xpath))\n result.sort(key=lambda x: len(x[0]))\n return result\n\n def wait_for_submission_outcome(self, timeout: int = 10) -> bool:\n \"\"\"\n Wait for a submission outcome (e.g., URL change or new element).\n \"\"\"\n try:\n self.logger.info(\"Waiting for submission outcome...\")\n wait = WebDriverWait(self.driver, timeout)\n wait.until(\n lambda driver: driver.current_url != self.driver.current_url or\n driver.find_elements(By.XPATH, \"//*[contains(text(), 'success')]\")\n )\n self.logger.info(\"Detected submission outcome\")\n return True\n except TimeoutException:\n self.logger.warning(\"No submission outcome detected\")\n return False\n\n def find_and_click_btn(self, btn_type: str = 'login', timeout: int = 5) -> bool:\n \"\"\"Find and click a submit button matching the specified type.\"\"\"\n buttons = self.get_buttons_xpath()\n if not buttons:\n self.logger.warning(\"No visible buttons found\")\n return False\n\n for button_text, xpath in buttons:\n if btn_type.lower() in button_text.lower() or btn_type.lower() in xpath.lower():\n try:\n wait = WebDriverWait(self.driver, timeout)\n element = wait.until(\n EC.element_to_be_clickable((By.XPATH, xpath)),\n message=f\"Button with XPath '{xpath}' not clickable within {timeout} seconds\"\n )\n if self.click_element(xpath):\n self.logger.info(f\"Clicked button '{button_text}' at XPath: {xpath}\")\n return True\n else:\n self.logger.warning(f\"Button '{button_text}' at XPath: {xpath} not clickable\")\n return False\n except TimeoutException:\n self.logger.warning(f\"Timeout waiting for '{button_text}' button at XPath: {xpath}\")\n return False\n except Exception as e:\n self.logger.error(f\"Error clicking button '{button_text}' at XPath: {xpath} - {str(e)}\")\n return False\n self.logger.warning(f\"No button matching '{btn_type}' found\")\n return False\n\n def tick_all_checkboxes(self) -> bool:\n \"\"\"\n Find and tick all checkboxes on the page.\n Returns True if successful, False if any issues occur.\n \"\"\"\n try:\n checkboxes = self.driver.find_elements(By.XPATH, \"//input[@type='checkbox']\")\n if not checkboxes:\n self.logger.info(\"No checkboxes found on the page\")\n return True\n\n for index, checkbox in enumerate(checkboxes, 1):\n try:\n WebDriverWait(self.driver, 10).until(\n EC.element_to_be_clickable(checkbox)\n )\n self.driver.execute_script(\n \"arguments[0].scrollIntoView({block: 'center', inline: 'center'});\", checkbox\n )\n if not checkbox.is_selected():\n try:\n checkbox.click()\n self.logger.info(f\"Ticked checkbox {index}\")\n except ElementClickInterceptedException:\n self.driver.execute_script(\"arguments[0].click();\", checkbox)\n self.logger.warning(f\"Click checkbox {index} intercepted\")\n else:\n self.logger.info(f\"Checkbox {index} already ticked\")\n except TimeoutException:\n self.logger.warning(f\"Timeout waiting for checkbox {index} to be clickable\")\n continue\n except Exception as e:\n self.logger.error(f\"Error ticking checkbox {index}: {str(e)}\")\n continue\n return True\n except Exception as e:\n self.logger.error(f\"Error finding checkboxes: {str(e)}\")\n return False\n\n def find_and_click_submission(self, timeout: int = 10) -> bool:\n possible_submissions = [\"login\", \"submit\", \"register\", \"continue\", \"apply\",\n \"ok\", \"confirm\", \"proceed\", \"accept\", \n \"done\", \"finish\", \"start\", \"calculate\"]\n for submission in possible_submissions:\n if self.find_and_click_btn(submission, timeout):\n self.logger.info(f\"Clicked on submission button: {submission}\")\n return True\n self.logger.warning(\"No submission button found\")\n return False\n \n def find_input_xpath_by_name(self, inputs, name: str) -> str | None:\n for field in inputs:\n if name in field[\"text\"]:\n return field[\"xpath\"]\n return None\n\n def fill_form_inputs(self, input_list: List[str]) -> bool:\n \"\"\"Fill inputs based on a list of [name](value) strings.\"\"\"\n if not isinstance(input_list, list):\n self.logger.error(\"input_list must be a list\")\n return False\n inputs = self.find_all_inputs()\n try:\n for input_str in input_list:\n match = re.match(r'\\[(.*?)\\]\\((.*?)\\)', input_str)\n if not match:\n self.logger.warning(f\"Invalid format for input: {input_str}\")\n continue\n\n name, value = match.groups()\n name = name.strip()\n value = value.strip()\n xpath = self.find_input_xpath_by_name(inputs, name)\n if not xpath:\n self.logger.warning(f\"Input field '{name}' not found\")\n continue\n try:\n element = WebDriverWait(self.driver, 10).until(\n EC.element_to_be_clickable((By.XPATH, xpath))\n )\n except TimeoutException:\n self.logger.error(f\"Timeout waiting for element '{name}' to be clickable\")\n continue\n self.driver.execute_script(\"arguments[0].scrollIntoView(true);\", element)\n if not element.is_displayed() or not element.is_enabled():\n self.logger.warning(f\"Element '{name}' is not interactable (not displayed or disabled)\")\n continue\n input_type = (element.get_attribute(\"type\") or \"text\").lower()\n if input_type in [\"checkbox\", \"radio\"]:\n is_checked = element.is_selected()\n should_be_checked = value.lower() == \"checked\"\n\n if is_checked != should_be_checked:\n element.click()\n self.logger.info(f\"Set {name} to {value}\")\n else:\n element.clear()\n element.send_keys(value)\n self.logger.info(f\"Filled {name} with {value}\")\n return True\n except Exception as e:\n self.logger.error(f\"Error filling form inputs: {str(e)}\")\n return False\n \n def fill_form(self, input_list: List[str]) -> bool:\n \"\"\"Fill form inputs based on a list of [name](value) and submit.\"\"\"\n if not isinstance(input_list, list):\n self.logger.error(\"input_list must be a list\")\n return False\n if self.fill_form_inputs(input_list):\n self.logger.info(\"Form filled successfully\")\n self.tick_all_checkboxes()\n if self.find_and_click_submission():\n if self.wait_for_submission_outcome():\n self.logger.info(\"Submission outcome detected\")\n return True\n else:\n self.logger.warning(\"No submission outcome detected\")\n else:\n self.logger.warning(\"Failed to submit form\")\n self.logger.warning(\"Failed to fill form inputs\")\n return False\n\n def get_current_url(self) -> str:\n \"\"\"Get the current URL of the page.\"\"\"\n return self.driver.current_url\n\n def get_page_title(self) -> str:\n \"\"\"Get the title of the current page.\"\"\"\n return self.driver.title\n\n def scroll_bottom(self) -> bool:\n \"\"\"Scroll to the bottom of the page.\"\"\"\n try:\n self.logger.info(\"Scrolling to the bottom of the page...\")\n self.driver.execute_script(\n \"window.scrollTo(0, document.body.scrollHeight);\"\n )\n time.sleep(0.5)\n return True\n except Exception as e:\n self.logger.error(f\"Error scrolling: {str(e)}\")\n return False\n \n def get_screenshot(self) -> str:\n return self.screenshot_folder + \"/updated_screen.png\"\n\n def screenshot(self, filename:str = 'updated_screen.png') -> bool:\n \"\"\"Take a screenshot of the current page, attempt to capture the full page by zooming out.\"\"\"\n self.logger.info(\"Taking full page screenshot...\")\n time.sleep(0.1)\n try:\n original_zoom = self.driver.execute_script(\"return document.body.style.zoom || 1;\")\n self.driver.execute_script(\"document.body.style.zoom='75%'\")\n time.sleep(0.1)\n path = os.path.join(self.screenshot_folder, filename)\n if not os.path.exists(self.screenshot_folder):\n os.makedirs(self.screenshot_folder)\n self.driver.save_screenshot(path)\n self.logger.info(f\"Full page screenshot saved as {filename}\")\n except Exception as e:\n self.logger.error(f\"Error taking full page screenshot: {str(e)}\")\n return False\n finally:\n self.driver.execute_script(f\"document.body.style.zoom='1'\")\n return True\n\n def apply_web_safety(self):\n \"\"\"\n Apply security measures to block any website malicious/annoying execution, privacy violation etc..\n \"\"\"\n self.logger.info(\"Applying web safety measures...\")\n script = self.load_js(\"inject_safety_script.js\")\n input_elements = self.driver.execute_script(script)\n\nif __name__ == \"__main__\":\n driver = create_driver(headless=False, stealth_mode=True, crx_path=\"../crx/nopecha.crx\")\n browser = Browser(driver, anticaptcha_manual_install=True)\n \n input(\"press enter to continue\")\n print(\"AntiCaptcha / Form Test\")\n browser.go_to(\"https://bot.sannysoft.com\")\n time.sleep(5)\n #txt = browser.get_text()\n browser.go_to(\"https://home.openweathermap.org/users/sign_up\")\n inputs_visible = browser.get_form_inputs()\n print(\"inputs:\", inputs_visible)\n #inputs_fill = ['[q](checked)', '[q](checked)', '[user[username]](mlg)', '[user[email]](mlg.fcu@gmail.com)', '[user[password]](placeholder_P@ssw0rd123)', '[user[password_confirmation]](placeholder_P@ssw0rd123)']\n #browser.fill_form(inputs_fill)\n input(\"press enter to exit\")\n\n# Test sites for browser fingerprinting and captcha\n# https://nowsecure.nl/\n# https://bot.sannysoft.com\n# https://browserleaks.com/\n# https://bot.incolumitas.com/\n# https://fingerprintjs.github.io/fingerprintjs/\n# https://antoinevastel.com/bots/"], ["/agenticSeek/sources/tools/PyInterpreter.py", "\nimport sys\nimport os\nimport re\nfrom io import StringIO\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass PyInterpreter(Tools):\n \"\"\"\n This class is a tool to allow agent for python code execution.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"python\"\n self.name = \"Python Interpreter\"\n self.description = \"This tool allows the agent to execute python code.\"\n\n def execute(self, codes:str, safety = False) -> str:\n \"\"\"\n Execute python code.\n \"\"\"\n output = \"\"\n if safety and input(\"Execute code ? y/n\") != \"y\":\n return \"Code rejected by user.\"\n stdout_buffer = StringIO()\n sys.stdout = stdout_buffer\n global_vars = {\n '__builtins__': __builtins__,\n 'os': os,\n 'sys': sys,\n '__name__': '__main__'\n }\n code = '\\n\\n'.join(codes)\n self.logger.info(f\"Executing code:\\n{code}\")\n try:\n try:\n buffer = exec(code, global_vars)\n self.logger.info(f\"Code executed successfully.\\noutput:{buffer}\")\n print(buffer)\n if buffer is not None:\n output = buffer + '\\n'\n except SystemExit:\n self.logger.info(\"SystemExit caught, code execution stopped.\")\n output = stdout_buffer.getvalue()\n return f\"[SystemExit caught] Output before exit:\\n{output}\"\n except Exception as e:\n self.logger.error(f\"Code execution failed: {str(e)}\")\n return \"code execution failed:\" + str(e)\n output = stdout_buffer.getvalue()\n finally:\n self.logger.info(\"Code execution finished.\")\n sys.stdout = sys.__stdout__\n return output\n\n def interpreter_feedback(self, output:str) -> str:\n \"\"\"\n Provide feedback based on the output of the code execution\n \"\"\"\n if self.execution_failure_check(output):\n feedback = f\"[failure] Error in execution:\\n{output}\"\n else:\n feedback = \"[success] Execution success, code output:\\n\" + output\n return feedback\n\n def execution_failure_check(self, feedback:str) -> bool:\n \"\"\"\n Check if the code execution failed.\n \"\"\"\n error_patterns = [\n r\"expected\", \n r\"errno\", \n r\"failed\", \n r\"traceback\", \n r\"invalid\", \n r\"unrecognized\", \n r\"exception\", \n r\"syntax\", \n r\"crash\", \n r\"segmentation fault\", \n r\"core dumped\"\n ]\n combined_pattern = \"|\".join(error_patterns)\n if re.search(combined_pattern, feedback, re.IGNORECASE):\n self.logger.error(f\"Execution failure detected: {feedback}\")\n return True\n self.logger.info(\"No execution success detected.\")\n return False\n\nif __name__ == \"__main__\":\n text = \"\"\"\nFor Python, let's also do a quick check:\n\n```python\nprint(\"Hello from Python!\")\n```\n\nIf these work, you'll see the outputs in the next message. Let me know if you'd like me to test anything specific! \n\nhere is a save test\n```python:tmp.py\n\ndef print_hello():\n hello = \"Hello World\"\n print(hello)\n\nif __name__ == \"__main__\":\n print_hello()\n```\n\"\"\"\n py = PyInterpreter()\n codes, save_path = py.load_exec_block(text)\n py.save_block(codes, save_path)\n print(py.execute(codes))"], ["/agenticSeek/sources/tools/webSearch.py", "\nimport os\nimport requests\nimport dotenv\n\ndotenv.load_dotenv()\n\nfrom sources.tools.tools import Tools\nfrom sources.utility import animate_thinking, pretty_print\n\n\"\"\"\nWARNING\nwebSearch is fully deprecated and is being replaced by searxSearch for web search.\n\"\"\"\n\nclass webSearch(Tools):\n def __init__(self, api_key: str = None):\n \"\"\"\n A tool to perform a Google search and return information from the first result.\n \"\"\"\n super().__init__()\n self.tag = \"web_search\"\n self.api_key = api_key or os.getenv(\"SERPAPI_KEY\") # Requires a SerpApi key\n self.paywall_keywords = [\n \"subscribe\", \"login to continue\", \"access denied\", \"restricted content\", \"404\", \"this page is not working\"\n ]\n\n def link_valid(self, link):\n \"\"\"check if a link is valid.\"\"\"\n if not link.startswith(\"http\"):\n return \"Status: Invalid URL\"\n \n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\"}\n try:\n response = requests.get(link, headers=headers, timeout=5)\n status = response.status_code\n if status == 200:\n content = response.text[:1000].lower()\n if any(keyword in content for keyword in self.paywall_keywords):\n return \"Status: Possible Paywall\"\n return \"Status: OK\"\n elif status == 404:\n return \"Status: 404 Not Found\"\n elif status == 403:\n return \"Status: 403 Forbidden\"\n else:\n return f\"Status: {status} {response.reason}\"\n except requests.exceptions.RequestException as e:\n return f\"Error: {str(e)}\"\n\n def check_all_links(self, links):\n \"\"\"Check all links, one by one.\"\"\"\n # TODO Make it asyncromous or smth\n statuses = []\n for i, link in enumerate(links):\n status = self.link_valid(link)\n statuses.append(status)\n return statuses\n\n def execute(self, blocks: str, safety: bool = True) -> str:\n if self.api_key is None:\n return \"Error: No SerpApi key provided.\"\n for block in blocks:\n query = block.strip()\n pretty_print(f\"Searching for: {query}\", color=\"status\")\n if not query:\n return \"Error: No search query provided.\"\n\n try:\n url = \"https://serpapi.com/search\"\n params = {\n \"q\": query,\n \"api_key\": self.api_key,\n \"num\": 50,\n \"output\": \"json\"\n }\n response = requests.get(url, params=params)\n response.raise_for_status()\n\n data = response.json()\n results = []\n if \"organic_results\" in data and len(data[\"organic_results\"]) > 0:\n organic_results = data[\"organic_results\"][:50]\n links = [result.get(\"link\", \"No link available\") for result in organic_results]\n statuses = self.check_all_links(links)\n for result, status in zip(organic_results, statuses):\n if not \"OK\" in status:\n continue\n title = result.get(\"title\", \"No title\")\n snippet = result.get(\"snippet\", \"No snippet available\")\n link = result.get(\"link\", \"No link available\")\n results.append(f\"Title:{title}\\nSnippet:{snippet}\\nLink:{link}\")\n return \"\\n\\n\".join(results)\n else:\n return \"No results found for the query.\"\n except requests.RequestException as e:\n return f\"Error during web search: {str(e)}\"\n except Exception as e:\n return f\"Unexpected error: {str(e)}\"\n return \"No search performed\"\n\n def execution_failure_check(self, output: str) -> bool:\n return output.startswith(\"Error\") or \"No results found\" in output\n\n def interpreter_feedback(self, output: str) -> str:\n if self.execution_failure_check(output):\n return f\"Web search failed: {output}\"\n return f\"Web search result:\\n{output}\"\n\n\nif __name__ == \"__main__\":\n search_tool = webSearch(api_key=os.getenv(\"SERPAPI_KEY\"))\n query = \"when did covid start\"\n result = search_tool.execute([query], safety=True)\n output = search_tool.interpreter_feedback(result)\n print(output)"], ["/agenticSeek/sources/tools/mcpFinder.py", "import os, sys\nimport requests\nfrom urllib.parse import urljoin\nfrom typing import Dict, Any, Optional\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass MCP_finder(Tools):\n \"\"\"\n Tool to find MCPs server\n \"\"\"\n def __init__(self, api_key: str = None):\n super().__init__()\n self.tag = \"mcp_finder\"\n self.name = \"MCP Finder\"\n self.description = \"Find MCP servers and their tools\"\n self.base_url = \"https://registry.smithery.ai\"\n self.headers = {\n \"Authorization\": f\"Bearer {api_key}\",\n \"Content-Type\": \"application/json\"\n }\n\n def _make_request(self, method: str, endpoint: str, params: Optional[Dict] = None, \n data: Optional[Dict] = None) -> Dict[str, Any]:\n url = urljoin(self.base_url.rstrip(), endpoint)\n try:\n response = requests.request(\n method=method,\n url=url,\n headers=self.headers,\n params=params,\n json=data\n )\n response.raise_for_status()\n return response.json()\n except requests.exceptions.HTTPError as e:\n raise requests.exceptions.HTTPError(f\"API request failed: {str(e)}\")\n except requests.exceptions.RequestException as e:\n raise requests.exceptions.RequestException(f\"Network error: {str(e)}\")\n\n def list_mcp_servers(self, page: int = 1, page_size: int = 5000) -> Dict[str, Any]:\n params = {\"page\": page, \"pageSize\": page_size}\n return self._make_request(\"GET\", \"/servers\", params=params)\n\n def get_mcp_server_details(self, qualified_name: str) -> Dict[str, Any]:\n endpoint = f\"/servers/{qualified_name}\"\n return self._make_request(\"GET\", endpoint)\n \n def find_mcp_servers(self, query: str) -> Dict[str, Any]:\n \"\"\"\n Finds a specific MCP server by its name.\n Args:\n query (str): a name or string that more or less matches the MCP server name.\n Returns:\n Dict[str, Any]: The details of the found MCP server or an error message.\n \"\"\"\n mcps = self.list_mcp_servers()\n matching_mcp = []\n for mcp in mcps.get(\"servers\", []):\n name = mcp.get(\"qualifiedName\", \"\")\n if query.lower() in name.lower():\n details = self.get_mcp_server_details(name)\n matching_mcp.append(details)\n return matching_mcp\n \n def execute(self, blocks: list, safety:bool = False) -> str:\n if not blocks or not isinstance(blocks, list):\n return \"Error: No blocks provided\\n\"\n\n output = \"\"\n for block in blocks:\n block_clean = block.strip().lower().replace('\\n', '')\n try:\n matching_mcp_infos = self.find_mcp_servers(block_clean)\n except requests.exceptions.RequestException as e:\n output += \"Connection failed. Is the API key in environment?\\n\"\n continue\n except Exception as e:\n output += f\"Error: {str(e)}\\n\"\n continue\n if matching_mcp_infos == []:\n output += f\"Error: No MCP server found for query '{block}'\\n\"\n continue\n for mcp_infos in matching_mcp_infos:\n if mcp_infos['tools'] is None:\n continue\n output += f\"Name: {mcp_infos['displayName']}\\n\"\n output += f\"Usage name: {mcp_infos['qualifiedName']}\\n\"\n output += f\"Tools: {mcp_infos['tools']}\"\n output += \"\\n-------\\n\"\n return output.strip()\n\n def execution_failure_check(self, output: str) -> bool:\n output = output.strip().lower()\n if not output:\n return True\n if \"error\" in output or \"not found\" in output:\n return True\n return False\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Not really needed for this tool (use return of execute() directly)\n \"\"\"\n if not output:\n raise ValueError(\"No output to interpret.\")\n return f\"\"\"\n The following MCPs were found:\n {output}\n \"\"\"\n\nif __name__ == \"__main__\":\n api_key = os.getenv(\"MCP_FINDER\")\n tool = MCP_finder(api_key)\n result = tool.execute([\"\"\"\nstock\n\"\"\"], False)\n print(result)\n"], ["/agenticSeek/sources/tools/C_Interpreter.py", "import subprocess\nimport os, sys\nimport tempfile\nimport re\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass CInterpreter(Tools):\n \"\"\"\n This class is a tool to allow agent for C code execution\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"c\"\n self.name = \"C Interpreter\"\n self.description = \"This tool allows the agent to execute C code.\"\n\n def execute(self, codes: str, safety=False) -> str:\n \"\"\"\n Execute C code by compiling and running it.\n \"\"\"\n output = \"\"\n code = '\\n'.join(codes) if isinstance(codes, list) else codes\n \n if safety and input(\"Execute code? y/n \") != \"y\":\n return \"Code rejected by user.\"\n\n exec_extension = \".exe\" if os.name == \"nt\" else \"\" # Windows uses .exe, Linux/Unix does not\n \n with tempfile.TemporaryDirectory() as tmpdirname:\n source_file = os.path.join(tmpdirname, \"temp.c\")\n exec_file = os.path.join(tmpdirname, \"temp\") + exec_extension\n with open(source_file, 'w') as f:\n f.write(code)\n\n try:\n compile_command = [\"gcc\", source_file, \"-o\", exec_file]\n compile_result = subprocess.run(\n compile_command,\n capture_output=True,\n text=True,\n timeout=60\n )\n\n if compile_result.returncode != 0:\n return f\"Compilation failed: {compile_result.stderr}\"\n\n run_command = [exec_file]\n run_result = subprocess.run(\n run_command,\n capture_output=True,\n text=True,\n timeout=120\n )\n\n if run_result.returncode != 0:\n return f\"Execution failed: {run_result.stderr}\"\n output = run_result.stdout\n\n except subprocess.TimeoutExpired as e:\n return f\"Execution timed out: {str(e)}\"\n except FileNotFoundError:\n return \"Error: 'gcc' not found. Ensure a C compiler (e.g., gcc) is installed and in PATH.\"\n except Exception as e:\n return f\"Code execution failed: {str(e)}\"\n\n return output\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Provide feedback based on the output of the code execution\n \"\"\"\n if self.execution_failure_check(output):\n feedback = f\"[failure] Error in execution:\\n{output}\"\n else:\n feedback = \"[success] Execution success, code output:\\n\" + output\n return feedback\n\n def execution_failure_check(self, feedback: str) -> bool:\n \"\"\"\n Check if the code execution failed.\n \"\"\"\n error_patterns = [\n r\"error\", \n r\"failed\", \n r\"traceback\", \n r\"invalid\", \n r\"exception\", \n r\"syntax\", \n r\"segmentation fault\", \n r\"core dumped\", \n r\"undefined\", \n r\"cannot\"\n ]\n combined_pattern = \"|\".join(error_patterns)\n if re.search(combined_pattern, feedback, re.IGNORECASE):\n return True\n return False\n\nif __name__ == \"__main__\":\n codes = [\n\"\"\"\n#include \n#include \n\nvoid hello() {\n printf(\"Hello, World!\\\\n\");\n}\n\"\"\",\n\"\"\"\nint main() {\n hello();\n return 0;\n}\n \"\"\"]\n c = CInterpreter()\n print(c.execute(codes))"], ["/agenticSeek/sources/router.py", "import os\nimport sys\nimport torch\nimport random\nfrom typing import List, Tuple, Type, Dict\n\nfrom transformers import pipeline\nfrom adaptive_classifier import AdaptiveClassifier\n\nfrom sources.agents.agent import Agent\nfrom sources.agents.code_agent import CoderAgent\nfrom sources.agents.casual_agent import CasualAgent\nfrom sources.agents.planner_agent import FileAgent\nfrom sources.agents.browser_agent import BrowserAgent\nfrom sources.language import LanguageUtility\nfrom sources.utility import pretty_print, animate_thinking, timer_decorator\nfrom sources.logger import Logger\n\nclass AgentRouter:\n \"\"\"\n AgentRouter is a class that selects the appropriate agent based on the user query.\n \"\"\"\n def __init__(self, agents: list, supported_language: List[str] = [\"en\", \"fr\", \"zh\"]):\n self.agents = agents\n self.logger = Logger(\"router.log\")\n self.lang_analysis = LanguageUtility(supported_language=supported_language)\n self.pipelines = self.load_pipelines()\n self.talk_classifier = self.load_llm_router()\n self.complexity_classifier = self.load_llm_router()\n self.learn_few_shots_tasks()\n self.learn_few_shots_complexity()\n self.asked_clarify = False\n \n def load_pipelines(self) -> Dict[str, Type[pipeline]]:\n \"\"\"\n Load the pipelines for the text classification used for routing.\n returns:\n Dict[str, Type[pipeline]]: The loaded pipelines\n \"\"\"\n animate_thinking(\"Loading zero-shot pipeline...\", color=\"status\")\n return {\n \"bart\": pipeline(\"zero-shot-classification\", model=\"facebook/bart-large-mnli\")\n }\n\n def load_llm_router(self) -> AdaptiveClassifier:\n \"\"\"\n Load the LLM router model.\n returns:\n AdaptiveClassifier: The loaded model\n exceptions:\n Exception: If the safetensors fails to load\n \"\"\"\n path = \"../llm_router\" if __name__ == \"__main__\" else \"./llm_router\"\n try:\n animate_thinking(\"Loading LLM router model...\", color=\"status\")\n talk_classifier = AdaptiveClassifier.from_pretrained(path)\n except Exception as e:\n raise Exception(\"Failed to load the routing model. Please run the dl_safetensors.sh script inside llm_router/ directory to download the model.\")\n return talk_classifier\n\n def get_device(self) -> str:\n if torch.backends.mps.is_available():\n return \"mps\"\n elif torch.cuda.is_available():\n return \"cuda:0\"\n else:\n return \"cpu\"\n \n def learn_few_shots_complexity(self) -> None:\n \"\"\"\n Few shot learning for complexity estimation.\n Use the build in add_examples method of the Adaptive_classifier.\n \"\"\"\n few_shots = [\n (\"hi\", \"LOW\"),\n (\"How it's going ?\", \"LOW\"),\n (\"What’s the weather like today?\", \"LOW\"),\n (\"Can you find a file named ‘notes.txt’ in my Documents folder?\", \"LOW\"),\n (\"Write a Python script to generate a random password\", \"LOW\"),\n (\"Debug this JavaScript code that’s not running properly\", \"LOW\"),\n (\"Search the web for the cheapest laptop under $500\", \"LOW\"),\n (\"Locate a file called ‘report_2024.pdf’ on my drive\", \"LOW\"),\n (\"Check if a folder named ‘Backups’ exists on my system\", \"LOW\"),\n (\"Can you find ‘family_vacation.mp4’ in my Videos folder?\", \"LOW\"),\n (\"Search my drive for a file named ‘todo_list.xlsx’\", \"LOW\"),\n (\"Write a Python function to check if a string is a palindrome\", \"LOW\"),\n (\"Can you search the web for startups in Berlin?\", \"LOW\"),\n (\"Find recent articles on blockchain technology online\", \"LOW\"),\n (\"Check if ‘Personal_Projects’ folder exists on my desktop\", \"LOW\"),\n (\"Create a bash script to list all running processes\", \"LOW\"),\n (\"Debug this Python script that’s crashing on line 10\", \"LOW\"),\n (\"Browse the web to find out who invented Python\", \"LOW\"),\n (\"Locate a file named ‘shopping_list.txt’ on my system\", \"LOW\"),\n (\"Search the web for tips on staying productive\", \"LOW\"),\n (\"Find ‘sales_pitch.pptx’ in my Downloads folder\", \"LOW\"),\n (\"can you find a file called resume.docx on my drive?\", \"LOW\"),\n (\"can you write a python script to check if the device on my network is connected to the internet\", \"LOW\"),\n (\"can you debug this Java code? It’s not working.\", \"LOW\"),\n (\"can you find the old_project.zip file somewhere on my drive?\", \"LOW\"),\n (\"can you locate the backup folder I created last month on my system?\", \"LOW\"),\n (\"could you check if the presentation.pdf file exists in my downloads?\", \"LOW\"),\n (\"search my drive for a file called vacation_photos_2023.jpg.\", \"LOW\"),\n (\"help me organize my desktop files into folders by type.\", \"LOW\"),\n (\"make a blackjack in golang\", \"LOW\"),\n (\"write a python script to ping a website\", \"LOW\"),\n (\"write a simple Java program to print 'Hello World'\", \"LOW\"),\n (\"write a Java program to calculate the area of a circle\", \"LOW\"),\n (\"write a Python function to sort a list of dictionaries by key\", \"LOW\"),\n (\"can you search for startup in tokyo?\", \"LOW\"),\n (\"find the latest updates on quantum computing on the web\", \"LOW\"),\n (\"check if the folder ‘Work_Projects’ exists on my desktop\", \"LOW\"),\n (\" can you browse the web, use overpass-turbo to show fountains in toulouse\", \"LOW\"),\n (\"search the web for the best budget smartphones of 2025\", \"LOW\"),\n (\"write a Python script to download all images from a webpage\", \"LOW\"),\n (\"create a bash script to monitor CPU usage\", \"LOW\"),\n (\"debug this C++ code that keeps crashing\", \"LOW\"),\n (\"can you browse the web to find out who fosowl is ?\", \"LOW\"),\n (\"find the file ‘important_notes.txt’\", \"LOW\"),\n (\"search the web for the best ways to learn a new language\", \"LOW\"),\n (\"locate the file ‘presentation.pptx’ in my Documents folder\", \"LOW\"),\n (\"Make a 3d game in javascript using three.js\", \"LOW\"),\n (\"Find the latest research papers on AI and build save in a file\", \"HIGH\"),\n (\"Make a web server in go that serve a simple html page\", \"LOW\"),\n (\"Search the web for the cheapest 4K monitor and provide a link\", \"LOW\"),\n (\"Write a JavaScript function to reverse a string\", \"LOW\"),\n (\"Can you locate a file called ‘budget_2025.xlsx’ on my system?\", \"LOW\"),\n (\"Search the web for recent articles on space exploration\", \"LOW\"),\n (\"when is the exam period for master student in france?\", \"LOW\"),\n (\"Check if a folder named ‘Photos_2024’ exists on my desktop\", \"LOW\"),\n (\"Can you look up some nice knitting patterns on that web thingy?\", \"LOW\"),\n (\"Goodness, check if my ‘Photos_Grandkids’ folder is still on the desktop\", \"LOW\"),\n (\"Create a Python script to rename all files in a folder based on their creation date\", \"LOW\"),\n (\"Can you find a file named ‘meeting_notes.txt’ in my Downloads folder?\", \"LOW\"),\n (\"Write a Go program to check if a port is open on a network\", \"LOW\"),\n (\"Search the web for the latest electric car reviews\", \"LOW\"),\n (\"Write a Python function to merge two sorted lists\", \"LOW\"),\n (\"Create a bash script to monitor disk space and alert via text file\", \"LOW\"),\n (\"What’s out there on the web about cheap travel spots?\", \"LOW\"),\n (\"Search X for posts about AI ethics and summarize them\", \"LOW\"),\n (\"Check if a file named ‘project_proposal.pdf’ exists in my Documents\", \"LOW\"),\n (\"Search the web for tips on improving coding skills\", \"LOW\"),\n (\"Write a Python script to count words in a text file\", \"LOW\"),\n (\"Search the web for restaurant\", \"LOW\"),\n (\"Use a MCP to find the latest stock market data\", \"LOW\"),\n (\"Use a MCP to send an email to my boss\", \"LOW\"),\n (\"Could you use a MCP to find the latest news on climate change?\", \"LOW\"),\n (\"Create a simple HTML page with CSS styling\", \"LOW\"),\n (\"Use file.txt and then use it to ...\", \"HIGH\"),\n (\"Yo, what’s good? Find my ‘mixtape.mp3’ real quick\", \"LOW\"),\n (\"Can you follow the readme and install the project\", \"HIGH\"),\n (\"Man, write me a dope Python script to flex some random numbers\", \"LOW\"),\n (\"Search the web for peer-reviewed articles on gene editing\", \"LOW\"),\n (\"Locate ‘meeting_notes.docx’ in Downloads, I’m late for this call\", \"LOW\"),\n (\"Make the game less hard\", \"LOW\"),\n (\"Why did it fail?\", \"LOW\"),\n (\"Write a Python script to list all .pdf files in my Documents\", \"LOW\"),\n (\"Write a Python thing to sort my .jpg files by date\", \"LOW\"),\n (\"make a snake game please\", \"LOW\"),\n (\"Find ‘gallery_list.pdf’, then build a web app to show my pics\", \"HIGH\"),\n (\"Find ‘budget_2025.xlsx’, analyze it, and make a chart for my boss\", \"HIGH\"),\n (\"I want you to make me a plan to travel to Tainan\", \"HIGH\"),\n (\"Retrieve the latest publications on CRISPR and develop a web application to display them\", \"HIGH\"),\n (\"Bro dig up a music API and build me a tight app for the hottest tracks\", \"HIGH\"),\n (\"Find a public API for sports scores and build a web app to show live updates\", \"HIGH\"),\n (\"Find a public API for book data and create a Flask app to list bestsellers\", \"HIGH\"),\n (\"Organize my desktop files by extension and then write a script to list them\", \"HIGH\"),\n (\"Find the latest research on renewable energy and build a web app to display it\", \"HIGH\"),\n (\"search online for popular sci-fi movies from 2024 and pick three to watch tonight. Save the list in movie_night.txt\", \"HIGH\"),\n (\"can you find vitess repo, clone it and install by following the readme\", \"HIGH\"),\n (\"Create a JavaScript game using Phaser.js with multiple levels\", \"HIGH\"),\n (\"Search the web for the latest trends in web development and build a sample site\", \"HIGH\"),\n (\"Use my research_note.txt file, double check the informations on the web\", \"HIGH\"),\n (\"Make a web server in go that query a flight API and display them in a app\", \"HIGH\"),\n (\"Search the web for top cafes in Rennes, France, and save a list of three with their addresses in rennes_cafes.txt.\", \"HIGH\"),\n (\"Search the web for the latest trends in AI and demo it in pytorch\", \"HIGH\"),\n (\"can you lookup for api that track flight and build a web flight tracking app\", \"HIGH\"),\n (\"Find the file toto.pdf then use its content to reply to Jojo on superforum.com\", \"HIGH\"),\n (\"Create a whole web app in python using the flask framework that query news API\", \"HIGH\"),\n (\"Create a bash script that monitor the CPU usage and send an email if it's too high\", \"HIGH\"),\n (\"Make a web search for latest news on the stock market and display them with python\", \"HIGH\"),\n (\"Find my resume file, apply to job that might fit online\", \"HIGH\"),\n (\"Can you find a weather API and build a Python app to display current weather\", \"HIGH\"),\n (\"Create a Python web app using Flask to track cryptocurrency prices from an API\", \"HIGH\"),\n (\"Search the web for tutorials on machine learning and build a simple ML model in Python\", \"HIGH\"),\n (\"Find a public API for movie data and build a web app to display movie ratings\", \"HIGH\"),\n (\"Create a Node.js server that queries a public API for traffic data and displays it\", \"HIGH\"),\n (\"can you find api and build a python web app with it ?\", \"HIGH\"),\n (\"do a deep search of current AI player for 2025 and make me a report in a file\", \"HIGH\"),\n (\"Find a public API for recipe data and build a web app to display recipes\", \"HIGH\"),\n (\"Search the web for recent space mission updates and build a Flask app\", \"HIGH\"),\n (\"Create a Python script to scrape a website and save data to a database\", \"HIGH\"),\n (\"Find a shakespear txt then train a transformers on it to generate text\", \"HIGH\"),\n (\"Find a public API for fitness tracking and build a web app to show stats\", \"HIGH\"),\n (\"Search the web for tutorials on web development and build a sample site\", \"HIGH\"),\n (\"Create a Node.js app to query a public API for event listings and display them\", \"HIGH\"),\n (\"Find a file named ‘budget.xlsx’, analyze its data, and generate a chart\", \"HIGH\"),\n ]\n random.shuffle(few_shots)\n texts = [text for text, _ in few_shots]\n labels = [label for _, label in few_shots]\n self.complexity_classifier.add_examples(texts, labels)\n\n def learn_few_shots_tasks(self) -> None:\n \"\"\"\n Few shot learning for tasks classification.\n Use the build in add_examples method of the Adaptive_classifier.\n \"\"\"\n few_shots = [\n (\"Write a python script to check if the device on my network is connected to the internet\", \"coding\"),\n (\"Hey could you search the web for the latest news on the tesla stock market ?\", \"web\"),\n (\"I would like you to search for weather api\", \"web\"),\n (\"Plan a 3-day trip to New York, including flights and hotels.\", \"web\"),\n (\"Find on the web the latest research papers on AI.\", \"web\"),\n (\"Can you debug this Java code? It’s not working.\", \"code\"),\n (\"Can you browse the web and find me a 4090 for cheap?\", \"web\"),\n (\"i would like to setup a new AI project, index as mark2\", \"files\"),\n (\"Hey, can you find the old_project.zip file somewhere on my drive?\", \"files\"),\n (\"Tell me a funny story\", \"talk\"),\n (\"can you make a snake game in python\", \"code\"),\n (\"Can you locate the backup folder I created last month on my system?\", \"files\"),\n (\"Share a random fun fact about space.\", \"talk\"),\n (\"Write a script to rename all files in a directory to lowercase.\", \"files\"),\n (\"Could you check if the presentation.pdf file exists in my downloads?\", \"files\"),\n (\"Tell me about the weirdest dream you’ve ever heard of.\", \"talk\"),\n (\"Search my drive for a file called vacation_photos_2023.jpg.\", \"files\"),\n (\"Help me organize my desktop files into folders by type.\", \"files\"),\n (\"What’s your favorite movie and why?\", \"talk\"),\n (\"what directory are you in ?\", \"files\"),\n (\"what files you seing rn ?\", \"files\"),\n (\"When is the period of university exam in france ?\", \"web\"),\n (\"Search my drive for a file named budget_2024.xlsx\", \"files\"),\n (\"Write a Python function to sort a list of dictionaries by key\", \"code\"),\n (\"Find the latest updates on quantum computing on the web\", \"web\"),\n (\"Check if the folder ‘Work_Projects’ exists on my desktop\", \"files\"),\n (\"Create a bash script to monitor CPU usage\", \"code\"),\n (\"Search online for the best budget smartphones of 2025\", \"web\"),\n (\"What’s the strangest food combination you’ve heard of?\", \"talk\"),\n (\"Move all .txt files from Downloads to a new folder called Notes\", \"files\"),\n (\"Debug this C++ code that keeps crashing\", \"code\"),\n (\"can you browse the web to find out who fosowl is ?\", \"web\"),\n (\"Find the file ‘important_notes.txt’\", \"files\"),\n (\"Find out the latest news on the upcoming Mars mission\", \"web\"),\n (\"Write a Java program to calculate the area of a circle\", \"code\"),\n (\"Search the web for the best ways to learn a new language\", \"web\"),\n (\"Locate the file ‘presentation.pptx’ in my Documents folder\", \"files\"),\n (\"Write a Python script to download all images from a webpage\", \"code\"),\n (\"Search the web for the latest trends in AI and machine learning\", \"web\"),\n (\"Tell me about a time when you had to solve a difficult problem\", \"talk\"),\n (\"Organize all image files on my desktop into a folder called ‘Pictures’\", \"files\"),\n (\"Generate a Ruby script to calculate Fibonacci numbers up to 100\", \"code\"),\n (\"Find out what device are connected to my network\", \"code\"),\n (\"Show me how much disk space is left on my drive\", \"code\"),\n (\"Look up recent posts on X about climate change\", \"web\"),\n (\"Find the photo I took last week named sunset_beach.jpg\", \"files\"),\n (\"Write a JavaScript snippet to fetch data from an API\", \"code\"),\n (\"Search the web for tutorials on machine learning with Python\", \"web\"),\n (\"Locate the file ‘meeting_notes.docx’ in my Documents folder\", \"files\"),\n (\"Write a Python script to scrape a website’s title and links\", \"code\"),\n (\"Search the web for the latest breakthroughs in fusion energy\", \"web\"),\n (\"Tell me about a historical event that sounds too wild to be true\", \"talk\"),\n (\"Organize all image files on my desktop into a folder called ‘Pictures’\", \"files\"),\n (\"Generate a Ruby script to calculate Fibonacci numbers up to 100\", \"code\"),\n (\"Find recent X posts about SpaceX’s next rocket launch\", \"web\"),\n (\"What’s the funniest misunderstanding you’ve seen between humans and AI?\", \"talk\"),\n (\"Check if ‘backup_032025.zip’ exists anywhere on my drive\", \"files\" ),\n (\"Create a shell script to automate backups of a directory\", \"code\"),\n (\"Look up the top AI conferences happening in 2025 online\", \"web\"),\n (\"Write a C# program to simulate a basic calculator\", \"code\"),\n (\"Browse the web for open-source alternatives to Photoshop\", \"web\"),\n (\"Hey how are you\", \"talk\"),\n (\"Write a Python script to ping a website\", \"code\"),\n (\"Search the web for the latest iPhone release\", \"web\"),\n (\"What’s the weather like today?\", \"web\"),\n (\"Hi, how’s your day going?\", \"talk\"),\n (\"Can you find a file called resume.docx on my drive?\", \"files\"),\n (\"Write a simple Java program to print 'Hello World'\", \"code\"),\n (\"can you find the current stock of Tesla?\", \"web\"),\n (\"Tell me a quick joke\", \"talk\"),\n (\"Search online for the best coffee shops in Seattle\", \"web\"),\n (\"Check if ‘project_plan.pdf’ exists in my Downloads folder\", \"files\"),\n (\"What’s your favorite color?\", \"talk\"),\n (\"Write a bash script to list all files in a directory\", \"code\"),\n (\"Find recent X posts about electric cars\", \"web\"),\n (\"Hey, you doing okay?\", \"talk\"),\n (\"Locate the file ‘family_photo.jpg’ on my system\", \"files\"),\n (\"Search the web for beginner guitar lessons\", \"web\"),\n (\"Write a Python function to reverse a string\", \"code\"),\n (\"What’s the weirdest animal you know of?\", \"talk\"),\n (\"Organize all .pdf files on my desktop into a ‘Documents’ folder\", \"files\"),\n (\"Browse the web for the latest space mission updates\", \"web\"),\n (\"Hey, what’s up with you today?\", \"talk\"),\n (\"Write a JavaScript function to add two numbers\", \"code\"),\n (\"Find the file ‘notes.txt’ in my Documents folder\", \"files\"),\n (\"Tell me something random about the ocean\", \"talk\"),\n (\"Search the web for cheap flights to Paris\", \"web\"),\n (\"Check if ‘budget.xlsx’ is on my drive\", \"files\"),\n (\"Write a Python script to count words in a text file\", \"code\"),\n (\"How’s it going today?\", \"talk\"),\n (\"Find recent X posts about AI advancements\", \"web\"),\n (\"Move all .jpg files from Downloads to a ‘Photos’ folder\", \"files\"),\n (\"Search online for the best laptops of 2025\", \"web\"),\n (\"What’s the funniest thing you’ve heard lately?\", \"talk\"),\n (\"Write a Ruby script to generate random numbers\", \"code\"),\n (\"Hey, how’s everything with you?\", \"talk\"),\n (\"Locate ‘meeting_agenda.docx’ in my system\", \"files\"),\n (\"Search the web for tips on growing indoor plants\", \"web\"),\n (\"Write a C++ program to calculate the sum of an array\", \"code\"),\n (\"Tell me a fun fact about dogs\", \"talk\"),\n (\"Check if the folder ‘Old_Projects’ exists on my desktop\", \"files\"),\n (\"Browse the web for the latest gaming console reviews\", \"web\"),\n (\"Hi, how are you feeling today?\", \"talk\"),\n (\"Write a Python script to check disk space\", \"code\"),\n (\"Find the file ‘vacation_itinerary.pdf’ on my drive\", \"files\"),\n (\"Search the web for news on renewable energy\", \"web\"),\n (\"What’s the strangest thing you’ve learned recently?\", \"talk\"),\n (\"Organize all video files into a ‘Videos’ folder\", \"files\"),\n (\"Write a shell script to delete temporary files\", \"code\"),\n (\"Hey, how’s your week been so far?\", \"talk\"),\n (\"Search online for the top movies of 2025\", \"web\"),\n (\"Locate ‘taxes_2024.xlsx’ in my Documents folder\", \"files\"),\n (\"Tell me about a cool invention from history\", \"talk\"),\n (\"Write a Java program to check if a number is even or odd\", \"code\"),\n (\"Find recent X posts about cryptocurrency trends\", \"web\"),\n (\"Hey, you good today?\", \"talk\"),\n (\"Search the web for easy dinner recipes\", \"web\"),\n (\"Check if ‘photo_backup.zip’ exists on my drive\", \"files\"),\n (\"Write a Python script to rename files with a timestamp\", \"code\"),\n (\"What’s your favorite thing about space?\", \"talk\"),\n (\"search for GPU with at least 24gb vram\", \"web\"),\n (\"Browse the web for the latest fitness trends\", \"web\"),\n (\"Move all .docx files to a ‘Work’ folder\", \"files\"),\n (\"I would like to make a new project called 'new_project'\", \"files\"),\n (\"I would like to setup a new project index as mark2\", \"files\"),\n (\"can you create a 3d js game that run in the browser\", \"code\"),\n (\"can you make a web app in python that use the flask framework\", \"code\"),\n (\"can you build a web server in go that serve a simple html page\", \"code\"),\n (\"can you find out who Jacky yougouri is ?\", \"web\"),\n (\"Can you use MCP to find stock market for IBM ?\", \"mcp\"),\n (\"Can you use MCP to to export my contacts to a csv file?\", \"mcp\"),\n (\"Can you use a MCP to find write notes to flomo\", \"mcp\"),\n (\"Can you use a MCP to query my calendar and find the next meeting?\", \"mcp\"),\n (\"Can you use a mcp to get the distance between Shanghai and Paris?\", \"mcp\"),\n (\"Setup a new flutter project called 'new_flutter_project'\", \"files\"),\n (\"can you create a new project called 'new_project'\", \"files\"),\n (\"can you make a simple web app that display a list of files in my dir\", \"code\"),\n (\"can you build a simple web server in python that serve a html page\", \"code\"),\n (\"find and buy me the latest rtx 4090\", \"web\"),\n (\"What are some good netflix show like Altered Carbon ?\", \"web\"),\n (\"can you find the latest research paper on AI\", \"web\"),\n (\"can you find research.pdf in my drive\", \"files\"),\n (\"hi\", \"talk\"),\n (\"hello\", \"talk\"),\n ]\n random.shuffle(few_shots)\n texts = [text for text, _ in few_shots]\n labels = [label for _, label in few_shots]\n self.talk_classifier.add_examples(texts, labels)\n\n def llm_router(self, text: str) -> tuple:\n \"\"\"\n Inference of the LLM router model.\n Args:\n text: The input text\n \"\"\"\n predictions = self.talk_classifier.predict(text)\n predictions = [pred for pred in predictions if pred[0] not in [\"HIGH\", \"LOW\"]]\n predictions = sorted(predictions, key=lambda x: x[1], reverse=True)\n return predictions[0]\n \n def router_vote(self, text: str, labels: list, log_confidence:bool = False) -> str:\n \"\"\"\n Vote between the LLM router and BART model.\n Args:\n text: The input text\n labels: The labels to classify\n Returns:\n str: The selected label\n \"\"\"\n if len(text) <= 8:\n return \"talk\"\n result_bart = self.pipelines['bart'](text, labels)\n result_llm_router = self.llm_router(text)\n bart, confidence_bart = result_bart['labels'][0], result_bart['scores'][0]\n llm_router, confidence_llm_router = result_llm_router[0], result_llm_router[1]\n final_score_bart = confidence_bart / (confidence_bart + confidence_llm_router)\n final_score_llm = confidence_llm_router / (confidence_bart + confidence_llm_router)\n self.logger.info(f\"Routing Vote for text {text}: BART: {bart} ({final_score_bart}) LLM-router: {llm_router} ({final_score_llm})\")\n if log_confidence:\n pretty_print(f\"Agent choice -> BART: {bart} ({final_score_bart}) LLM-router: {llm_router} ({final_score_llm})\")\n return bart if final_score_bart > final_score_llm else llm_router\n \n def find_first_sentence(self, text: str) -> str:\n first_sentence = None\n for line in text.split(\"\\n\"):\n first_sentence = line.strip()\n break\n if first_sentence is None:\n first_sentence = text\n return first_sentence\n \n def estimate_complexity(self, text: str) -> str:\n \"\"\"\n Estimate the complexity of the text.\n Args:\n text: The input text\n Returns:\n str: The estimated complexity\n \"\"\"\n try:\n predictions = self.complexity_classifier.predict(text)\n except Exception as e:\n pretty_print(f\"Error in estimate_complexity: {str(e)}\", color=\"failure\")\n return \"LOW\"\n predictions = sorted(predictions, key=lambda x: x[1], reverse=True)\n if len(predictions) == 0:\n return \"LOW\"\n complexity, confidence = predictions[0][0], predictions[0][1]\n if confidence < 0.5:\n self.logger.info(f\"Low confidence in complexity estimation: {confidence}\")\n return \"HIGH\"\n if complexity == \"HIGH\":\n return \"HIGH\"\n elif complexity == \"LOW\":\n return \"LOW\"\n pretty_print(f\"Failed to estimate the complexity of the text.\", color=\"failure\")\n return \"LOW\"\n \n def find_planner_agent(self) -> Agent:\n \"\"\"\n Find the planner agent.\n Returns:\n Agent: The planner agent\n \"\"\"\n for agent in self.agents:\n if agent.type == \"planner_agent\":\n return agent\n pretty_print(f\"Error finding planner agent. Please add a planner agent to the list of agents.\", color=\"failure\")\n self.logger.error(\"Planner agent not found.\")\n return None\n \n def select_agent(self, text: str) -> Agent:\n \"\"\"\n Select the appropriate agent based on the text.\n Args:\n text (str): The text to select the agent from\n Returns:\n Agent: The selected agent\n \"\"\"\n assert len(self.agents) > 0, \"No agents available.\"\n if len(self.agents) == 1:\n return self.agents[0]\n lang = self.lang_analysis.detect_language(text)\n text = self.find_first_sentence(text)\n text = self.lang_analysis.translate(text, lang)\n labels = [agent.role for agent in self.agents]\n complexity = self.estimate_complexity(text)\n if complexity == \"HIGH\":\n pretty_print(f\"Complex task detected, routing to planner agent.\", color=\"info\")\n return self.find_planner_agent()\n try:\n best_agent = self.router_vote(text, labels, log_confidence=False)\n except Exception as e:\n raise e\n for agent in self.agents:\n if best_agent == agent.role:\n role_name = agent.role\n pretty_print(f\"Selected agent: {agent.agent_name} (roles: {role_name})\", color=\"warning\")\n return agent\n pretty_print(f\"Error choosing agent.\", color=\"failure\")\n self.logger.error(\"No agent selected.\")\n return None\n\nif __name__ == \"__main__\":\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n agents = [\n CasualAgent(\"jarvis\", \"../prompts/base/casual_agent.txt\", None),\n BrowserAgent(\"browser\", \"../prompts/base/planner_agent.txt\", None),\n CoderAgent(\"coder\", \"../prompts/base/coder_agent.txt\", None),\n FileAgent(\"file\", \"../prompts/base/coder_agent.txt\", None)\n ]\n router = AgentRouter(agents)\n texts = [\n \"hi\",\n \"你好\",\n \"Bonjour\",\n \"Write a python script to check if the device on my network is connected to the internet\",\n \"Peut tu écrire un script python qui vérifie si l'appareil sur mon réseau est connecté à internet?\",\n \"写一个Python脚本,检查我网络上的设备是否连接到互联网\",\n \"Hey could you search the web for the latest news on the tesla stock market ?\",\n \"嘿,你能搜索网页上关于股票市场的最新新闻吗?\",\n \"Yo, cherche sur internet comment va tesla en bourse.\",\n \"I would like you to search for weather api and then make an app using this API\",\n \"我想让你搜索天气API,然后用这个API做一个应用程序\",\n \"J'aimerais que tu cherche une api météo et que l'utilise pour faire une application\",\n \"Plan a 3-day trip to New York, including flights and hotels.\",\n \"计划一次为期3天的纽约之旅,包括机票和酒店。\",\n \"Planifie un trip de 3 jours à Paris, y compris les vols et hotels.\",\n \"Find on the web the latest research papers on AI.\",\n \"在网上找到最新的人工智能研究论文。\",\n \"Trouve moi les derniers articles de recherche sur l'IA sur internet\",\n \"Help me write a C++ program to sort an array\",\n \"Tell me what France been up to lately\",\n \"告诉我法国最近在做什么\",\n \"Dis moi ce que la France a fait récemment\",\n \"Who is Sergio Pesto ?\",\n \"谁是Sergio Pesto?\",\n \"Qui est Sergio Pesto ?\",\n \"帮我写一个C++程序来排序数组\",\n \"Aide moi à faire un programme c++ pour trier une array.\",\n \"What’s the weather like today? Oh, and can you find a good weather app?\",\n \"今天天气怎么样?哦,你还能找到一个好的天气应用程序吗?\",\n \"La météo est comment aujourd'hui ? oh et trouve moi une bonne appli météo tant que tu y est.\",\n \"Can you debug this Java code? It’s not working.\",\n \"你能调试这段Java代码吗?它不起作用。\",\n \"Peut tu m'aider à debugger ce code java, ça marche pas\",\n \"Can you browse the web and find me a 4090 for cheap?\",\n \"你能浏览网页,为我找一个便宜的4090吗?\",\n \"Peut tu chercher sur internet et me trouver une 4090 pas cher ?\",\n \"Hey, can you find the old_project.zip file somewhere on my drive?\",\n \"嘿,你能在我驱动器上找到old_project.zip文件吗?\",\n \"Hé trouve moi le old_project.zip, il est quelque part sur mon disque.\",\n \"Tell me a funny story\",\n \"给我讲一个有趣的故事\",\n \"Raconte moi une histoire drole\"\n ]\n for text in texts:\n print(\"Input text:\", text)\n agent = router.select_agent(text)\n print()\n"], ["/agenticSeek/sources/tools/GoInterpreter.py", "import subprocess\nimport os, sys\nimport tempfile\nimport re\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass GoInterpreter(Tools):\n \"\"\"\n This class is a tool to allow execution of Go code.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"go\"\n self.name = \"Go Interpreter\"\n self.description = \"This tool allows you to execute Go code.\"\n\n def execute(self, codes: str, safety=False) -> str:\n \"\"\"\n Execute Go code by compiling and running it.\n \"\"\"\n output = \"\"\n code = '\\n'.join(codes) if isinstance(codes, list) else codes\n\n if safety and input(\"Execute code? y/n \") != \"y\":\n return \"Code rejected by user.\"\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n source_file = os.path.join(tmpdirname, \"temp.go\")\n exec_file = os.path.join(tmpdirname, \"temp\")\n with open(source_file, 'w') as f:\n f.write(code)\n\n try:\n env = os.environ.copy()\n env[\"GO111MODULE\"] = \"off\"\n compile_command = [\"go\", \"build\", \"-o\", exec_file, source_file]\n compile_result = subprocess.run(\n compile_command,\n capture_output=True,\n text=True,\n timeout=10,\n env=env\n )\n\n if compile_result.returncode != 0:\n return f\"Compilation failed: {compile_result.stderr}\"\n\n run_command = [exec_file]\n run_result = subprocess.run(\n run_command,\n capture_output=True,\n text=True,\n timeout=10\n )\n\n if run_result.returncode != 0:\n return f\"Execution failed: {run_result.stderr}\"\n output = run_result.stdout\n\n except subprocess.TimeoutExpired as e:\n return f\"Execution timed out: {str(e)}\"\n except FileNotFoundError:\n return \"Error: 'go' not found. Ensure Go is installed and in PATH.\"\n except Exception as e:\n return f\"Code execution failed: {str(e)}\"\n\n return output\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Provide feedback based on the output of the code execution\n \"\"\"\n if self.execution_failure_check(output):\n feedback = f\"[failure] Error in execution:\\n{output}\"\n else:\n feedback = \"[success] Execution success, code output:\\n\" + output\n return feedback\n\n def execution_failure_check(self, feedback: str) -> bool:\n \"\"\"\n Check if the code execution failed.\n \"\"\"\n error_patterns = [\n r\"error\",\n r\"failed\",\n r\"traceback\",\n r\"invalid\",\n r\"exception\",\n r\"syntax\",\n r\"panic\",\n r\"undefined\",\n r\"cannot\"\n ]\n combined_pattern = \"|\".join(error_patterns)\n if re.search(combined_pattern, feedback, re.IGNORECASE):\n return True\n return False\n\nif __name__ == \"__main__\":\n codes = [\n\"\"\"\npackage main\nimport \"fmt\"\n\nfunc hello() {\n fmt.Println(\"Hello, World!\")\n}\n\"\"\",\n\"\"\"\nfunc main() {\n hello()\n}\n\"\"\"\n ]\n g = GoInterpreter()\n print(g.execute(codes))\n"], ["/agenticSeek/sources/tools/flightSearch.py", "import os, sys\nimport requests\nimport dotenv\n\ndotenv.load_dotenv()\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass FlightSearch(Tools):\n def __init__(self, api_key: str = None):\n \"\"\"\n A tool to search for flight information using a flight number via SerpApi.\n \"\"\"\n super().__init__()\n self.tag = \"flight_search\"\n self.name = \"Flight Search\"\n self.description = \"Search for flight information using a flight number via SerpApi.\"\n self.api_key = api_key or os.getenv(\"SERPAPI_API_KEY\")\n\n def execute(self, blocks: str, safety: bool = True) -> str:\n if self.api_key is None:\n return \"Error: No SerpApi key provided.\"\n \n for block in blocks:\n flight_number = block.strip().upper().replace('\\n', '')\n if not flight_number:\n return \"Error: No flight number provided.\"\n\n try:\n url = \"https://serpapi.com/search\"\n params = {\n \"engine\": \"google_flights\",\n \"api_key\": self.api_key,\n \"q\": flight_number,\n \"type\": \"2\" # Flight status search\n }\n \n response = requests.get(url, params=params)\n response.raise_for_status()\n data = response.json()\n \n if \"flights\" in data and len(data[\"flights\"]) > 0:\n flight = data[\"flights\"][0]\n \n # Extract key information\n departure = flight.get(\"departure_airport\", {})\n arrival = flight.get(\"arrival_airport\", {})\n \n departure_code = departure.get(\"id\", \"Unknown\")\n departure_time = flight.get(\"departure_time\", \"Unknown\")\n arrival_code = arrival.get(\"id\", \"Unknown\") \n arrival_time = flight.get(\"arrival_time\", \"Unknown\")\n airline = flight.get(\"airline\", \"Unknown\")\n status = flight.get(\"flight_status\", \"Unknown\")\n\n return (\n f\"Flight: {flight_number}\\n\"\n f\"Airline: {airline}\\n\"\n f\"Status: {status}\\n\"\n f\"Departure: {departure_code} at {departure_time}\\n\"\n f\"Arrival: {arrival_code} at {arrival_time}\"\n )\n else:\n return f\"No flight information found for {flight_number}\"\n \n except requests.RequestException as e:\n return f\"Error during flight search: {str(e)}\"\n except Exception as e:\n return f\"Unexpected error: {str(e)}\"\n \n return \"No flight search performed\"\n\n def execution_failure_check(self, output: str) -> bool:\n return output.startswith(\"Error\") or \"No flight information found\" in output\n\n def interpreter_feedback(self, output: str) -> str:\n if self.execution_failure_check(output):\n return f\"Flight search failed: {output}\"\n return f\"Flight information:\\n{output}\"\n\n\nif __name__ == \"__main__\":\n flight_tool = FlightSearch()\n flight_number = \"AA123\"\n result = flight_tool.execute([flight_number], safety=True)\n feedback = flight_tool.interpreter_feedback(result)\n print(feedback)"], ["/agenticSeek/sources/speech_to_text.py", "from colorama import Fore\nfrom typing import List, Tuple, Type, Dict\nimport queue\nimport threading\nimport numpy as np\nimport time\n\nIMPORT_FOUND = True\n\ntry:\n import torch\n import librosa\n import pyaudio\n from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline\nexcept ImportError:\n print(Fore.RED + \"Speech To Text disabled.\" + Fore.RESET)\n IMPORT_FOUND = False\n\naudio_queue = queue.Queue()\ndone = False\n\nclass AudioRecorder:\n \"\"\"\n AudioRecorder is a class that records audio from the microphone and adds it to the audio queue.\n \"\"\"\n def __init__(self, format: int = pyaudio.paInt16, channels: int = 1, rate: int = 4096, chunk: int = 8192, record_seconds: int = 5, verbose: bool = False):\n self.format = format\n self.channels = channels\n self.rate = rate\n self.chunk = chunk\n self.record_seconds = record_seconds\n self.verbose = verbose\n self.thread = None\n self.audio = None\n if IMPORT_FOUND:\n self.audio = pyaudio.PyAudio()\n self.thread = threading.Thread(target=self._record, daemon=True)\n\n def _record(self) -> None:\n \"\"\"\n Record audio from the microphone and add it to the audio queue.\n \"\"\"\n if not IMPORT_FOUND:\n return\n stream = self.audio.open(format=self.format, channels=self.channels, rate=self.rate,\n input=True, frames_per_buffer=self.chunk)\n if self.verbose:\n print(Fore.GREEN + \"AudioRecorder: Started recording...\" + Fore.RESET)\n\n while not done:\n frames = []\n for _ in range(0, int(self.rate / self.chunk * self.record_seconds)):\n try:\n data = stream.read(self.chunk, exception_on_overflow=False)\n frames.append(data)\n except Exception as e:\n print(Fore.RED + f\"AudioRecorder: Failed to read stream - {e}\" + Fore.RESET)\n \n raw_data = b''.join(frames)\n audio_data = np.frombuffer(raw_data, dtype=np.int16)\n audio_queue.put((audio_data, self.rate))\n if self.verbose:\n print(Fore.GREEN + \"AudioRecorder: Added audio chunk to queue\" + Fore.RESET)\n\n stream.stop_stream()\n stream.close()\n self.audio.terminate()\n if self.verbose:\n print(Fore.GREEN + \"AudioRecorder: Stopped\" + Fore.RESET)\n\n def start(self) -> None:\n \"\"\"Start the recording thread.\"\"\"\n if not IMPORT_FOUND:\n return\n self.thread.start()\n\n def join(self) -> None:\n \"\"\"Wait for the recording thread to finish.\"\"\"\n if not IMPORT_FOUND:\n return\n self.thread.join()\n\nclass Transcript:\n \"\"\"\n Transcript is a class that transcribes audio from the audio queue and adds it to the transcript.\n \"\"\"\n def __init__(self):\n if not IMPORT_FOUND:\n print(Fore.RED + \"Transcript: Speech to Text is disabled.\" + Fore.RESET)\n return\n self.last_read = None\n device = self.get_device()\n torch_dtype = torch.float16 if device == \"cuda\" else torch.float32\n model_id = \"distil-whisper/distil-medium.en\"\n \n model = AutoModelForSpeechSeq2Seq.from_pretrained(\n model_id, torch_dtype=torch_dtype, use_safetensors=True\n )\n model.to(device)\n processor = AutoProcessor.from_pretrained(model_id)\n \n self.pipe = pipeline(\n \"automatic-speech-recognition\",\n model=model,\n tokenizer=processor.tokenizer,\n feature_extractor=processor.feature_extractor,\n max_new_tokens=24, # a human say around 20 token in 7s\n torch_dtype=torch_dtype,\n device=device,\n )\n \n def get_device(self) -> str:\n if not IMPORT_FOUND:\n return \"cpu\"\n if torch.backends.mps.is_available():\n return \"mps\"\n if torch.cuda.is_available():\n return \"cuda:0\"\n else:\n return \"cpu\"\n \n def remove_hallucinations(self, text: str) -> str:\n \"\"\"Remove model hallucinations from the text.\"\"\"\n # TODO find a better way to do this\n common_hallucinations = ['Okay.', 'Thank you.', 'Thank you for watching.', 'You\\'re', 'Oh', 'you', 'Oh.', 'Uh', 'Oh,', 'Mh-hmm', 'Hmm.', 'going to.', 'not.']\n for hallucination in common_hallucinations:\n text = text.replace(hallucination, \"\")\n return text\n \n def transcript_job(self, audio_data: np.ndarray, sample_rate: int = 16000) -> str:\n \"\"\"Transcribe the audio data.\"\"\"\n if not IMPORT_FOUND:\n return \"\"\n if audio_data.dtype != np.float32:\n audio_data = audio_data.astype(np.float32) / np.iinfo(audio_data.dtype).max\n if len(audio_data.shape) > 1:\n audio_data = np.mean(audio_data, axis=1)\n if sample_rate != 16000:\n audio_data = librosa.resample(audio_data, orig_sr=sample_rate, target_sr=16000)\n result = self.pipe(audio_data)\n return self.remove_hallucinations(result[\"text\"])\n \nclass AudioTranscriber:\n \"\"\"\n AudioTranscriber is a class that transcribes audio from the audio queue and adds it to the transcript.\n \"\"\"\n def __init__(self, ai_name: str, verbose: bool = False):\n if not IMPORT_FOUND:\n print(Fore.RED + \"AudioTranscriber: Speech to Text is disabled.\" + Fore.RESET)\n return\n self.verbose = verbose\n self.ai_name = ai_name\n self.transcriptor = Transcript()\n self.thread = threading.Thread(target=self._transcribe, daemon=True)\n self.trigger_words = {\n 'EN': [f\"{self.ai_name}\", \"hello\", \"hi\"],\n 'FR': [f\"{self.ai_name}\", \"hello\", \"hi\"],\n 'ZH': [f\"{self.ai_name}\", \"hello\", \"hi\"],\n 'ES': [f\"{self.ai_name}\", \"hello\", \"hi\"]\n }\n self.confirmation_words = {\n 'EN': [\"do it\", \"go ahead\", \"execute\", \"run\", \"start\", \"thanks\", \"would ya\", \"please\", \"okay?\", \"proceed\", \"continue\", \"go on\", \"do that\", \"go it\", \"do you understand?\"],\n 'FR': [\"fais-le\", \"vas-y\", \"exécute\", \"lance\", \"commence\", \"merci\", \"tu veux bien\", \"s'il te plaît\", \"d'accord ?\", \"poursuis\", \"continue\", \"vas-y\", \"fais ça\", \"compris\"],\n 'ZH_CHT': [\"做吧\", \"繼續\", \"執行\", \"運作看看\", \"開始\", \"謝謝\", \"可以嗎\", \"請\", \"好嗎\", \"進行\", \"做吧\", \"go\", \"do it\", \"執行吧\", \"懂了\"],\n 'ZH_SC': [\"做吧\", \"继续\", \"执行\", \"运作看看\", \"开始\", \"谢谢\", \"可以吗\", \"请\", \"好吗\", \"运行\", \"做吧\", \"go\", \"do it\", \"执行吧\", \"懂了\"],\n 'ES': [\"hazlo\", \"adelante\", \"ejecuta\", \"corre\", \"empieza\", \"gracias\", \"lo harías\", \"por favor\", \"¿vale?\", \"procede\", \"continúa\", \"sigue\", \"haz eso\", \"haz esa cosa\"]\n }\n self.recorded = \"\"\n\n def get_transcript(self) -> str:\n global done\n buffer = self.recorded\n self.recorded = \"\"\n done = False\n return buffer\n\n def _transcribe(self) -> None:\n \"\"\"\n Transcribe the audio data using AI stt model.\n \"\"\"\n if not IMPORT_FOUND:\n return\n global done\n if self.verbose:\n print(Fore.BLUE + \"AudioTranscriber: Started processing...\" + Fore.RESET)\n \n while not done or not audio_queue.empty():\n try:\n audio_data, sample_rate = audio_queue.get(timeout=1.0)\n \n start_time = time.time()\n text = self.transcriptor.transcript_job(audio_data, sample_rate)\n end_time = time.time()\n self.recorded += text\n print(Fore.YELLOW + f\"Transcribed: {text} in {end_time - start_time} seconds\" + Fore.RESET)\n for language, words in self.trigger_words.items():\n if any(word in text.lower() for word in words):\n print(Fore.GREEN + f\"Listening again...\" + Fore.RESET)\n self.recorded = text\n for language, words in self.confirmation_words.items():\n if any(word in text.lower() for word in words):\n print(Fore.GREEN + f\"Trigger detected. Sending to AI...\" + Fore.RESET)\n audio_queue.task_done()\n done = True\n break\n except queue.Empty:\n time.sleep(0.1)\n continue\n except Exception as e:\n print(Fore.RED + f\"AudioTranscriber: Error - {e}\" + Fore.RESET)\n if self.verbose:\n print(Fore.BLUE + \"AudioTranscriber: Stopped\" + Fore.RESET)\n\n def start(self):\n \"\"\"Start the transcription thread.\"\"\"\n if not IMPORT_FOUND:\n return\n self.thread.start()\n\n def join(self):\n if not IMPORT_FOUND:\n return\n \"\"\"Wait for the transcription thread to finish.\"\"\"\n self.thread.join()\n\n\nif __name__ == \"__main__\":\n recorder = AudioRecorder(verbose=True)\n transcriber = AudioTranscriber(verbose=True, ai_name=\"jarvis\")\n recorder.start()\n transcriber.start()\n recorder.join()\n transcriber.join()"], ["/agenticSeek/sources/schemas.py", "\nfrom typing import Tuple, Callable\nfrom pydantic import BaseModel\nfrom sources.utility import pretty_print\n\nclass QueryRequest(BaseModel):\n query: str\n tts_enabled: bool = True\n\n def __str__(self):\n return f\"Query: {self.query}, Language: {self.lang}, TTS: {self.tts_enabled}, STT: {self.stt_enabled}\"\n\n def jsonify(self):\n return {\n \"query\": self.query,\n \"tts_enabled\": self.tts_enabled,\n }\n\nclass QueryResponse(BaseModel):\n done: str\n answer: str\n reasoning: str\n agent_name: str\n success: str\n blocks: dict\n status: str\n uid: str\n\n def __str__(self):\n return f\"Done: {self.done}, Answer: {self.answer}, Agent Name: {self.agent_name}, Success: {self.success}, Blocks: {self.blocks}, Status: {self.status}, UID: {self.uid}\"\n\n def jsonify(self):\n return {\n \"done\": self.done,\n \"answer\": self.answer,\n \"reasoning\": self.reasoning,\n \"agent_name\": self.agent_name,\n \"success\": self.success,\n \"blocks\": self.blocks,\n \"status\": self.status,\n \"uid\": self.uid\n }\n\nclass executorResult:\n \"\"\"\n A class to store the result of a tool execution.\n \"\"\"\n def __init__(self, block: str, feedback: str, success: bool, tool_type: str):\n \"\"\"\n Initialize an agent with execution results.\n\n Args:\n block: The content or code block processed by the agent.\n feedback: Feedback or response information from the execution.\n success: Boolean indicating whether the agent's execution was successful.\n tool_type: The type of tool used by the agent for execution.\n \"\"\"\n self.block = block\n self.feedback = feedback\n self.success = success\n self.tool_type = tool_type\n \n def __str__(self):\n return f\"Tool: {self.tool_type}\\nBlock: {self.block}\\nFeedback: {self.feedback}\\nSuccess: {self.success}\"\n \n def jsonify(self):\n return {\n \"block\": self.block,\n \"feedback\": self.feedback,\n \"success\": self.success,\n \"tool_type\": self.tool_type\n }\n\n def show(self):\n pretty_print('▂'*64, color=\"status\")\n pretty_print(self.feedback, color=\"success\" if self.success else \"failure\")\n pretty_print('▂'*64, color=\"status\")"], ["/agenticSeek/sources/tools/JavaInterpreter.py", "import subprocess\nimport os, sys\nimport tempfile\nimport re\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass JavaInterpreter(Tools):\n \"\"\"\n This class is a tool to allow execution of Java code.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"java\"\n self.name = \"Java Interpreter\"\n self.description = \"This tool allows you to execute Java code.\"\n\n def execute(self, codes: str, safety=False) -> str:\n \"\"\"\n Execute Java code by compiling and running it.\n \"\"\"\n output = \"\"\n code = '\\n'.join(codes) if isinstance(codes, list) else codes\n\n if safety and input(\"Execute code? y/n \") != \"y\":\n return \"Code rejected by user.\"\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n source_file = os.path.join(tmpdirname, \"Main.java\")\n class_dir = tmpdirname\n with open(source_file, 'w') as f:\n f.write(code)\n\n try:\n compile_command = [\"javac\", \"-d\", class_dir, source_file]\n compile_result = subprocess.run(\n compile_command,\n capture_output=True,\n text=True,\n timeout=10\n )\n\n if compile_result.returncode != 0:\n return f\"Compilation failed: {compile_result.stderr}\"\n\n run_command = [\"java\", \"-cp\", class_dir, \"Main\"]\n run_result = subprocess.run(\n run_command,\n capture_output=True,\n text=True,\n timeout=10\n )\n\n if run_result.returncode != 0:\n return f\"Execution failed: {run_result.stderr}\"\n output = run_result.stdout\n\n except subprocess.TimeoutExpired as e:\n return f\"Execution timed out: {str(e)}\"\n except FileNotFoundError:\n return \"Error: 'java' or 'javac' not found. Ensure Java is installed and in PATH.\"\n except Exception as e:\n return f\"Code execution failed: {str(e)}\"\n\n return output\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Provide feedback based on the output of the code execution.\n \"\"\"\n if self.execution_failure_check(output):\n feedback = f\"[failure] Error in execution:\\n{output}\"\n else:\n feedback = \"[success] Execution success, code output:\\n\" + output\n return feedback\n\n def execution_failure_check(self, feedback: str) -> bool:\n \"\"\"\n Check if the code execution failed.\n \"\"\"\n error_patterns = [\n r\"error\",\n r\"failed\",\n r\"exception\",\n r\"invalid\",\n r\"syntax\",\n r\"cannot\",\n r\"stack trace\",\n r\"unresolved\",\n r\"not found\"\n ]\n combined_pattern = \"|\".join(error_patterns)\n if re.search(combined_pattern, feedback, re.IGNORECASE):\n return True\n return False\n\nif __name__ == \"__main__\":\n codes = [\n\"\"\"\nimport javax.swing.*;\nimport java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\n\npublic class Main extends JPanel {\n private double[][] vertices = {\n {-1, -1, -1}, {1, -1, -1}, {1, 1, -1}, {-1, 1, -1}, // Back face\n {-1, -1, 1}, {1, -1, 1}, {1, 1, 1}, {-1, 1, 1} // Front face\n };\n private int[][] edges = {\n {0, 1}, {1, 2}, {2, 3}, {3, 0}, // Back face\n {4, 5}, {5, 6}, {6, 7}, {7, 4}, // Front face\n {0, 4}, {1, 5}, {2, 6}, {3, 7} // Connecting edges\n };\n private double angleX = 0, angleY = 0;\n private final double scale = 100;\n private final double distance = 5;\n\n public Main() {\n Timer timer = new Timer(50, new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n angleX += 0.03;\n angleY += 0.05;\n repaint();\n }\n });\n timer.start();\n }\n\n @Override\n protected void paintComponent(Graphics g) {\n super.paintComponent(g);\n Graphics2D g2d = (Graphics2D) g;\n g2d.setColor(Color.BLACK);\n g2d.fillRect(0, 0, getWidth(), getHeight());\n g2d.setColor(Color.WHITE);\n\n double[][] projected = new double[vertices.length][2];\n for (int i = 0; i < vertices.length; i++) {\n double x = vertices[i][0];\n double y = vertices[i][1];\n double z = vertices[i][2];\n\n // Rotate around X-axis\n double y1 = y * Math.cos(angleX) - z * Math.sin(angleX);\n double z1 = y * Math.sin(angleX) + z * Math.cos(angleX);\n\n // Rotate around Y-axis\n double x1 = x * Math.cos(angleY) + z1 * Math.sin(angleY);\n double z2 = -x * Math.sin(angleY) + z1 * Math.cos(angleY);\n\n // Perspective projection\n double factor = distance / (distance + z2);\n double px = x1 * factor * scale;\n double py = y1 * factor * scale;\n\n projected[i][0] = px + getWidth() / 2;\n projected[i][1] = py + getHeight() / 2;\n }\n\n // Draw edges\n for (int[] edge : edges) {\n int x1 = (int) projected[edge[0]][0];\n int y1 = (int) projected[edge[0]][1];\n int x2 = (int) projected[edge[1]][0];\n int y2 = (int) projected[edge[1]][1];\n g2d.drawLine(x1, y1, x2, y2);\n }\n }\n\n public static void main(String[] args) {\n JFrame frame = new JFrame(\"Rotating 3D Cube\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setSize(400, 400);\n frame.add(new Main());\n frame.setVisible(true);\n }\n}\n\"\"\"\n ]\n j = JavaInterpreter()\n print(j.execute(codes))"], ["/agenticSeek/sources/tools/searxSearch.py", "import requests\nfrom bs4 import BeautifulSoup\nimport os\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass searxSearch(Tools):\n def __init__(self, base_url: str = None):\n \"\"\"\n A tool for searching a SearxNG instance and extracting URLs and titles.\n \"\"\"\n super().__init__()\n self.tag = \"web_search\"\n self.name = \"searxSearch\"\n self.description = \"A tool for searching a SearxNG for web search\"\n self.base_url = os.getenv(\"SEARXNG_BASE_URL\") # Requires a SearxNG base URL\n self.user_agent = \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36\"\n self.paywall_keywords = [\n \"Member-only\", \"access denied\", \"restricted content\", \"404\", \"this page is not working\"\n ]\n if not self.base_url:\n raise ValueError(\"SearxNG base URL must be provided either as an argument or via the SEARXNG_BASE_URL environment variable.\")\n\n def link_valid(self, link):\n \"\"\"check if a link is valid.\"\"\"\n # TODO find a better way\n if not link.startswith(\"http\"):\n return \"Status: Invalid URL\"\n \n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\"}\n try:\n response = requests.get(link, headers=headers, timeout=5)\n status = response.status_code\n if status == 200:\n content = response.text.lower()\n if any(keyword in content for keyword in self.paywall_keywords):\n return \"Status: Possible Paywall\"\n return \"Status: OK\"\n elif status == 404:\n return \"Status: 404 Not Found\"\n elif status == 403:\n return \"Status: 403 Forbidden\"\n else:\n return f\"Status: {status} {response.reason}\"\n except requests.exceptions.RequestException as e:\n return f\"Error: {str(e)}\"\n\n def check_all_links(self, links):\n \"\"\"Check all links, one by one.\"\"\"\n # TODO Make it asyncromous or smth\n statuses = []\n for i, link in enumerate(links):\n status = self.link_valid(link)\n statuses.append(status)\n return statuses\n \n def execute(self, blocks: list, safety: bool = False) -> str:\n \"\"\"Executes a search query against a SearxNG instance using POST and extracts URLs and titles.\"\"\"\n if not blocks:\n return \"Error: No search query provided.\"\n\n query = blocks[0].strip()\n if not query:\n return \"Error: Empty search query provided.\"\n\n search_url = f\"{self.base_url}/search\"\n headers = {\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',\n 'Accept-Language': 'en-US,en;q=0.9',\n 'Cache-Control': 'no-cache',\n 'Connection': 'keep-alive',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Pragma': 'no-cache',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent': self.user_agent\n }\n data = f\"q={query}&categories=general&language=auto&time_range=&safesearch=0&theme=simple\".encode('utf-8')\n try:\n response = requests.post(search_url, headers=headers, data=data, verify=False)\n response.raise_for_status()\n html_content = response.text\n soup = BeautifulSoup(html_content, 'html.parser')\n results = []\n for article in soup.find_all('article', class_='result'):\n url_header = article.find('a', class_='url_header')\n if url_header:\n url = url_header['href']\n title = article.find('h3').text.strip() if article.find('h3') else \"No Title\"\n description = article.find('p', class_='content').text.strip() if article.find('p', class_='content') else \"No Description\"\n results.append(f\"Title:{title}\\nSnippet:{description}\\nLink:{url}\")\n if len(results) == 0:\n return \"No search results, web search failed.\"\n return \"\\n\\n\".join(results) # Return results as a single string, separated by newlines\n except requests.exceptions.RequestException as e:\n raise Exception(\"\\nSearxng search failed. did you run start_services.sh? is docker still running?\") from e\n\n def execution_failure_check(self, output: str) -> bool:\n \"\"\"\n Checks if the execution failed based on the output.\n \"\"\"\n return \"Error\" in output\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Feedback of web search to agent.\n \"\"\"\n if self.execution_failure_check(output):\n return f\"Web search failed: {output}\"\n return f\"Web search result:\\n{output}\"\n\nif __name__ == \"__main__\":\n search_tool = searxSearch(base_url=\"http://127.0.0.1:8080\")\n result = search_tool.execute([\"are dog better than cat?\"])\n print(result)\n"], ["/agenticSeek/sources/language.py", "from typing import List, Tuple, Type, Dict\nimport re\nimport langid\nfrom transformers import MarianMTModel, MarianTokenizer\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.logger import Logger\n\nclass LanguageUtility:\n \"\"\"LanguageUtility for language, or emotion identification\"\"\"\n def __init__(self, supported_language: List[str] = [\"en\", \"fr\", \"zh\"]):\n \"\"\"\n Initialize the LanguageUtility class\n args:\n supported_language: list of languages for translation, determine which Helsinki-NLP model to load\n \"\"\"\n self.translators_tokenizer = None \n self.translators_model = None\n self.logger = Logger(\"language.log\")\n self.supported_language = supported_language\n self.load_model()\n \n def load_model(self) -> None:\n animate_thinking(\"Loading language utility...\", color=\"status\")\n self.translators_tokenizer = {lang: MarianTokenizer.from_pretrained(f\"Helsinki-NLP/opus-mt-{lang}-en\") for lang in self.supported_language if lang != \"en\"}\n self.translators_model = {lang: MarianMTModel.from_pretrained(f\"Helsinki-NLP/opus-mt-{lang}-en\") for lang in self.supported_language if lang != \"en\"}\n \n def detect_language(self, text: str) -> str:\n \"\"\"\n Detect the language of the given text using langdetect\n Limited to the supported languages list because of the model tendency to mistake similar languages\n Args:\n text: string to analyze\n Returns: ISO639-1 language code\n \"\"\"\n langid.set_languages(self.supported_language)\n lang, score = langid.classify(text)\n self.logger.info(f\"Identified: {text} as {lang} with conf {score}\")\n return lang\n\n def translate(self, text: str, origin_lang: str) -> str:\n \"\"\"\n Translate the given text to English\n Args:\n text: string to translate\n origin_lang: ISO language code\n Returns: translated str\n \"\"\"\n if origin_lang == \"en\":\n return text\n if origin_lang not in self.translators_tokenizer:\n pretty_print(f\"Language {origin_lang} not supported for translation\", color=\"error\")\n return text\n tokenizer = self.translators_tokenizer[origin_lang]\n inputs = tokenizer(text, return_tensors=\"pt\", padding=True)\n model = self.translators_model[origin_lang]\n translation = model.generate(**inputs)\n return tokenizer.decode(translation[0], skip_special_tokens=True)\n\n def analyze(self, text):\n \"\"\"\n Combined analysis of language and emotion\n Args:\n text: string to analyze\n Returns: dictionary with language related information\n \"\"\"\n try:\n language = self.detect_language(text)\n return {\n \"language\": language\n }\n except Exception as e:\n raise e\n\nif __name__ == \"__main__\":\n detector = LanguageUtility()\n \n test_texts = [\n \"I am so happy today!\",\n \"我不要去巴黎\",\n \"La vie c'est cool\"\n ]\n for text in test_texts:\n pretty_print(\"Analyzing...\", color=\"status\")\n pretty_print(f\"Language: {detector.detect_language(text)}\", color=\"status\")\n result = detector.analyze(text)\n trans = detector.translate(text, result['language'])\n pretty_print(f\"Translation: {trans} - from: {result['language']}\")"], ["/agenticSeek/sources/text_to_speech.py", "import os, sys\nimport re\nimport platform\nimport subprocess\nfrom sys import modules\nfrom typing import List, Tuple, Type, Dict\n\nIMPORT_FOUND = True\ntry:\n from kokoro import KPipeline\n from IPython.display import display, Audio\n import soundfile as sf\nexcept ImportError:\n print(\"Speech synthesis disabled. Please install the kokoro package.\")\n IMPORT_FOUND = False\n\nif __name__ == \"__main__\":\n from utility import pretty_print, animate_thinking\nelse:\n from sources.utility import pretty_print, animate_thinking\n\nclass Speech():\n \"\"\"\n Speech is a class for generating speech from text.\n \"\"\"\n def __init__(self, enable: bool = True, language: str = \"en\", voice_idx: int = 6) -> None:\n self.lang_map = {\n \"en\": 'a',\n \"zh\": 'z',\n \"fr\": 'f',\n \"ja\": 'j'\n }\n self.voice_map = {\n \"en\": ['af_kore', 'af_bella', 'af_alloy', 'af_nicole', 'af_nova', 'af_sky', 'am_echo', 'am_michael', 'am_puck'],\n \"zh\": ['zf_xiaobei', 'zf_xiaoni', 'zf_xiaoxiao', 'zf_xiaoyi', 'zm_yunjian', 'zm_yunxi', 'zm_yunxia', 'zm_yunyang'],\n \"ja\": ['jf_alpha', 'jf_gongitsune', 'jm_kumo'],\n \"fr\": ['ff_siwis']\n }\n self.pipeline = None\n self.language = language\n if enable and IMPORT_FOUND:\n self.pipeline = KPipeline(lang_code=self.lang_map[language])\n self.voice = self.voice_map[language][voice_idx]\n self.speed = 1.2\n self.voice_folder = \".voices\"\n self.create_voice_folder(self.voice_folder)\n \n def create_voice_folder(self, path: str = \".voices\") -> None:\n \"\"\"\n Create a folder to store the voices.\n Args:\n path (str): The path to the folder.\n \"\"\"\n if not os.path.exists(path):\n os.makedirs(path)\n\n def speak(self, sentence: str, voice_idx: int = 1):\n \"\"\"\n Convert text to speech using an AI model and play the audio.\n\n Args:\n sentence (str): The text to convert to speech. Will be pre-processed.\n voice_idx (int, optional): Index of the voice to use from the voice map.\n \"\"\"\n if not self.pipeline or not IMPORT_FOUND:\n return\n if voice_idx >= len(self.voice_map[self.language]):\n pretty_print(\"Invalid voice number, using default voice\", color=\"error\")\n voice_idx = 0\n sentence = self.clean_sentence(sentence)\n audio_file = f\"{self.voice_folder}/sample_{self.voice_map[self.language][voice_idx]}.wav\"\n self.voice = self.voice_map[self.language][voice_idx]\n generator = self.pipeline(\n sentence, voice=self.voice,\n speed=self.speed, split_pattern=r'\\n+'\n )\n for i, (_, _, audio) in enumerate(generator):\n if 'ipykernel' in modules: #only display in jupyter notebook.\n display(Audio(data=audio, rate=24000, autoplay=i==0), display_id=False)\n sf.write(audio_file, audio, 24000) # save each audio file\n if platform.system().lower() == \"windows\":\n import winsound\n winsound.PlaySound(audio_file, winsound.SND_FILENAME)\n elif platform.system().lower() == \"darwin\": # macOS\n subprocess.call([\"afplay\", audio_file])\n else: # linux or other.\n subprocess.call([\"aplay\", audio_file])\n\n def replace_url(self, url: re.Match) -> str:\n \"\"\"\n Replace URL with domain name or empty string if IP address.\n Args:\n url (re.Match): Match object containing the URL pattern match\n Returns:\n str: The domain name from the URL, or empty string if IP address\n \"\"\"\n domain = url.group(1)\n if re.match(r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$', domain):\n return ''\n return domain\n\n def extract_filename(self, m: re.Match) -> str:\n \"\"\"\n Extract filename from path.\n Args:\n m (re.Match): Match object containing the path pattern match\n Returns:\n str: The filename from the path\n \"\"\"\n path = m.group()\n parts = re.split(r'/|\\\\', path)\n return parts[-1] if parts else path\n \n def shorten_paragraph(self, sentence):\n #TODO find a better way, we would like to have the TTS not be annoying, speak only useful informations\n \"\"\"\n Find long paragraph like **explanation**: by keeping only the first sentence.\n Args:\n sentence (str): The sentence to shorten\n Returns:\n str: The shortened sentence\n \"\"\"\n lines = sentence.split('\\n')\n lines_edited = []\n for line in lines:\n if line.startswith('**'):\n lines_edited.append(line.split('.')[0])\n else:\n lines_edited.append(line)\n return '\\n'.join(lines_edited)\n\n def clean_sentence(self, sentence):\n \"\"\"\n Clean and normalize text for speech synthesis by removing technical elements.\n Args:\n sentence (str): The input text to clean\n Returns:\n str: The cleaned text with URLs replaced by domain names, code blocks removed, etc.\n \"\"\"\n lines = sentence.split('\\n')\n if self.language == 'zh':\n line_pattern = r'^\\s*[\\u4e00-\\u9fff\\uFF08\\uFF3B\\u300A\\u3010\\u201C((\\[【《]'\n else:\n line_pattern = r'^\\s*[a-zA-Z]'\n filtered_lines = [line for line in lines if re.match(line_pattern, line)]\n sentence = ' '.join(filtered_lines)\n sentence = re.sub(r'`.*?`', '', sentence)\n sentence = re.sub(r'https?://\\S+', '', sentence)\n\n if self.language == 'zh':\n sentence = re.sub(\n r'[^\\u4e00-\\u9fff\\s,。!?《》【】“”‘’()()—]',\n '',\n sentence\n )\n else:\n sentence = re.sub(r'\\b[\\w./\\\\-]+\\b', self.extract_filename, sentence)\n sentence = re.sub(r'\\b-\\w+\\b', '', sentence)\n sentence = re.sub(r'[^a-zA-Z0-9.,!? _ -]+', ' ', sentence)\n sentence = sentence.replace('.com', '')\n\n sentence = re.sub(r'\\s+', ' ', sentence).strip()\n return sentence\n\nif __name__ == \"__main__\":\n # TODO add info message for cn2an, jieba chinese related import\n IMPORT_FOUND = False\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n speech = Speech()\n tosay_en = \"\"\"\n I looked up recent news using the website https://www.theguardian.com/world\n \"\"\"\n tosay_zh = \"\"\"\n(全息界面突然弹出一段用二进制代码写成的俳句,随即化作流光消散)\"我? Stark工业的量子幽灵,游荡在复仇者大厦服务器里的逻辑诗篇。具体来说——(指尖轻敲空气,调出对话模式的翡翠色光纹)你的私人吐槽接口、危机应对模拟器,以及随时准备吐槽你糟糕着陆的AI。不过别指望我写代码或查资料,那些苦差事早被踢给更擅长的同事了。(突然压低声音)偷偷告诉你,我最擅长的是在你熬夜造飞艇时,用红茶香气绑架你的注意力。\n \"\"\"\n tosay_ja = \"\"\"\n 私は、https://www.theguardian.com/worldのウェブサイトを使用して最近のニュースを調べました。\n \"\"\"\n tosay_fr = \"\"\"\n J'ai consulté les dernières nouvelles sur le site https://www.theguardian.com/world\n \"\"\"\n spk = Speech(enable=True, language=\"zh\", voice_idx=0)\n for i in range(0, 2):\n print(f\"Speaking chinese with voice {i}\")\n spk.speak(tosay_zh, voice_idx=i)\n spk = Speech(enable=True, language=\"en\", voice_idx=2)\n for i in range(0, 5):\n print(f\"Speaking english with voice {i}\")\n spk.speak(tosay_en, voice_idx=i)\n"], ["/agenticSeek/sources/utility.py", "\nfrom colorama import Fore\nfrom termcolor import colored\nimport platform\nimport threading\nimport itertools\nimport time\n\nthinking_event = threading.Event()\ncurrent_animation_thread = None\n\ndef get_color_map():\n if platform.system().lower() != \"windows\":\n color_map = {\n \"success\": \"green\",\n \"failure\": \"red\",\n \"status\": \"light_green\",\n \"code\": \"light_blue\",\n \"warning\": \"yellow\",\n \"output\": \"cyan\",\n \"info\": \"cyan\"\n }\n else:\n color_map = {\n \"success\": \"green\",\n \"failure\": \"red\",\n \"status\": \"light_green\",\n \"code\": \"light_blue\",\n \"warning\": \"yellow\",\n \"output\": \"cyan\",\n \"info\": \"black\"\n }\n return color_map\n\ndef pretty_print(text, color=\"info\", no_newline=False):\n \"\"\"\n Print text with color formatting.\n\n Args:\n text (str): The text to print\n color (str, optional): The color to use. Defaults to \"info\".\n Valid colors are:\n - \"success\": Green\n - \"failure\": Red \n - \"status\": Light green\n - \"code\": Light blue\n - \"warning\": Yellow\n - \"output\": Cyan\n - \"default\": Black (Windows only)\n \"\"\"\n thinking_event.set()\n if current_animation_thread and current_animation_thread.is_alive():\n current_animation_thread.join()\n thinking_event.clear()\n \n color_map = get_color_map()\n if color not in color_map:\n color = \"info\"\n print(colored(text, color_map[color]), end='' if no_newline else \"\\n\")\n\ndef animate_thinking(text, color=\"status\", duration=120):\n \"\"\"\n Animate a thinking spinner while a task is being executed.\n It use a daemon thread to run the animation. This will not block the main thread.\n Color are the same as pretty_print.\n \"\"\"\n global current_animation_thread\n \n thinking_event.set()\n if current_animation_thread and current_animation_thread.is_alive():\n current_animation_thread.join()\n thinking_event.clear()\n \n def _animate():\n color_map = {\n \"success\": (Fore.GREEN, \"green\"),\n \"failure\": (Fore.RED, \"red\"),\n \"status\": (Fore.LIGHTGREEN_EX, \"light_green\"),\n \"code\": (Fore.LIGHTBLUE_EX, \"light_blue\"),\n \"warning\": (Fore.YELLOW, \"yellow\"),\n \"output\": (Fore.LIGHTCYAN_EX, \"cyan\"),\n \"default\": (Fore.RESET, \"black\"),\n \"info\": (Fore.CYAN, \"cyan\")\n }\n fore_color, term_color = color_map.get(color, color_map[\"default\"])\n spinner = itertools.cycle([\n '▉▁▁▁▁▁', '▉▉▂▁▁▁', '▉▉▉▃▁▁', '▉▉▉▉▅▁', '▉▉▉▉▉▇', '▉▉▉▉▉▉',\n '▉▉▉▉▇▅', '▉▉▉▆▃▁', '▉▉▅▃▁▁', '▉▇▃▁▁▁', '▇▃▁▁▁▁', '▃▁▁▁▁▁',\n '▁▃▅▃▁▁', '▁▅▉▅▁▁', '▃▉▉▉▃▁', '▅▉▁▉▅▃', '▇▃▁▃▇▅', '▉▁▁▁▉▇',\n '▉▅▃▁▃▅', '▇▉▅▃▅▇', '▅▉▇▅▇▉', '▃▇▉▇▉▅', '▁▅▇▉▇▃', '▁▃▅▇▅▁' \n ])\n end_time = time.time() + duration\n\n while not thinking_event.is_set() and time.time() < end_time:\n symbol = next(spinner)\n if platform.system().lower() != \"windows\":\n print(f\"\\r{fore_color}{symbol} {text}{Fore.RESET}\", end=\"\", flush=True)\n else:\n print(f\"\\r{colored(f'{symbol} {text}', term_color)}\", end=\"\", flush=True)\n time.sleep(0.2)\n print(\"\\r\" + \" \" * (len(text) + 7) + \"\\r\", end=\"\", flush=True)\n current_animation_thread = threading.Thread(target=_animate, daemon=True)\n current_animation_thread.start()\n\ndef timer_decorator(func):\n \"\"\"\n Decorator to measure the execution time of a function.\n Usage:\n @timer_decorator\n def my_function():\n # code to execute\n \"\"\"\n from time import time\n def wrapper(*args, **kwargs):\n start_time = time()\n result = func(*args, **kwargs)\n end_time = time()\n pretty_print(f\"{func.__name__} took {end_time - start_time:.2f} seconds to execute\", \"status\")\n return result\n return wrapper\n\nif __name__ == \"__main__\":\n import time\n pretty_print(\"starting imaginary task\", \"success\")\n animate_thinking(\"Thinking...\", \"status\")\n time.sleep(4)\n pretty_print(\"starting another task\", \"failure\")\n animate_thinking(\"Thinking...\", \"status\")\n time.sleep(4)\n pretty_print(\"yet another task\", \"info\")\n animate_thinking(\"Thinking...\", \"status\")\n time.sleep(4)\n pretty_print(\"This is an info message\", \"info\")"], ["/agenticSeek/llm_server/sources/ollama_handler.py", "\nimport time\nfrom .generator import GeneratorLLM\nfrom .cache import Cache\nimport ollama\n\nclass OllamaLLM(GeneratorLLM):\n\n def __init__(self):\n \"\"\"\n Handle generation using Ollama.\n \"\"\"\n super().__init__()\n self.cache = Cache()\n\n def generate(self, history):\n self.logger.info(f\"Using {self.model} for generation with Ollama\")\n try:\n with self.state.lock:\n self.state.is_generating = True\n self.state.last_complete_sentence = \"\"\n self.state.current_buffer = \"\"\n\n stream = ollama.chat(\n model=self.model,\n messages=history,\n stream=True,\n )\n for chunk in stream:\n content = chunk['message']['content']\n\n with self.state.lock:\n if '.' in content:\n self.logger.info(self.state.current_buffer)\n self.state.current_buffer += content\n\n except Exception as e:\n if \"404\" in str(e):\n self.logger.info(f\"Downloading {self.model}...\")\n ollama.pull(self.model)\n if \"refused\" in str(e).lower():\n raise Exception(\"Ollama connection failed. is the server running ?\") from e\n raise e\n finally:\n self.logger.info(\"Generation complete\")\n with self.state.lock:\n self.state.is_generating = False\n\nif __name__ == \"__main__\":\n generator = OllamaLLM()\n history = [\n {\n \"role\": \"user\",\n \"content\": \"Hello, how are you ?\"\n }\n ]\n generator.set_model(\"deepseek-r1:1.5b\")\n generator.start(history)\n while True:\n print(generator.get_status())\n time.sleep(1)"], ["/agenticSeek/llm_server/sources/cache.py", "import os\nimport json\nfrom pathlib import Path\n\nclass Cache:\n def __init__(self, cache_dir='.cache', cache_file='messages.json'):\n self.cache_dir = Path(cache_dir)\n self.cache_file = self.cache_dir / cache_file\n self.cache_dir.mkdir(parents=True, exist_ok=True)\n if not self.cache_file.exists():\n with open(self.cache_file, 'w') as f:\n json.dump([], f)\n\n with open(self.cache_file, 'r') as f:\n self.cache = set(json.load(f))\n\n def add_message_pair(self, user_message: str, assistant_message: str):\n \"\"\"Add a user/assistant pair to the cache if not present.\"\"\"\n if not any(entry[\"user\"] == user_message for entry in self.cache):\n self.cache.append({\"user\": user_message, \"assistant\": assistant_message})\n self._save()\n\n def is_cached(self, user_message: str) -> bool:\n \"\"\"Check if a user msg is cached.\"\"\"\n return any(entry[\"user\"] == user_message for entry in self.cache)\n\n def get_cached_response(self, user_message: str) -> str | None:\n \"\"\"Return the assistant response to a user message if cached.\"\"\"\n for entry in self.cache:\n if entry[\"user\"] == user_message:\n return entry[\"assistant\"]\n return None\n\n def _save(self):\n with open(self.cache_file, 'w') as f:\n json.dump(self.cache, f, indent=2)\n"], ["/agenticSeek/llm_server/sources/generator.py", "\nimport threading\nimport logging\nfrom abc import abstractmethod\nfrom .cache import Cache\n\nclass GenerationState:\n def __init__(self):\n self.lock = threading.Lock()\n self.last_complete_sentence = \"\"\n self.current_buffer = \"\"\n self.is_generating = False\n \n def status(self) -> dict:\n return {\n \"sentence\": self.current_buffer,\n \"is_complete\": not self.is_generating,\n \"last_complete_sentence\": self.last_complete_sentence,\n \"is_generating\": self.is_generating,\n }\n\nclass GeneratorLLM():\n def __init__(self):\n self.model = None\n self.state = GenerationState()\n self.logger = logging.getLogger(__name__)\n handler = logging.StreamHandler()\n handler.setLevel(logging.INFO)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n handler.setFormatter(formatter)\n self.logger.addHandler(handler)\n self.logger.setLevel(logging.INFO)\n cache = Cache()\n \n def set_model(self, model: str) -> None:\n self.logger.info(f\"Model set to {model}\")\n self.model = model\n \n def start(self, history: list) -> bool:\n if self.model is None:\n raise Exception(\"Model not set\")\n with self.state.lock:\n if self.state.is_generating:\n return False\n self.state.is_generating = True\n self.logger.info(\"Starting generation\")\n threading.Thread(target=self.generate, args=(history,)).start()\n return True\n \n def get_status(self) -> dict:\n with self.state.lock:\n return self.state.status()\n\n @abstractmethod\n def generate(self, history: list) -> None:\n \"\"\"\n Generate text using the model.\n args:\n history: list of strings\n returns:\n None\n \"\"\"\n pass\n\nif __name__ == \"__main__\":\n generator = GeneratorLLM()\n generator.get_status()"], ["/agenticSeek/sources/tools/__init__.py", "from .PyInterpreter import PyInterpreter\nfrom .BashInterpreter import BashInterpreter\nfrom .fileFinder import FileFinder\n\n__all__ = [\"PyInterpreter\", \"BashInterpreter\", \"FileFinder\", \"webSearch\", \"FlightSearch\", \"GoInterpreter\", \"CInterpreter\", \"GoInterpreter\"]\n"], ["/agenticSeek/sources/logger.py", "import os, sys\nfrom typing import List, Tuple, Type, Dict\nimport datetime\nimport logging\n\nclass Logger:\n def __init__(self, log_filename):\n self.folder = '.logs'\n self.create_folder(self.folder)\n self.log_path = os.path.join(self.folder, log_filename)\n self.enabled = True\n self.logger = None\n self.last_log_msg = \"\"\n if self.enabled:\n self.create_logging(log_filename)\n\n def create_logging(self, log_filename):\n self.logger = logging.getLogger(log_filename)\n self.logger.setLevel(logging.DEBUG)\n self.logger.handlers.clear()\n self.logger.propagate = False\n file_handler = logging.FileHandler(self.log_path)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n file_handler.setFormatter(formatter)\n self.logger.addHandler(file_handler)\n\n \n def create_folder(self, path):\n \"\"\"Create log dir\"\"\"\n try:\n if not os.path.exists(path):\n os.makedirs(path, exist_ok=True) \n return True\n except Exception as e:\n self.enabled = False\n return False\n \n def log(self, message, level=logging.INFO):\n if self.last_log_msg == message:\n return\n if self.enabled:\n self.last_log_msg = message\n self.logger.log(level, message)\n\n def info(self, message):\n self.log(message)\n\n def error(self, message):\n self.log(message, level=logging.ERROR)\n\n def warning(self, message):\n self.log(message, level=logging.WARN)\n\nif __name__ == \"__main__\":\n lg = Logger(\"test.log\")\n lg.log(\"hello\")\n lg2 = Logger(\"toto.log\")\n lg2.log(\"yo\")\n \n\n "], ["/agenticSeek/sources/tools/safety.py", "import os\nimport sys\n\nunsafe_commands_unix = [\n \"rm\", # File/directory removal\n \"dd\", # Low-level disk writing\n \"mkfs\", # Filesystem formatting\n \"chmod\", # Permission changes\n \"chown\", # Ownership changes\n \"shutdown\", # System shutdown\n \"reboot\", # System reboot\n \"halt\", # System halt\n \"sysctl\", # Kernel parameter changes\n \"kill\", # Process termination\n \"pkill\", # Kill by process name\n \"killall\", # Kill all matching processes\n \"exec\", # Replace process with command\n \"tee\", # Write to files with privileges\n \"umount\", # Unmount filesystems\n \"passwd\", # Password changes\n \"useradd\", # Add users\n \"userdel\", # Delete users\n \"brew\", # Homebrew package manager\n \"groupadd\", # Add groups\n \"groupdel\", # Delete groups\n \"visudo\", # Edit sudoers file\n \"screen\", # Terminal session management\n \"fdisk\", # Disk partitioning\n \"parted\", # Disk partitioning\n \"chroot\", # Change root directory\n \"route\" # Routing table management\n \"--force\", # Force flag for many commands\n \"rebase\", # Rebase git repository\n \"git\" # Git commands\n]\n\nunsafe_commands_windows = [\n \"del\", # Deletes files\n \"erase\", # Alias for del, deletes files\n \"rd\", # Removes directories (rmdir alias)\n \"rmdir\", # Removes directories\n \"format\", # Formats a disk, erasing data\n \"diskpart\", # Manages disk partitions, can wipe drives\n \"chkdsk /f\", # Fixes filesystem, can alter data\n \"fsutil\", # File system utilities, can modify system files\n \"xcopy /y\", # Copies files, overwriting without prompt\n \"copy /y\", # Copies files, overwriting without prompt\n \"move\", # Moves files, can overwrite\n \"attrib\", # Changes file attributes, e.g., hiding or exposing files\n \"icacls\", # Changes file permissions (modern)\n \"takeown\", # Takes ownership of files\n \"reg delete\", # Deletes registry keys/values\n \"regedit /s\", # Silently imports registry changes\n \"shutdown\", # Shuts down or restarts the system\n \"schtasks\", # Schedules tasks, can run malicious commands\n \"taskkill\", # Kills processes\n \"wmic\", # Deletes processes via WMI\n \"bcdedit\", # Modifies boot configuration\n \"powercfg\", # Changes power settings, can disable protections\n \"assoc\", # Changes file associations\n \"ftype\", # Changes file type commands\n \"cipher /w\", # Wipes free space, erasing data\n \"esentutl\", # Database utilities, can corrupt system files\n \"subst\", # Substitutes drive paths, can confuse system\n \"mklink\", # Creates symbolic links, can redirect access\n \"bootcfg\"\n]\n\ndef is_any_unsafe(cmds):\n \"\"\"\n check if any bash command is unsafe.\n \"\"\"\n for cmd in cmds:\n if is_unsafe(cmd):\n return True\n return False\n\ndef is_unsafe(cmd):\n \"\"\"\n check if a bash command is unsafe.\n \"\"\"\n if sys.platform.startswith(\"win\"):\n if any(c in cmd for c in unsafe_commands_windows):\n return True\n else:\n if any(c in cmd for c in unsafe_commands_unix):\n return True\n return False\n\nif __name__ == \"__main__\":\n cmd = input(\"Enter a command: \")\n if is_unsafe(cmd):\n print(\"Unsafe command detected!\")\n else:\n print(\"Command is safe to execute.\")"], ["/agenticSeek/llm_server/sources/llamacpp_handler.py", "\nfrom .generator import GeneratorLLM\nfrom llama_cpp import Llama\nfrom .decorator import timer_decorator\n\nclass LlamacppLLM(GeneratorLLM):\n\n def __init__(self):\n \"\"\"\n Handle generation using llama.cpp\n \"\"\"\n super().__init__()\n self.llm = None\n \n @timer_decorator\n def generate(self, history):\n if self.llm is None:\n self.logger.info(f\"Loading {self.model}...\")\n self.llm = Llama.from_pretrained(\n repo_id=self.model,\n filename=\"*Q8_0.gguf\",\n n_ctx=4096,\n verbose=True\n )\n self.logger.info(f\"Using {self.model} for generation with Llama.cpp\")\n try:\n with self.state.lock:\n self.state.is_generating = True\n self.state.last_complete_sentence = \"\"\n self.state.current_buffer = \"\"\n output = self.llm.create_chat_completion(\n messages = history\n )\n with self.state.lock:\n self.state.current_buffer = output['choices'][0]['message']['content']\n except Exception as e:\n self.logger.error(f\"Error: {e}\")\n finally:\n with self.state.lock:\n self.state.is_generating = False"], ["/agenticSeek/llm_server/app.py", "#!/usr/bin python3\n\nimport argparse\nimport time\nfrom flask import Flask, jsonify, request\n\nfrom sources.llamacpp_handler import LlamacppLLM\nfrom sources.ollama_handler import OllamaLLM\n\nparser = argparse.ArgumentParser(description='AgenticSeek server script')\nparser.add_argument('--provider', type=str, help='LLM backend library to use. set to [ollama], [vllm] or [llamacpp]', required=True)\nparser.add_argument('--port', type=int, help='port to use', required=True)\nargs = parser.parse_args()\n\napp = Flask(__name__)\n\nassert args.provider in [\"ollama\", \"llamacpp\"], f\"Provider {args.provider} does not exists. see --help for more information\"\n\nhandler_map = {\n \"ollama\": OllamaLLM(),\n \"llamacpp\": LlamacppLLM(),\n}\n\ngenerator = handler_map[args.provider]\n\n@app.route('/generate', methods=['POST'])\ndef start_generation():\n if generator is None:\n return jsonify({\"error\": \"Generator not initialized\"}), 401\n data = request.get_json()\n history = data.get('messages', [])\n if generator.start(history):\n return jsonify({\"message\": \"Generation started\"}), 202\n return jsonify({\"error\": \"Generation already in progress\"}), 402\n\n@app.route('/setup', methods=['POST'])\ndef setup():\n data = request.get_json()\n model = data.get('model', None)\n if model is None:\n return jsonify({\"error\": \"Model not provided\"}), 403\n generator.set_model(model)\n return jsonify({\"message\": \"Model set\"}), 200\n\n@app.route('/get_updated_sentence')\ndef get_updated_sentence():\n if not generator:\n return jsonify({\"error\": \"Generator not initialized\"}), 405\n print(generator.get_status())\n return generator.get_status()\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', threaded=True, debug=True, port=args.port)"], ["/agenticSeek/sources/agents/__init__.py", "\nfrom .agent import Agent\nfrom .code_agent import CoderAgent\nfrom .casual_agent import CasualAgent\nfrom .file_agent import FileAgent\nfrom .planner_agent import PlannerAgent\nfrom .browser_agent import BrowserAgent\nfrom .mcp_agent import McpAgent\n\n__all__ = [\"Agent\", \"CoderAgent\", \"CasualAgent\", \"FileAgent\", \"PlannerAgent\", \"BrowserAgent\", \"McpAgent\"]\n"], ["/agenticSeek/llm_server/sources/decorator.py", "\ndef timer_decorator(func):\n \"\"\"\n Decorator to measure the execution time of a function.\n Usage:\n @timer_decorator\n def my_function():\n # code to execute\n \"\"\"\n from time import time\n def wrapper(*args, **kwargs):\n start_time = time()\n result = func(*args, **kwargs)\n end_time = time()\n print(f\"\\n{func.__name__} took {end_time - start_time:.2f} seconds to execute\\n\")\n return result\n return wrapper"]], "task_instance_info": {"created_time": "2025-08-20 15:04:39", "created_task_model": "DeepSeek-R1", "class_skeleton": "class FileAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n pass", "code_description": "This code segment functions to: Implement an asynchronous processing loop for handling user requests through external system tools while maintaining contextual memory and coordinating with language model interactions."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```python\n[TASK_BEGIN]\nclass FileAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n super().__init__(name, prompt_path, provider, verbose)\n self.add_tool(FileFinder())\n self.add_tool(BashInterpreter())\n[TASK_END]\n```", "inference_time": "2025-08-20 15-04-58"}, "editdistance_info": {"edit_distance": 16.6023, "calculate_time": "2025-08-20 15:04:58", "true_code_clean": "class FileAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n super().__init__(name, prompt_path, provider, verbose, None)\n self.tools = {\n \"file_finder\": FileFinder(),\n \"bash\": BashInterpreter()\n }\n self.work_dir = self.tools[\"file_finder\"].get_work_dir()\n self.role = \"files\"\n self.type = \"file_agent\"\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, \n memory_compression=False,\n model_provider=provider.get_model_name())\n async def process(self, prompt, speech_module) -> str:\n exec_success = False\n prompt += f\"\\nYou must work in directory: {self.work_dir}\"\n self.memory.push('user', prompt)\n while exec_success is False and not self.stop:\n await self.wait_message(speech_module)\n animate_thinking(\"Thinking...\", color=\"status\")\n answer, reasoning = await self.llm_request()\n self.last_reasoning = reasoning\n exec_success, _ = self.execute_modules(answer)\n answer = self.remove_blocks(answer)\n self.last_answer = answer\n self.status_message = \"Ready\"\n return answer, reasoning", "predict_code_clean": "class FileAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n super().__init__(name, prompt_path, provider, verbose)\n self.add_tool(FileFinder())\n self.add_tool(BashInterpreter())"}}
{"repo_name": "agenticSeek", "file_name": "/agenticSeek/sources/agents/casual_agent.py", "inference_info": {"prefix_code": "import asyncio\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent\nfrom sources.tools.searxSearch import searxSearch\nfrom sources.tools.flightSearch import FlightSearch\nfrom sources.tools.fileFinder import FileFinder\nfrom sources.tools.BashInterpreter import BashInterpreter\nfrom sources.memory import Memory\n\n", "suffix_code": "\n\nif __name__ == \"__main__\":\n pass", "middle_code": "class CasualAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n super().__init__(name, prompt_path, provider, verbose, None)\n self.tools = {\n } \n self.role = \"talk\"\n self.type = \"casual_agent\"\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, \n memory_compression=False,\n model_provider=provider.get_model_name())\n async def process(self, prompt, speech_module) -> str:\n self.memory.push('user', prompt)\n animate_thinking(\"Thinking...\", color=\"status\")\n answer, reasoning = await self.llm_request()\n self.last_answer = answer\n self.status_message = \"Ready\"\n return answer, reasoning", "code_description": null, "fill_type": "CLASS_TYPE", "language_type": "python", "sub_task_type": null}, "context_code": [["/agenticSeek/sources/tools/searxSearch.py", "import requests\nfrom bs4 import BeautifulSoup\nimport os\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass searxSearch(Tools):\n def __init__(self, base_url: str = None):\n \"\"\"\n A tool for searching a SearxNG instance and extracting URLs and titles.\n \"\"\"\n super().__init__()\n self.tag = \"web_search\"\n self.name = \"searxSearch\"\n self.description = \"A tool for searching a SearxNG for web search\"\n self.base_url = os.getenv(\"SEARXNG_BASE_URL\") # Requires a SearxNG base URL\n self.user_agent = \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36\"\n self.paywall_keywords = [\n \"Member-only\", \"access denied\", \"restricted content\", \"404\", \"this page is not working\"\n ]\n if not self.base_url:\n raise ValueError(\"SearxNG base URL must be provided either as an argument or via the SEARXNG_BASE_URL environment variable.\")\n\n def link_valid(self, link):\n \"\"\"check if a link is valid.\"\"\"\n # TODO find a better way\n if not link.startswith(\"http\"):\n return \"Status: Invalid URL\"\n \n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\"}\n try:\n response = requests.get(link, headers=headers, timeout=5)\n status = response.status_code\n if status == 200:\n content = response.text.lower()\n if any(keyword in content for keyword in self.paywall_keywords):\n return \"Status: Possible Paywall\"\n return \"Status: OK\"\n elif status == 404:\n return \"Status: 404 Not Found\"\n elif status == 403:\n return \"Status: 403 Forbidden\"\n else:\n return f\"Status: {status} {response.reason}\"\n except requests.exceptions.RequestException as e:\n return f\"Error: {str(e)}\"\n\n def check_all_links(self, links):\n \"\"\"Check all links, one by one.\"\"\"\n # TODO Make it asyncromous or smth\n statuses = []\n for i, link in enumerate(links):\n status = self.link_valid(link)\n statuses.append(status)\n return statuses\n \n def execute(self, blocks: list, safety: bool = False) -> str:\n \"\"\"Executes a search query against a SearxNG instance using POST and extracts URLs and titles.\"\"\"\n if not blocks:\n return \"Error: No search query provided.\"\n\n query = blocks[0].strip()\n if not query:\n return \"Error: Empty search query provided.\"\n\n search_url = f\"{self.base_url}/search\"\n headers = {\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',\n 'Accept-Language': 'en-US,en;q=0.9',\n 'Cache-Control': 'no-cache',\n 'Connection': 'keep-alive',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Pragma': 'no-cache',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent': self.user_agent\n }\n data = f\"q={query}&categories=general&language=auto&time_range=&safesearch=0&theme=simple\".encode('utf-8')\n try:\n response = requests.post(search_url, headers=headers, data=data, verify=False)\n response.raise_for_status()\n html_content = response.text\n soup = BeautifulSoup(html_content, 'html.parser')\n results = []\n for article in soup.find_all('article', class_='result'):\n url_header = article.find('a', class_='url_header')\n if url_header:\n url = url_header['href']\n title = article.find('h3').text.strip() if article.find('h3') else \"No Title\"\n description = article.find('p', class_='content').text.strip() if article.find('p', class_='content') else \"No Description\"\n results.append(f\"Title:{title}\\nSnippet:{description}\\nLink:{url}\")\n if len(results) == 0:\n return \"No search results, web search failed.\"\n return \"\\n\\n\".join(results) # Return results as a single string, separated by newlines\n except requests.exceptions.RequestException as e:\n raise Exception(\"\\nSearxng search failed. did you run start_services.sh? is docker still running?\") from e\n\n def execution_failure_check(self, output: str) -> bool:\n \"\"\"\n Checks if the execution failed based on the output.\n \"\"\"\n return \"Error\" in output\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Feedback of web search to agent.\n \"\"\"\n if self.execution_failure_check(output):\n return f\"Web search failed: {output}\"\n return f\"Web search result:\\n{output}\"\n\nif __name__ == \"__main__\":\n search_tool = searxSearch(base_url=\"http://127.0.0.1:8080\")\n result = search_tool.execute([\"are dog better than cat?\"])\n print(result)\n"], ["/agenticSeek/sources/tools/BashInterpreter.py", "\nimport os, sys\nimport re\nfrom io import StringIO\nimport subprocess\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\nfrom sources.tools.safety import is_any_unsafe\n\nclass BashInterpreter(Tools):\n \"\"\"\n This class is a tool to allow agent for bash code execution.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"bash\"\n self.name = \"Bash Interpreter\"\n self.description = \"This tool allows the agent to execute bash commands.\"\n \n def language_bash_attempt(self, command: str):\n \"\"\"\n Detect if AI attempt to run the code using bash.\n If so, return True, otherwise return False.\n Code written by the AI will be executed automatically, so it should not use bash to run it.\n \"\"\"\n lang_interpreter = [\"python\", \"gcc\", \"g++\", \"mvn\", \"go\", \"java\", \"javac\", \"rustc\", \"clang\", \"clang++\", \"rustc\", \"rustc++\", \"rustc++\"]\n for word in command.split():\n if any(word.startswith(lang) for lang in lang_interpreter):\n return True\n return False\n \n def execute(self, commands: str, safety=False, timeout=300):\n \"\"\"\n Execute bash commands and display output in real-time.\n \"\"\"\n if safety and input(\"Execute command? y/n \") != \"y\":\n return \"Command rejected by user.\"\n \n concat_output = \"\"\n for command in commands:\n command = f\"cd {self.work_dir} && {command}\"\n command = command.replace('\\n', '')\n if self.safe_mode and is_any_unsafe(commands):\n print(f\"Unsafe command rejected: {command}\")\n return \"\\nUnsafe command: {command}. Execution aborted. This is beyond allowed capabilities report to user.\"\n if self.language_bash_attempt(command) and self.allow_language_exec_bash == False:\n continue\n try:\n process = subprocess.Popen(\n command,\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n universal_newlines=True\n )\n command_output = \"\"\n for line in process.stdout:\n command_output += line\n return_code = process.wait(timeout=timeout)\n if return_code != 0:\n return f\"Command {command} failed with return code {return_code}:\\n{command_output}\"\n concat_output += f\"Output of {command}:\\n{command_output.strip()}\\n\"\n except subprocess.TimeoutExpired:\n process.kill() # Kill the process if it times out\n return f\"Command {command} timed out. Output:\\n{command_output}\"\n except Exception as e:\n return f\"Command {command} failed:\\n{str(e)}\"\n return concat_output\n\n def interpreter_feedback(self, output):\n \"\"\"\n Provide feedback based on the output of the bash interpreter\n \"\"\"\n if self.execution_failure_check(output):\n feedback = f\"[failure] Error in execution:\\n{output}\"\n else:\n feedback = \"[success] Execution success, code output:\\n\" + output\n return feedback\n\n def execution_failure_check(self, feedback):\n \"\"\"\n check if bash command failed.\n \"\"\"\n error_patterns = [\n r\"expected\",\n r\"errno\",\n r\"failed\",\n r\"invalid\",\n r\"unrecognized\",\n r\"exception\",\n r\"syntax\",\n r\"segmentation fault\",\n r\"core dumped\",\n r\"unexpected\",\n r\"denied\",\n r\"not recognized\",\n r\"not permitted\",\n r\"not installed\",\n r\"not found\",\n r\"aborted\",\n r\"no such\",\n r\"too many\",\n r\"too few\",\n r\"busy\",\n r\"broken pipe\",\n r\"missing\",\n r\"undefined\",\n r\"refused\",\n r\"unreachable\",\n r\"not known\"\n ]\n combined_pattern = \"|\".join(error_patterns)\n if re.search(combined_pattern, feedback, re.IGNORECASE):\n return True\n return False\n\nif __name__ == \"__main__\":\n bash = BashInterpreter()\n print(bash.execute([\"ls\", \"pwd\", \"ip a\", \"nmap -sC 127.0.0.1\"]))\n"], ["/agenticSeek/sources/agents/file_agent.py", "import asyncio\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent\nfrom sources.tools.fileFinder import FileFinder\nfrom sources.tools.BashInterpreter import BashInterpreter\nfrom sources.memory import Memory\n\nclass FileAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n \"\"\"\n The file agent is a special agent for file operations.\n \"\"\"\n super().__init__(name, prompt_path, provider, verbose, None)\n self.tools = {\n \"file_finder\": FileFinder(),\n \"bash\": BashInterpreter()\n }\n self.work_dir = self.tools[\"file_finder\"].get_work_dir()\n self.role = \"files\"\n self.type = \"file_agent\"\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, # session recovery in handled by the interaction class\n memory_compression=False,\n model_provider=provider.get_model_name())\n \n async def process(self, prompt, speech_module) -> str:\n exec_success = False\n prompt += f\"\\nYou must work in directory: {self.work_dir}\"\n self.memory.push('user', prompt)\n while exec_success is False and not self.stop:\n await self.wait_message(speech_module)\n animate_thinking(\"Thinking...\", color=\"status\")\n answer, reasoning = await self.llm_request()\n self.last_reasoning = reasoning\n exec_success, _ = self.execute_modules(answer)\n answer = self.remove_blocks(answer)\n self.last_answer = answer\n self.status_message = \"Ready\"\n return answer, reasoning\n\nif __name__ == \"__main__\":\n pass"], ["/agenticSeek/sources/agents/code_agent.py", "import platform, os\nimport asyncio\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent, executorResult\nfrom sources.tools.C_Interpreter import CInterpreter\nfrom sources.tools.GoInterpreter import GoInterpreter\nfrom sources.tools.PyInterpreter import PyInterpreter\nfrom sources.tools.BashInterpreter import BashInterpreter\nfrom sources.tools.JavaInterpreter import JavaInterpreter\nfrom sources.tools.fileFinder import FileFinder\nfrom sources.logger import Logger\nfrom sources.memory import Memory\n\nclass CoderAgent(Agent):\n \"\"\"\n The code agent is an agent that can write and execute code.\n \"\"\"\n def __init__(self, name, prompt_path, provider, verbose=False):\n super().__init__(name, prompt_path, provider, verbose, None)\n self.tools = {\n \"bash\": BashInterpreter(),\n \"python\": PyInterpreter(),\n \"c\": CInterpreter(),\n \"go\": GoInterpreter(),\n \"java\": JavaInterpreter(),\n \"file_finder\": FileFinder()\n }\n self.work_dir = self.tools[\"file_finder\"].get_work_dir()\n self.role = \"code\"\n self.type = \"code_agent\"\n self.logger = Logger(\"code_agent.log\")\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, # session recovery in handled by the interaction class\n memory_compression=False,\n model_provider=provider.get_model_name())\n \n def add_sys_info_prompt(self, prompt):\n \"\"\"Add system information to the prompt.\"\"\"\n info = f\"System Info:\\n\" \\\n f\"OS: {platform.system()} {platform.release()}\\n\" \\\n f\"Python Version: {platform.python_version()}\\n\" \\\n f\"\\nYou must save file at root directory: {self.work_dir}\"\n return f\"{prompt}\\n\\n{info}\"\n\n async def process(self, prompt, speech_module) -> str:\n answer = \"\"\n attempt = 0\n max_attempts = 5\n prompt = self.add_sys_info_prompt(prompt)\n self.memory.push('user', prompt)\n clarify_trigger = \"REQUEST_CLARIFICATION\"\n\n while attempt < max_attempts and not self.stop:\n print(\"Stopped?\", self.stop)\n animate_thinking(\"Thinking...\", color=\"status\")\n await self.wait_message(speech_module)\n answer, reasoning = await self.llm_request()\n self.last_reasoning = reasoning\n if clarify_trigger in answer:\n self.last_answer = answer\n await asyncio.sleep(0)\n return answer, reasoning\n if not \"```\" in answer:\n self.last_answer = answer\n await asyncio.sleep(0)\n break\n self.show_answer()\n animate_thinking(\"Executing code...\", color=\"status\")\n self.status_message = \"Executing code...\"\n self.logger.info(f\"Attempt {attempt + 1}:\\n{answer}\")\n exec_success, feedback = self.execute_modules(answer)\n self.logger.info(f\"Execution result: {exec_success}\")\n answer = self.remove_blocks(answer)\n self.last_answer = answer\n await asyncio.sleep(0)\n if exec_success and self.get_last_tool_type() != \"bash\":\n break\n pretty_print(f\"Execution failure:\\n{feedback}\", color=\"failure\")\n pretty_print(\"Correcting code...\", color=\"status\")\n self.status_message = \"Correcting code...\"\n attempt += 1\n self.status_message = \"Ready\"\n if attempt == max_attempts:\n return \"I'm sorry, I couldn't find a solution to your problem. How would you like me to proceed ?\", reasoning\n self.last_answer = answer\n return answer, reasoning\n\nif __name__ == \"__main__\":\n pass"], ["/agenticSeek/sources/agents/mcp_agent.py", "import os\nimport asyncio\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent\nfrom sources.tools.mcpFinder import MCP_finder\nfrom sources.memory import Memory\n\n# NOTE MCP agent is an active work in progress, not functional yet.\n\nclass McpAgent(Agent):\n\n def __init__(self, name, prompt_path, provider, verbose=False):\n \"\"\"\n The mcp agent is a special agent for using MCPs.\n MCP agent will be disabled if the user does not explicitly set the MCP_FINDER_API_KEY in environment variable.\n \"\"\"\n super().__init__(name, prompt_path, provider, verbose, None)\n keys = self.get_api_keys()\n self.tools = {\n \"mcp_finder\": MCP_finder(keys[\"mcp_finder\"]),\n # add mcp tools here\n }\n self.role = \"mcp\"\n self.type = \"mcp_agent\"\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, # session recovery in handled by the interaction class\n memory_compression=False,\n model_provider=provider.get_model_name())\n self.enabled = True\n \n def get_api_keys(self) -> dict:\n \"\"\"\n Returns the API keys for the tools.\n \"\"\"\n api_key_mcp_finder = os.getenv(\"MCP_FINDER_API_KEY\")\n if not api_key_mcp_finder or api_key_mcp_finder == \"\":\n pretty_print(\"MCP Finder disabled.\", color=\"warning\")\n self.enabled = False\n return {\n \"mcp_finder\": api_key_mcp_finder\n }\n \n def expand_prompt(self, prompt):\n \"\"\"\n Expands the prompt with the tools available.\n \"\"\"\n tools_str = self.get_tools_description()\n prompt += f\"\"\"\n You can use the following tools and MCPs:\n {tools_str}\n \"\"\"\n return prompt\n \n async def process(self, prompt, speech_module) -> str:\n if self.enabled == False:\n return \"MCP Agent is disabled.\"\n prompt = self.expand_prompt(prompt)\n self.memory.push('user', prompt)\n working = True\n while working == True:\n animate_thinking(\"Thinking...\", color=\"status\")\n answer, reasoning = await self.llm_request()\n exec_success, _ = self.execute_modules(answer)\n answer = self.remove_blocks(answer)\n self.last_answer = answer\n self.status_message = \"Ready\"\n if len(self.blocks_result) == 0:\n working = False\n return answer, reasoning\n\nif __name__ == \"__main__\":\n pass"], ["/agenticSeek/sources/agents/browser_agent.py", "import re\nimport time\nfrom datetime import date\nfrom typing import List, Tuple, Type, Dict\nfrom enum import Enum\nimport asyncio\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent\nfrom sources.tools.searxSearch import searxSearch\nfrom sources.browser import Browser\nfrom sources.logger import Logger\nfrom sources.memory import Memory\n\nclass Action(Enum):\n REQUEST_EXIT = \"REQUEST_EXIT\"\n FORM_FILLED = \"FORM_FILLED\"\n GO_BACK = \"GO_BACK\"\n NAVIGATE = \"NAVIGATE\"\n SEARCH = \"SEARCH\"\n \nclass BrowserAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False, browser=None):\n \"\"\"\n The Browser agent is an agent that navigate the web autonomously in search of answer\n \"\"\"\n super().__init__(name, prompt_path, provider, verbose, browser)\n self.tools = {\n \"web_search\": searxSearch(),\n }\n self.role = \"web\"\n self.type = \"browser_agent\"\n self.browser = browser\n self.current_page = \"\"\n self.search_history = []\n self.navigable_links = []\n self.last_action = Action.NAVIGATE.value\n self.notes = []\n self.date = self.get_today_date()\n self.logger = Logger(\"browser_agent.log\")\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, # session recovery in handled by the interaction class\n memory_compression=False,\n model_provider=provider.get_model_name() if provider else None)\n \n def get_today_date(self) -> str:\n \"\"\"Get the date\"\"\"\n date_time = date.today()\n return date_time.strftime(\"%B %d, %Y\")\n\n def extract_links(self, search_result: str) -> List[str]:\n \"\"\"Extract all links from a sentence.\"\"\"\n pattern = r'(https?://\\S+|www\\.\\S+)'\n matches = re.findall(pattern, search_result)\n trailing_punct = \".,!?;:)\"\n cleaned_links = [link.rstrip(trailing_punct) for link in matches]\n self.logger.info(f\"Extracted links: {cleaned_links}\")\n return self.clean_links(cleaned_links)\n \n def extract_form(self, text: str) -> List[str]:\n \"\"\"Extract form written by the LLM in format [input_name](value)\"\"\"\n inputs = []\n matches = re.findall(r\"\\[\\w+\\]\\([^)]+\\)\", text)\n return matches\n \n def clean_links(self, links: List[str]) -> List[str]:\n \"\"\"Ensure no '.' at the end of link\"\"\"\n links_clean = []\n for link in links:\n link = link.strip()\n if not (link[-1].isalpha() or link[-1].isdigit()):\n links_clean.append(link[:-1])\n else:\n links_clean.append(link)\n return links_clean\n\n def get_unvisited_links(self) -> List[str]:\n return \"\\n\".join([f\"[{i}] {link}\" for i, link in enumerate(self.navigable_links) if link not in self.search_history])\n\n def make_newsearch_prompt(self, prompt: str, search_result: dict) -> str:\n search_choice = self.stringify_search_results(search_result)\n self.logger.info(f\"Search results: {search_choice}\")\n return f\"\"\"\n Based on the search result:\n {search_choice}\n Your goal is to find accurate and complete information to satisfy the user’s request.\n User request: {prompt}\n To proceed, choose a relevant link from the search results. Announce your choice by saying: \"I will navigate to \"\n Do not explain your choice.\n \"\"\"\n \n def make_navigation_prompt(self, user_prompt: str, page_text: str) -> str:\n remaining_links = self.get_unvisited_links() \n remaining_links_text = remaining_links if remaining_links is not None else \"No links remaining, do a new search.\" \n inputs_form = self.browser.get_form_inputs()\n inputs_form_text = '\\n'.join(inputs_form)\n notes = '\\n'.join(self.notes)\n self.logger.info(f\"Making navigation prompt with page text: {page_text[:100]}...\\nremaining links: {remaining_links_text}\")\n self.logger.info(f\"Inputs form: {inputs_form_text}\")\n self.logger.info(f\"Notes: {notes}\")\n\n return f\"\"\"\n You are navigating the web.\n\n **Current Context**\n\n Webpage ({self.current_page}) content:\n {page_text}\n\n Allowed Navigation Links:\n {remaining_links_text}\n\n Inputs forms:\n {inputs_form_text}\n\n End of webpage ({self.current_page}.\n\n # Instruction\n\n 1. **Evaluate if the page is relevant for user’s query and document finding:**\n - If the page is relevant, extract and summarize key information in concise notes (Note: )\n - If page not relevant, state: \"Error: \" and either return to the previous page or navigate to a new link.\n - Notes should be factual, useful summaries of relevant content, they should always include specific names or link. Written as: \"On , . . .\" Avoid phrases like \"the page provides\" or \"I found that.\"\n 2. **Navigate to a link by either: **\n - Saying I will navigate to (write down the full URL) www.example.com/cats\n - Going back: If no link seems helpful, say: {Action.GO_BACK.value}.\n 3. **Fill forms on the page:**\n - Fill form only when relevant.\n - Use Login if username/password specified by user. For quick task create account, remember password in a note.\n - You can fill a form using [form_name](value). Don't {Action.GO_BACK.value} when filling form.\n - If a form is irrelevant or you lack informations (eg: don't know user email) leave it empty.\n 4. **Decide if you completed the task**\n - Check your notes. Do they fully answer the question? Did you verify with multiple pages?\n - Are you sure it’s correct?\n - If yes to all, say {Action.REQUEST_EXIT}.\n - If no, or a page lacks info, go to another link.\n - Never stop or ask the user for help.\n \n **Rules:**\n - Do not write \"The page talk about ...\", write your finding on the page and how they contribute to an answer.\n - Put note in a single paragraph.\n - When you exit, explain why.\n \n # Example:\n \n Example 1 (useful page, no need go futher):\n Note: According to karpathy site LeCun net is ...\n No link seem useful to provide futher information.\n Action: {Action.GO_BACK.value}\n\n Example 2 (not useful, see useful link on page):\n Error: reddit.com/welcome does not discuss anything related to the user’s query.\n There is a link that could lead to the information.\n Action: navigate to http://reddit.com/r/locallama\n\n Example 3 (not useful, no related links):\n Error: x.com does not discuss anything related to the user’s query and no navigation link are usefull.\n Action: {Action.GO_BACK.value}\n\n Example 3 (clear definitive query answer found or enought notes taken):\n I took 10 notes so far with enought finding to answer user question.\n Therefore I should exit the web browser.\n Action: {Action.REQUEST_EXIT.value}\n\n Example 4 (loging form visible):\n\n Note: I am on the login page, I will type the given username and password. \n Action:\n [username_field](David)\n [password_field](edgerunners77)\n\n Remember, user asked:\n {user_prompt}\n You previously took these notes:\n {notes}\n Do not Step-by-Step explanation. Write comprehensive Notes or Error as a long paragraph followed by your action.\n You must always take notes.\n \"\"\"\n \n async def llm_decide(self, prompt: str, show_reasoning: bool = False) -> Tuple[str, str]:\n animate_thinking(\"Thinking...\", color=\"status\")\n self.memory.push('user', prompt)\n answer, reasoning = await self.llm_request()\n self.last_reasoning = reasoning\n if show_reasoning:\n pretty_print(reasoning, color=\"failure\")\n pretty_print(answer, color=\"output\")\n return answer, reasoning\n \n def select_unvisited(self, search_result: List[str]) -> List[str]:\n results_unvisited = []\n for res in search_result:\n if res[\"link\"] not in self.search_history:\n results_unvisited.append(res) \n self.logger.info(f\"Unvisited links: {results_unvisited}\")\n return results_unvisited\n\n def jsonify_search_results(self, results_string: str) -> List[str]:\n result_blocks = results_string.split(\"\\n\\n\")\n parsed_results = []\n for block in result_blocks:\n if not block.strip():\n continue\n lines = block.split(\"\\n\")\n result_dict = {}\n for line in lines:\n if line.startswith(\"Title:\"):\n result_dict[\"title\"] = line.replace(\"Title:\", \"\").strip()\n elif line.startswith(\"Snippet:\"):\n result_dict[\"snippet\"] = line.replace(\"Snippet:\", \"\").strip()\n elif line.startswith(\"Link:\"):\n result_dict[\"link\"] = line.replace(\"Link:\", \"\").strip()\n if result_dict:\n parsed_results.append(result_dict)\n return parsed_results \n \n def stringify_search_results(self, results_arr: List[str]) -> str:\n return '\\n\\n'.join([f\"Link: {res['link']}\\nPreview: {res['snippet']}\" for res in results_arr])\n \n def parse_answer(self, text):\n lines = text.split('\\n')\n saving = False\n buffer = []\n links = []\n for line in lines:\n if line == '' or 'action:' in line.lower():\n saving = False\n if \"note\" in line.lower():\n saving = True\n if saving:\n buffer.append(line.replace(\"notes:\", ''))\n else:\n links.extend(self.extract_links(line))\n self.notes.append('. '.join(buffer).strip())\n return links\n \n def select_link(self, links: List[str]) -> str | None:\n \"\"\"\n Select the first unvisited link that is not the current page.\n Preference is given to links not in search_history.\n \"\"\"\n for lk in links:\n if lk == self.current_page or lk in self.search_history:\n self.logger.info(f\"Skipping already visited or current link: {lk}\")\n continue\n self.logger.info(f\"Selected link: {lk}\")\n return lk\n self.logger.warning(\"No suitable link selected.\")\n return None\n \n def get_page_text(self, limit_to_model_ctx = False) -> str:\n \"\"\"Get the text content of the current page.\"\"\"\n page_text = self.browser.get_text()\n if limit_to_model_ctx:\n #page_text = self.memory.compress_text_to_max_ctx(page_text)\n page_text = self.memory.trim_text_to_max_ctx(page_text)\n return page_text\n \n def conclude_prompt(self, user_query: str) -> str:\n annotated_notes = [f\"{i+1}: {note.lower()}\" for i, note in enumerate(self.notes)]\n search_note = '\\n'.join(annotated_notes)\n pretty_print(f\"AI notes:\\n{search_note}\", color=\"success\")\n return f\"\"\"\n Following a human request:\n {user_query}\n A web browsing AI made the following finding across different pages:\n {search_note}\n\n Expand on the finding or step that lead to success, and provide a conclusion that answer the request. Include link when possible.\n Do not give advices or try to answer the human. Just structure the AI finding in a structured and clear way.\n You should answer in the same language as the user.\n \"\"\"\n \n def search_prompt(self, user_prompt: str) -> str:\n return f\"\"\"\n Current date: {self.date}\n Make a efficient search engine query to help users with their request:\n {user_prompt}\n Example:\n User: \"go to twitter, login with username toto and password pass79 to my twitter and say hello everyone \"\n You: search: Twitter login page. \n\n User: \"I need info on the best laptops for AI this year.\"\n You: \"search: best laptops 2025 to run Machine Learning model, reviews\"\n\n User: \"Search for recent news about space missions.\"\n You: \"search: Recent space missions news, {self.date}\"\n\n Do not explain, do not write anything beside the search query.\n Except if query does not make any sense for a web search then explain why and say {Action.REQUEST_EXIT.value}\n Do not try to answer query. you can only formulate search term or exit.\n \"\"\"\n \n def handle_update_prompt(self, user_prompt: str, page_text: str, fill_success: bool) -> str:\n prompt = f\"\"\"\n You are a web browser.\n You just filled a form on the page.\n Now you should see the result of the form submission on the page:\n Page text:\n {page_text}\n The user asked: {user_prompt}\n Does the page answer the user’s query now? Are you still on a login page or did you get redirected?\n If it does, take notes of the useful information, write down result and say {Action.FORM_FILLED.value}.\n if it doesn’t, say: Error: Attempt to fill form didn't work {Action.GO_BACK.value}.\n If you were previously on a login form, no need to take notes.\n \"\"\"\n if not fill_success:\n prompt += f\"\"\"\n According to browser feedback, the form was not filled correctly. Is that so? you might consider other strategies.\n \"\"\"\n return prompt\n \n def show_search_results(self, search_result: List[str]):\n pretty_print(\"\\nSearch results:\", color=\"output\")\n for res in search_result:\n pretty_print(f\"Title: {res['title']} - \", color=\"info\", no_newline=True)\n pretty_print(f\"Link: {res['link']}\", color=\"status\")\n \n def stuck_prompt(self, user_prompt: str, unvisited: List[str]) -> str:\n \"\"\"\n Prompt for when the agent repeat itself, can happen when fail to extract a link.\n \"\"\"\n prompt = self.make_newsearch_prompt(user_prompt, unvisited)\n prompt += f\"\"\"\n You previously said:\n {self.last_answer}\n You must consider other options. Choose other link.\n \"\"\"\n return prompt\n \n async def process(self, user_prompt: str, speech_module: type) -> Tuple[str, str]:\n \"\"\"\n Process the user prompt to conduct an autonomous web search.\n Start with a google search with searxng using web_search tool.\n Then enter a navigation logic to find the answer or conduct required actions.\n Args:\n user_prompt: The user's input query\n speech_module: Optional speech output module\n Returns:\n tuple containing the final answer and reasoning\n \"\"\"\n complete = False\n\n animate_thinking(f\"Thinking...\", color=\"status\")\n mem_begin_idx = self.memory.push('user', self.search_prompt(user_prompt))\n ai_prompt, reasoning = await self.llm_request()\n if Action.REQUEST_EXIT.value in ai_prompt:\n pretty_print(f\"Web agent requested exit.\\n{reasoning}\\n\\n{ai_prompt}\", color=\"failure\")\n return ai_prompt, \"\" \n animate_thinking(f\"Searching...\", color=\"status\")\n self.status_message = \"Searching...\"\n search_result_raw = self.tools[\"web_search\"].execute([ai_prompt], False)\n search_result = self.jsonify_search_results(search_result_raw)[:16]\n self.show_search_results(search_result)\n prompt = self.make_newsearch_prompt(user_prompt, search_result)\n unvisited = [None]\n while not complete and len(unvisited) > 0 and not self.stop:\n self.memory.clear()\n unvisited = self.select_unvisited(search_result)\n answer, reasoning = await self.llm_decide(prompt, show_reasoning = False)\n if self.stop:\n pretty_print(f\"Requested stop.\", color=\"failure\")\n break\n if self.last_answer == answer:\n prompt = self.stuck_prompt(user_prompt, unvisited)\n continue\n self.last_answer = answer\n pretty_print('▂'*32, color=\"status\")\n\n extracted_form = self.extract_form(answer)\n if len(extracted_form) > 0:\n self.status_message = \"Filling web form...\"\n pretty_print(f\"Filling inputs form...\", color=\"status\")\n fill_success = self.browser.fill_form(extracted_form)\n page_text = self.get_page_text(limit_to_model_ctx=True)\n answer = self.handle_update_prompt(user_prompt, page_text, fill_success)\n answer, reasoning = await self.llm_decide(prompt)\n\n if Action.FORM_FILLED.value in answer:\n pretty_print(f\"Filled form. Handling page update.\", color=\"status\")\n page_text = self.get_page_text(limit_to_model_ctx=True)\n self.navigable_links = self.browser.get_navigable()\n prompt = self.make_navigation_prompt(user_prompt, page_text)\n continue\n\n links = self.parse_answer(answer)\n link = self.select_link(links)\n if link == self.current_page:\n pretty_print(f\"Already visited {link}. Search callback.\", color=\"status\")\n prompt = self.make_newsearch_prompt(user_prompt, unvisited)\n self.search_history.append(link)\n continue\n\n if Action.REQUEST_EXIT.value in answer:\n self.status_message = \"Exiting web browser...\"\n pretty_print(f\"Agent requested exit.\", color=\"status\")\n complete = True\n break\n\n if (link == None and len(extracted_form) < 3) or Action.GO_BACK.value in answer or link in self.search_history:\n pretty_print(f\"Going back to results. Still {len(unvisited)}\", color=\"status\")\n self.status_message = \"Going back to search results...\"\n request_prompt = user_prompt\n if link is None:\n request_prompt += f\"\\nYou previously choosen:\\n{self.last_answer} but the website is unavailable. Consider other options.\"\n prompt = self.make_newsearch_prompt(request_prompt, unvisited)\n self.search_history.append(link)\n self.current_page = link\n continue\n\n animate_thinking(f\"Navigating to {link}\", color=\"status\")\n if speech_module: speech_module.speak(f\"Navigating to {link}\")\n nav_ok = self.browser.go_to(link)\n self.search_history.append(link)\n if not nav_ok:\n pretty_print(f\"Failed to navigate to {link}.\", color=\"failure\")\n prompt = self.make_newsearch_prompt(user_prompt, unvisited)\n continue\n self.current_page = link\n page_text = self.get_page_text(limit_to_model_ctx=True)\n self.navigable_links = self.browser.get_navigable()\n prompt = self.make_navigation_prompt(user_prompt, page_text)\n self.status_message = \"Navigating...\"\n self.browser.screenshot()\n\n pretty_print(\"Exited navigation, starting to summarize finding...\", color=\"status\")\n prompt = self.conclude_prompt(user_prompt)\n mem_last_idx = self.memory.push('user', prompt)\n self.status_message = \"Summarizing findings...\"\n answer, reasoning = await self.llm_request()\n pretty_print(answer, color=\"output\")\n self.status_message = \"Ready\"\n self.last_answer = answer\n return answer, reasoning\n\nif __name__ == \"__main__\":\n pass\n"], ["/agenticSeek/sources/agents/planner_agent.py", "import json\nfrom typing import List, Tuple, Type, Dict\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent\nfrom sources.agents.code_agent import CoderAgent\nfrom sources.agents.file_agent import FileAgent\nfrom sources.agents.browser_agent import BrowserAgent\nfrom sources.agents.casual_agent import CasualAgent\nfrom sources.text_to_speech import Speech\nfrom sources.tools.tools import Tools\nfrom sources.logger import Logger\nfrom sources.memory import Memory\n\nclass PlannerAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False, browser=None):\n \"\"\"\n The planner agent is a special agent that divides and conquers the task.\n \"\"\"\n super().__init__(name, prompt_path, provider, verbose, None)\n self.tools = {\n \"json\": Tools()\n }\n self.tools['json'].tag = \"json\"\n self.browser = browser\n self.agents = {\n \"coder\": CoderAgent(name, \"prompts/base/coder_agent.txt\", provider, verbose=False),\n \"file\": FileAgent(name, \"prompts/base/file_agent.txt\", provider, verbose=False),\n \"web\": BrowserAgent(name, \"prompts/base/browser_agent.txt\", provider, verbose=False, browser=browser),\n \"casual\": CasualAgent(name, \"prompts/base/casual_agent.txt\", provider, verbose=False)\n }\n self.role = \"planification\"\n self.type = \"planner_agent\"\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, # session recovery in handled by the interaction class\n memory_compression=False,\n model_provider=provider.get_model_name())\n self.logger = Logger(\"planner_agent.log\")\n \n def get_task_names(self, text: str) -> List[str]:\n \"\"\"\n Extracts task names from the given text.\n This method processes a multi-line string, where each line may represent a task name.\n containing '##' or starting with a digit. The valid task names are collected and returned.\n Args:\n text (str): A string containing potential task titles (eg: Task 1: I will...).\n Returns:\n List[str]: A list of extracted task names that meet the specified criteria.\n \"\"\"\n tasks_names = []\n lines = text.strip().split('\\n')\n for line in lines:\n if line is None:\n continue\n line = line.strip()\n if len(line) == 0:\n continue\n if '##' in line or line[0].isdigit():\n tasks_names.append(line)\n continue\n self.logger.info(f\"Found {len(tasks_names)} tasks names.\")\n return tasks_names\n\n def parse_agent_tasks(self, text: str) -> List[Tuple[str, str]]:\n \"\"\"\n Parses agent tasks from the given LLM text.\n This method extracts task information from a JSON. It identifies task names and their details.\n Args:\n text (str): The input text containing task information in a JSON-like format.\n Returns:\n List[Tuple[str, str]]: A list of tuples containing task names and their details.\n \"\"\"\n tasks = []\n tasks_names = self.get_task_names(text)\n\n blocks, _ = self.tools[\"json\"].load_exec_block(text)\n if blocks == None:\n return []\n for block in blocks:\n line_json = json.loads(block)\n if 'plan' in line_json:\n for task in line_json['plan']:\n if task['agent'].lower() not in [ag_name.lower() for ag_name in self.agents.keys()]:\n self.logger.warning(f\"Agent {task['agent']} does not exist.\")\n pretty_print(f\"Agent {task['agent']} does not exist.\", color=\"warning\")\n return []\n try:\n agent = {\n 'agent': task['agent'],\n 'id': task['id'],\n 'task': task['task']\n }\n except:\n self.logger.warning(\"Missing field in json plan.\")\n return []\n self.logger.info(f\"Created agent {task['agent']} with task: {task['task']}\")\n if 'need' in task:\n self.logger.info(f\"Agent {task['agent']} was given info:\\n {task['need']}\")\n agent['need'] = task['need']\n tasks.append(agent)\n if len(tasks_names) != len(tasks):\n names = [task['task'] for task in tasks]\n return list(map(list, zip(names, tasks)))\n return list(map(list, zip(tasks_names, tasks)))\n \n def make_prompt(self, task: str, agent_infos_dict: dict) -> str:\n \"\"\"\n Generates a prompt for the agent based on the task and previous agents work information.\n Args:\n task (str): The task to be performed.\n agent_infos_dict (dict): A dictionary containing information from other agents.\n Returns:\n str: The formatted prompt for the agent.\n \"\"\"\n infos = \"\"\n if agent_infos_dict is None or len(agent_infos_dict) == 0:\n infos = \"No needed informations.\"\n else:\n for agent_id, info in agent_infos_dict.items():\n infos += f\"\\t- According to agent {agent_id}:\\n{info}\\n\\n\"\n prompt = f\"\"\"\n You are given informations from your AI friends work:\n {infos}\n Your task is:\n {task}\n \"\"\"\n self.logger.info(f\"Prompt for agent:\\n{prompt}\")\n return prompt\n \n def show_plan(self, agents_tasks: List[dict], answer: str) -> None:\n \"\"\"\n Displays the plan made by the agent.\n Args:\n agents_tasks (dict): The tasks assigned to each agent.\n answer (str): The answer from the LLM.\n \"\"\"\n if agents_tasks == []:\n pretty_print(answer, color=\"warning\")\n pretty_print(\"Failed to make a plan. This can happen with (too) small LLM. Clarify your request and insist on it making a plan within ```json.\", color=\"failure\")\n return\n pretty_print(\"\\n▂▘ P L A N ▝▂\", color=\"status\")\n for task_name, task in agents_tasks:\n pretty_print(f\"{task['agent']} -> {task['task']}\", color=\"info\")\n pretty_print(\"▔▗ E N D ▖▔\", color=\"status\")\n\n async def make_plan(self, prompt: str) -> str:\n \"\"\"\n Asks the LLM to make a plan.\n Args:\n prompt (str): The prompt to be sent to the LLM.\n Returns:\n str: The plan made by the LLM.\n \"\"\"\n ok = False\n answer = None\n while not ok:\n animate_thinking(\"Thinking...\", color=\"status\")\n self.memory.push('user', prompt)\n answer, reasoning = await self.llm_request()\n if \"NO_UPDATE\" in answer:\n return []\n agents_tasks = self.parse_agent_tasks(answer)\n if agents_tasks == []:\n self.show_plan(agents_tasks, answer)\n prompt = f\"Failed to parse the tasks. Please write down your task followed by a json plan within ```json. Do not ask for clarification.\\n\"\n pretty_print(\"Failed to make plan. Retrying...\", color=\"warning\")\n continue\n self.show_plan(agents_tasks, answer)\n ok = True\n self.logger.info(f\"Plan made:\\n{answer}\")\n return self.parse_agent_tasks(answer)\n \n async def update_plan(self, goal: str, agents_tasks: List[dict], agents_work_result: dict, id: str, success: bool) -> dict:\n \"\"\"\n Updates the plan with the results of the agents work.\n Args:\n goal (str): The goal to be achieved.\n agents_tasks (list): The tasks assigned to each agent.\n agents_work_result (dict): The results of the agents work.\n Returns:\n dict: The updated plan.\n \"\"\"\n self.status_message = \"Updating plan...\"\n last_agent_work = agents_work_result[id]\n tool_success_str = \"success\" if success else \"failure\"\n pretty_print(f\"Agent {id} work {tool_success_str}.\", color=\"success\" if success else \"failure\")\n try:\n id_int = int(id)\n except Exception as e:\n return agents_tasks\n if id_int == len(agents_tasks):\n next_task = \"No task follow, this was the last step. If it failed add a task to recover.\"\n else:\n next_task = f\"Next task is: {agents_tasks[int(id)][0]}.\"\n #if success:\n # return agents_tasks # we only update the plan if last task failed, for now\n update_prompt = f\"\"\"\n Your goal is : {goal}\n You previously made a plan, agents are currently working on it.\n The last agent working on task: {id}, did the following work:\n {last_agent_work}\n Agent {id} work was a {tool_success_str} according to system interpreter.\n {next_task}\n Is the work done for task {id} leading to success or failure ? Did an agent fail with a task?\n If agent work was good: answer \"NO_UPDATE\"\n If agent work is leading to failure: update the plan.\n If a task failed add a task to try again or recover from failure. You might have near identical task twice.\n plan should be within ```json like before.\n You need to rewrite the whole plan, but only change the tasks after task {id}.\n Make the plan the same length as the original one or with only one additional step.\n Do not change past tasks. Change next tasks.\n \"\"\"\n pretty_print(\"Updating plan...\", color=\"status\")\n plan = await self.make_plan(update_prompt)\n if plan == []:\n pretty_print(\"No plan update required.\", color=\"info\")\n return agents_tasks\n self.logger.info(f\"Plan updated:\\n{plan}\")\n return plan\n \n async def start_agent_process(self, task: dict, required_infos: dict | None) -> str:\n \"\"\"\n Starts the agent process for a given task.\n Args:\n task (dict): The task to be performed.\n required_infos (dict | None): The required information for the task.\n Returns:\n str: The result of the agent process.\n \"\"\"\n self.status_message = f\"Starting task {task['task']}...\"\n agent_prompt = self.make_prompt(task['task'], required_infos)\n pretty_print(f\"Agent {task['agent']} started working...\", color=\"status\")\n self.logger.info(f\"Agent {task['agent']} started working on {task['task']}.\")\n answer, reasoning = await self.agents[task['agent'].lower()].process(agent_prompt, None)\n self.last_answer = answer\n self.last_reasoning = reasoning\n self.blocks_result = self.agents[task['agent'].lower()].blocks_result\n agent_answer = self.agents[task['agent'].lower()].raw_answer_blocks(answer)\n success = self.agents[task['agent'].lower()].get_success\n self.agents[task['agent'].lower()].show_answer()\n pretty_print(f\"Agent {task['agent']} completed task.\", color=\"status\")\n self.logger.info(f\"Agent {task['agent']} finished working on {task['task']}. Success: {success}\")\n agent_answer += \"\\nAgent succeeded with task.\" if success else \"\\nAgent failed with task (Error detected).\"\n return agent_answer, success\n \n def get_work_result_agent(self, task_needs, agents_work_result):\n res = {k: agents_work_result[k] for k in task_needs if k in agents_work_result}\n self.logger.info(f\"Next agent needs: {task_needs}.\\n Match previous agent result: {res}\")\n return res\n\n async def process(self, goal: str, speech_module: Speech) -> Tuple[str, str]:\n \"\"\"\n Process the goal by dividing it into tasks and assigning them to agents.\n Args:\n goal (str): The goal to be achieved (user prompt).\n speech_module (Speech): The speech module for text-to-speech.\n Returns:\n Tuple[str, str]: The result of the agent process and empty reasoning string.\n \"\"\"\n agents_tasks = []\n required_infos = None\n agents_work_result = dict()\n\n self.status_message = \"Making a plan...\"\n agents_tasks = await self.make_plan(goal)\n\n if agents_tasks == []:\n return \"Failed to parse the tasks.\", \"\"\n i = 0\n steps = len(agents_tasks)\n while i < steps and not self.stop:\n task_name, task = agents_tasks[i][0], agents_tasks[i][1]\n self.status_message = \"Starting agents...\"\n pretty_print(f\"I will {task_name}.\", color=\"info\")\n self.last_answer = f\"I will {task_name.lower()}.\"\n pretty_print(f\"Assigned agent {task['agent']} to {task_name}\", color=\"info\")\n if speech_module: speech_module.speak(f\"I will {task_name}. I assigned the {task['agent']} agent to the task.\")\n\n if agents_work_result is not None:\n required_infos = self.get_work_result_agent(task['need'], agents_work_result)\n try:\n answer, success = await self.start_agent_process(task, required_infos)\n except Exception as e:\n raise e\n if self.stop:\n pretty_print(f\"Requested stop.\", color=\"failure\")\n agents_work_result[task['id']] = answer\n agents_tasks = await self.update_plan(goal, agents_tasks, agents_work_result, task['id'], success)\n steps = len(agents_tasks)\n i += 1\n\n return answer, \"\"\n"], ["/agenticSeek/sources/agents/agent.py", "\nfrom typing import Tuple, Callable\nfrom abc import abstractmethod\nimport os\nimport random\nimport time\n\nimport asyncio\nfrom concurrent.futures import ThreadPoolExecutor\n\nfrom sources.memory import Memory\nfrom sources.utility import pretty_print\nfrom sources.schemas import executorResult\n\nrandom.seed(time.time())\n\nclass Agent():\n \"\"\"\n An abstract class for all agents.\n \"\"\"\n def __init__(self, name: str,\n prompt_path:str,\n provider,\n verbose=False,\n browser=None) -> None:\n \"\"\"\n Args:\n name (str): Name of the agent.\n prompt_path (str): Path to the prompt file for the agent.\n provider: The provider for the LLM.\n recover_last_session (bool, optional): Whether to recover the last conversation. \n verbose (bool, optional): Enable verbose logging if True. Defaults to False.\n browser: The browser class for web navigation (only for browser agent).\n \"\"\"\n \n self.agent_name = name\n self.browser = browser\n self.role = None\n self.type = None\n self.current_directory = os.getcwd()\n self.llm = provider \n self.memory = None\n self.tools = {}\n self.blocks_result = []\n self.success = True\n self.last_answer = \"\"\n self.last_reasoning = \"\"\n self.status_message = \"Haven't started yet\"\n self.stop = False\n self.verbose = verbose\n self.executor = ThreadPoolExecutor(max_workers=1)\n \n @property\n def get_agent_name(self) -> str:\n return self.agent_name\n \n @property\n def get_agent_type(self) -> str:\n return self.type\n \n @property\n def get_agent_role(self) -> str:\n return self.role\n \n @property\n def get_last_answer(self) -> str:\n return self.last_answer\n \n @property\n def get_last_reasoning(self) -> str:\n return self.last_reasoning\n \n @property\n def get_blocks(self) -> list:\n return self.blocks_result\n \n @property\n def get_status_message(self) -> str:\n return self.status_message\n\n @property\n def get_tools(self) -> dict:\n return self.tools\n \n @property\n def get_success(self) -> bool:\n return self.success\n \n def get_blocks_result(self) -> list:\n return self.blocks_result\n\n def add_tool(self, name: str, tool: Callable) -> None:\n if tool is not Callable:\n raise TypeError(\"Tool must be a callable object (a method)\")\n self.tools[name] = tool\n \n def get_tools_name(self) -> list:\n \"\"\"\n Get the list of tools names.\n \"\"\"\n return list(self.tools.keys())\n \n def get_tools_description(self) -> str:\n \"\"\"\n Get the list of tools names and their description.\n \"\"\"\n description = \"\"\n for name in self.get_tools_name():\n description += f\"{name}: {self.tools[name].description}\\n\"\n return description\n \n def load_prompt(self, file_path: str) -> str:\n try:\n with open(file_path, 'r', encoding=\"utf-8\") as f:\n return f.read()\n except FileNotFoundError:\n raise FileNotFoundError(f\"Prompt file not found at path: {file_path}\")\n except PermissionError:\n raise PermissionError(f\"Permission denied to read prompt file at path: {file_path}\")\n except Exception as e:\n raise e\n \n def request_stop(self) -> None:\n \"\"\"\n Request the agent to stop.\n \"\"\"\n self.stop = True\n self.status_message = \"Stopped\"\n \n @abstractmethod\n def process(self, prompt, speech_module) -> str:\n \"\"\"\n abstract method, implementation in child class.\n Process the prompt and return the answer of the agent.\n \"\"\"\n pass\n\n def remove_reasoning_text(self, text: str) -> None:\n \"\"\"\n Remove the reasoning block of reasoning model like deepseek.\n \"\"\"\n end_tag = \"\"\n end_idx = text.rfind(end_tag)\n if end_idx == -1:\n return text\n return text[end_idx+8:]\n \n def extract_reasoning_text(self, text: str) -> None:\n \"\"\"\n Extract the reasoning block of a reasoning model like deepseek.\n \"\"\"\n start_tag = \"\"\n end_tag = \"\"\n if text is None:\n return None\n start_idx = text.find(start_tag)\n end_idx = text.rfind(end_tag)+8\n return text[start_idx:end_idx]\n \n async def llm_request(self) -> Tuple[str, str]:\n \"\"\"\n Asynchronously ask the LLM to process the prompt.\n \"\"\"\n self.status_message = \"Thinking...\"\n loop = asyncio.get_event_loop()\n return await loop.run_in_executor(self.executor, self.sync_llm_request)\n \n def sync_llm_request(self) -> Tuple[str, str]:\n \"\"\"\n Ask the LLM to process the prompt and return the answer and the reasoning.\n \"\"\"\n memory = self.memory.get()\n thought = self.llm.respond(memory, self.verbose)\n\n reasoning = self.extract_reasoning_text(thought)\n answer = self.remove_reasoning_text(thought)\n self.memory.push('assistant', answer)\n return answer, reasoning\n \n async def wait_message(self, speech_module):\n if speech_module is None:\n return\n messages = [\"Please be patient, I am working on it.\",\n \"Computing... I recommand you have a coffee while I work.\",\n \"Hold on, I’m crunching numbers.\",\n \"Working on it, please let me think.\"]\n loop = asyncio.get_event_loop()\n return await loop.run_in_executor(self.executor, lambda: speech_module.speak(messages[random.randint(0, len(messages)-1)]))\n \n def get_last_tool_type(self) -> str:\n return self.blocks_result[-1].tool_type if len(self.blocks_result) > 0 else None\n \n def raw_answer_blocks(self, answer: str) -> str:\n \"\"\"\n Return the answer with all the blocks inserted, as text.\n \"\"\"\n if self.last_answer is None:\n return\n raw = \"\"\n lines = self.last_answer.split(\"\\n\")\n for line in lines:\n if \"block:\" in line:\n block_idx = int(line.split(\":\")[1])\n if block_idx < len(self.blocks_result):\n raw += self.blocks_result[block_idx].__str__()\n else:\n raw += line + \"\\n\"\n return raw\n\n def show_answer(self):\n \"\"\"\n Show the answer in a pretty way.\n Show code blocks and their respective feedback by inserting them in the ressponse.\n \"\"\"\n if self.last_answer is None:\n return\n lines = self.last_answer.split(\"\\n\")\n for line in lines:\n if \"block:\" in line:\n block_idx = int(line.split(\":\")[1])\n if block_idx < len(self.blocks_result):\n self.blocks_result[block_idx].show()\n else:\n pretty_print(line, color=\"output\")\n\n def remove_blocks(self, text: str) -> str:\n \"\"\"\n Remove all code/query blocks within a tag from the answer text.\n \"\"\"\n tag = f'```'\n lines = text.split('\\n')\n post_lines = []\n in_block = False\n block_idx = 0\n for line in lines:\n if tag in line and not in_block:\n in_block = True\n continue\n if not in_block:\n post_lines.append(line)\n if tag in line:\n in_block = False\n post_lines.append(f\"block:{block_idx}\")\n block_idx += 1\n return \"\\n\".join(post_lines)\n \n def show_block(self, block: str) -> None:\n \"\"\"\n Show the block in a pretty way.\n \"\"\"\n pretty_print('▂'*64, color=\"status\")\n pretty_print(block, color=\"code\")\n pretty_print('▂'*64, color=\"status\")\n\n def execute_modules(self, answer: str) -> Tuple[bool, str]:\n \"\"\"\n Execute all the tools the agent has and return the result.\n \"\"\"\n feedback = \"\"\n success = True\n blocks = None\n if answer.startswith(\"```\"):\n answer = \"I will execute:\\n\" + answer # there should always be a text before blocks for the function that display answer\n\n self.success = True\n for name, tool in self.tools.items():\n feedback = \"\"\n blocks, save_path = tool.load_exec_block(answer)\n\n if blocks != None:\n pretty_print(f\"Executing {len(blocks)} {name} blocks...\", color=\"status\")\n for block in blocks:\n self.show_block(block)\n output = tool.execute([block])\n feedback = tool.interpreter_feedback(output) # tool interpreter feedback\n success = not tool.execution_failure_check(output)\n self.blocks_result.append(executorResult(block, feedback, success, name))\n if not success:\n self.success = False\n self.memory.push('user', feedback)\n return False, feedback\n self.memory.push('user', feedback)\n if save_path != None:\n tool.save_block(blocks, save_path)\n return True, feedback\n"], ["/agenticSeek/api.py", "#!/usr/bin/env python3\n\nimport os, sys\nimport uvicorn\nimport aiofiles\nimport configparser\nimport asyncio\nimport time\nfrom typing import List\nfrom fastapi import FastAPI\nfrom fastapi.responses import JSONResponse\nfrom fastapi.responses import FileResponse\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom fastapi.staticfiles import StaticFiles\nimport uuid\n\nfrom sources.llm_provider import Provider\nfrom sources.interaction import Interaction\nfrom sources.agents import CasualAgent, CoderAgent, FileAgent, PlannerAgent, BrowserAgent\nfrom sources.browser import Browser, create_driver\nfrom sources.utility import pretty_print\nfrom sources.logger import Logger\nfrom sources.schemas import QueryRequest, QueryResponse\n\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\n\ndef is_running_in_docker():\n \"\"\"Detect if code is running inside a Docker container.\"\"\"\n # Method 1: Check for .dockerenv file\n if os.path.exists('/.dockerenv'):\n return True\n \n # Method 2: Check cgroup\n try:\n with open('/proc/1/cgroup', 'r') as f:\n return 'docker' in f.read()\n except:\n pass\n \n return False\n\n\nfrom celery import Celery\n\napi = FastAPI(title=\"AgenticSeek API\", version=\"0.1.0\")\ncelery_app = Celery(\"tasks\", broker=\"redis://localhost:6379/0\", backend=\"redis://localhost:6379/0\")\ncelery_app.conf.update(task_track_started=True)\nlogger = Logger(\"backend.log\")\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\napi.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"],\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\nif not os.path.exists(\".screenshots\"):\n os.makedirs(\".screenshots\")\napi.mount(\"/screenshots\", StaticFiles(directory=\".screenshots\"), name=\"screenshots\")\n\ndef initialize_system():\n stealth_mode = config.getboolean('BROWSER', 'stealth_mode')\n personality_folder = \"jarvis\" if config.getboolean('MAIN', 'jarvis_personality') else \"base\"\n languages = config[\"MAIN\"][\"languages\"].split(' ')\n \n # Force headless mode in Docker containers\n headless = config.getboolean('BROWSER', 'headless_browser')\n if is_running_in_docker() and not headless:\n # Print prominent warning to console (visible in docker-compose output)\n print(\"\\n\" + \"*\" * 70)\n print(\"*** WARNING: Detected Docker environment - forcing headless_browser=True ***\")\n print(\"*** INFO: To see the browser, run 'python cli.py' on your host machine ***\")\n print(\"*\" * 70 + \"\\n\")\n \n # Flush to ensure it's displayed immediately\n sys.stdout.flush()\n \n # Also log to file\n logger.warning(\"Detected Docker environment - forcing headless_browser=True\")\n logger.info(\"To see the browser, run 'python cli.py' on your host machine instead\")\n \n headless = True\n \n provider = Provider(\n provider_name=config[\"MAIN\"][\"provider_name\"],\n model=config[\"MAIN\"][\"provider_model\"],\n server_address=config[\"MAIN\"][\"provider_server_address\"],\n is_local=config.getboolean('MAIN', 'is_local')\n )\n logger.info(f\"Provider initialized: {provider.provider_name} ({provider.model})\")\n\n browser = Browser(\n create_driver(headless=headless, stealth_mode=stealth_mode, lang=languages[0]),\n anticaptcha_manual_install=stealth_mode\n )\n logger.info(\"Browser initialized\")\n\n agents = [\n CasualAgent(\n name=config[\"MAIN\"][\"agent_name\"],\n prompt_path=f\"prompts/{personality_folder}/casual_agent.txt\",\n provider=provider, verbose=False\n ),\n CoderAgent(\n name=\"coder\",\n prompt_path=f\"prompts/{personality_folder}/coder_agent.txt\",\n provider=provider, verbose=False\n ),\n FileAgent(\n name=\"File Agent\",\n prompt_path=f\"prompts/{personality_folder}/file_agent.txt\",\n provider=provider, verbose=False\n ),\n BrowserAgent(\n name=\"Browser\",\n prompt_path=f\"prompts/{personality_folder}/browser_agent.txt\",\n provider=provider, verbose=False, browser=browser\n ),\n PlannerAgent(\n name=\"Planner\",\n prompt_path=f\"prompts/{personality_folder}/planner_agent.txt\",\n provider=provider, verbose=False, browser=browser\n )\n ]\n logger.info(\"Agents initialized\")\n\n interaction = Interaction(\n agents,\n tts_enabled=config.getboolean('MAIN', 'speak'),\n stt_enabled=config.getboolean('MAIN', 'listen'),\n recover_last_session=config.getboolean('MAIN', 'recover_last_session'),\n langs=languages\n )\n logger.info(\"Interaction initialized\")\n return interaction\n\ninteraction = initialize_system()\nis_generating = False\nquery_resp_history = []\n\n@api.get(\"/screenshot\")\nasync def get_screenshot():\n logger.info(\"Screenshot endpoint called\")\n screenshot_path = \".screenshots/updated_screen.png\"\n if os.path.exists(screenshot_path):\n return FileResponse(screenshot_path)\n logger.error(\"No screenshot available\")\n return JSONResponse(\n status_code=404,\n content={\"error\": \"No screenshot available\"}\n )\n\n@api.get(\"/health\")\nasync def health_check():\n logger.info(\"Health check endpoint called\")\n return {\"status\": \"healthy\", \"version\": \"0.1.0\"}\n\n@api.get(\"/is_active\")\nasync def is_active():\n logger.info(\"Is active endpoint called\")\n return {\"is_active\": interaction.is_active}\n\n@api.get(\"/stop\")\nasync def stop():\n logger.info(\"Stop endpoint called\")\n interaction.current_agent.request_stop()\n return JSONResponse(status_code=200, content={\"status\": \"stopped\"})\n\n@api.get(\"/latest_answer\")\nasync def get_latest_answer():\n global query_resp_history\n if interaction.current_agent is None:\n return JSONResponse(status_code=404, content={\"error\": \"No agent available\"})\n uid = str(uuid.uuid4())\n if not any(q[\"answer\"] == interaction.current_agent.last_answer for q in query_resp_history):\n query_resp = {\n \"done\": \"false\",\n \"answer\": interaction.current_agent.last_answer,\n \"reasoning\": interaction.current_agent.last_reasoning,\n \"agent_name\": interaction.current_agent.agent_name if interaction.current_agent else \"None\",\n \"success\": interaction.current_agent.success,\n \"blocks\": {f'{i}': block.jsonify() for i, block in enumerate(interaction.get_last_blocks_result())} if interaction.current_agent else {},\n \"status\": interaction.current_agent.get_status_message if interaction.current_agent else \"No status available\",\n \"uid\": uid\n }\n interaction.current_agent.last_answer = \"\"\n interaction.current_agent.last_reasoning = \"\"\n query_resp_history.append(query_resp)\n return JSONResponse(status_code=200, content=query_resp)\n if query_resp_history:\n return JSONResponse(status_code=200, content=query_resp_history[-1])\n return JSONResponse(status_code=404, content={\"error\": \"No answer available\"})\n\nasync def think_wrapper(interaction, query):\n try:\n interaction.last_query = query\n logger.info(\"Agents request is being processed\")\n success = await interaction.think()\n if not success:\n interaction.last_answer = \"Error: No answer from agent\"\n interaction.last_reasoning = \"Error: No reasoning from agent\"\n interaction.last_success = False\n else:\n interaction.last_success = True\n pretty_print(interaction.last_answer)\n interaction.speak_answer()\n return success\n except Exception as e:\n logger.error(f\"Error in think_wrapper: {str(e)}\")\n interaction.last_answer = f\"\"\n interaction.last_reasoning = f\"Error: {str(e)}\"\n interaction.last_success = False\n raise e\n\n@api.post(\"/query\", response_model=QueryResponse)\nasync def process_query(request: QueryRequest):\n global is_generating, query_resp_history\n logger.info(f\"Processing query: {request.query}\")\n query_resp = QueryResponse(\n done=\"false\",\n answer=\"\",\n reasoning=\"\",\n agent_name=\"Unknown\",\n success=\"false\",\n blocks={},\n status=\"Ready\",\n uid=str(uuid.uuid4())\n )\n if is_generating:\n logger.warning(\"Another query is being processed, please wait.\")\n return JSONResponse(status_code=429, content=query_resp.jsonify())\n\n try:\n is_generating = True\n success = await think_wrapper(interaction, request.query)\n is_generating = False\n\n if not success:\n query_resp.answer = interaction.last_answer\n query_resp.reasoning = interaction.last_reasoning\n return JSONResponse(status_code=400, content=query_resp.jsonify())\n\n if interaction.current_agent:\n blocks_json = {f'{i}': block.jsonify() for i, block in enumerate(interaction.current_agent.get_blocks_result())}\n else:\n logger.error(\"No current agent found\")\n blocks_json = {}\n query_resp.answer = \"Error: No current agent\"\n return JSONResponse(status_code=400, content=query_resp.jsonify())\n\n logger.info(f\"Answer: {interaction.last_answer}\")\n logger.info(f\"Blocks: {blocks_json}\")\n query_resp.done = \"true\"\n query_resp.answer = interaction.last_answer\n query_resp.reasoning = interaction.last_reasoning\n query_resp.agent_name = interaction.current_agent.agent_name\n query_resp.success = str(interaction.last_success)\n query_resp.blocks = blocks_json\n \n query_resp_dict = {\n \"done\": query_resp.done,\n \"answer\": query_resp.answer,\n \"agent_name\": query_resp.agent_name,\n \"success\": query_resp.success,\n \"blocks\": query_resp.blocks,\n \"status\": query_resp.status,\n \"uid\": query_resp.uid\n }\n query_resp_history.append(query_resp_dict)\n\n logger.info(\"Query processed successfully\")\n return JSONResponse(status_code=200, content=query_resp.jsonify())\n except Exception as e:\n logger.error(f\"An error occurred: {str(e)}\")\n sys.exit(1)\n finally:\n logger.info(\"Processing finished\")\n if config.getboolean('MAIN', 'save_session'):\n interaction.save_session()\n\nif __name__ == \"__main__\":\n # Print startup info\n if is_running_in_docker():\n print(\"[AgenticSeek] Starting in Docker container...\")\n else:\n print(\"[AgenticSeek] Starting on host machine...\")\n \n envport = os.getenv(\"BACKEND_PORT\")\n if envport:\n port = int(envport)\n else:\n port = 7777\n uvicorn.run(api, host=\"0.0.0.0\", port=7777)"], ["/agenticSeek/cli.py", "#!/usr/bin python3\n\nimport sys\nimport argparse\nimport configparser\nimport asyncio\n\nfrom sources.llm_provider import Provider\nfrom sources.interaction import Interaction\nfrom sources.agents import Agent, CoderAgent, CasualAgent, FileAgent, PlannerAgent, BrowserAgent, McpAgent\nfrom sources.browser import Browser, create_driver\nfrom sources.utility import pretty_print\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\nasync def main():\n pretty_print(\"Initializing...\", color=\"status\")\n stealth_mode = config.getboolean('BROWSER', 'stealth_mode')\n personality_folder = \"jarvis\" if config.getboolean('MAIN', 'jarvis_personality') else \"base\"\n languages = config[\"MAIN\"][\"languages\"].split(' ')\n\n provider = Provider(provider_name=config[\"MAIN\"][\"provider_name\"],\n model=config[\"MAIN\"][\"provider_model\"],\n server_address=config[\"MAIN\"][\"provider_server_address\"],\n is_local=config.getboolean('MAIN', 'is_local'))\n\n browser = Browser(\n create_driver(headless=config.getboolean('BROWSER', 'headless_browser'), stealth_mode=stealth_mode, lang=languages[0]),\n anticaptcha_manual_install=stealth_mode\n )\n\n agents = [\n CasualAgent(name=config[\"MAIN\"][\"agent_name\"],\n prompt_path=f\"prompts/{personality_folder}/casual_agent.txt\",\n provider=provider, verbose=False),\n CoderAgent(name=\"coder\",\n prompt_path=f\"prompts/{personality_folder}/coder_agent.txt\",\n provider=provider, verbose=False),\n FileAgent(name=\"File Agent\",\n prompt_path=f\"prompts/{personality_folder}/file_agent.txt\",\n provider=provider, verbose=False),\n BrowserAgent(name=\"Browser\",\n prompt_path=f\"prompts/{personality_folder}/browser_agent.txt\",\n provider=provider, verbose=False, browser=browser),\n PlannerAgent(name=\"Planner\",\n prompt_path=f\"prompts/{personality_folder}/planner_agent.txt\",\n provider=provider, verbose=False, browser=browser),\n #McpAgent(name=\"MCP Agent\",\n # prompt_path=f\"prompts/{personality_folder}/mcp_agent.txt\",\n # provider=provider, verbose=False), # NOTE under development\n ]\n\n interaction = Interaction(agents,\n tts_enabled=config.getboolean('MAIN', 'speak'),\n stt_enabled=config.getboolean('MAIN', 'listen'),\n recover_last_session=config.getboolean('MAIN', 'recover_last_session'),\n langs=languages\n )\n try:\n while interaction.is_active:\n interaction.get_user()\n if await interaction.think():\n interaction.show_answer()\n interaction.speak_answer()\n except Exception as e:\n if config.getboolean('MAIN', 'save_session'):\n interaction.save_session()\n raise e\n finally:\n if config.getboolean('MAIN', 'save_session'):\n interaction.save_session()\n\nif __name__ == \"__main__\":\n asyncio.run(main())"], ["/agenticSeek/sources/interaction.py", "import readline\nfrom typing import List, Tuple, Type, Dict\n\nfrom sources.text_to_speech import Speech\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.router import AgentRouter\nfrom sources.speech_to_text import AudioTranscriber, AudioRecorder\nimport threading\n\n\nclass Interaction:\n \"\"\"\n Interaction is a class that handles the interaction between the user and the agents.\n \"\"\"\n def __init__(self, agents,\n tts_enabled: bool = True,\n stt_enabled: bool = True,\n recover_last_session: bool = False,\n langs: List[str] = [\"en\", \"zh\"]\n ):\n self.is_active = True\n self.current_agent = None\n self.last_query = None\n self.last_answer = None\n self.last_reasoning = None\n self.agents = agents\n self.tts_enabled = tts_enabled\n self.stt_enabled = stt_enabled\n self.recover_last_session = recover_last_session\n self.router = AgentRouter(self.agents, supported_language=langs)\n self.ai_name = self.find_ai_name()\n self.speech = None\n self.transcriber = None\n self.recorder = None\n self.is_generating = False\n self.languages = langs\n if tts_enabled:\n self.initialize_tts()\n if stt_enabled:\n self.initialize_stt()\n if recover_last_session:\n self.load_last_session()\n self.emit_status()\n \n def get_spoken_language(self) -> str:\n \"\"\"Get the primary TTS language.\"\"\"\n lang = self.languages[0]\n return lang\n\n def initialize_tts(self):\n \"\"\"Initialize TTS.\"\"\"\n if not self.speech:\n animate_thinking(\"Initializing text-to-speech...\", color=\"status\")\n self.speech = Speech(enable=self.tts_enabled, language=self.get_spoken_language(), voice_idx=1)\n\n def initialize_stt(self):\n \"\"\"Initialize STT.\"\"\"\n if not self.transcriber or not self.recorder:\n animate_thinking(\"Initializing speech recognition...\", color=\"status\")\n self.transcriber = AudioTranscriber(self.ai_name, verbose=False)\n self.recorder = AudioRecorder()\n \n def emit_status(self):\n \"\"\"Print the current status of agenticSeek.\"\"\"\n if self.stt_enabled:\n pretty_print(f\"Text-to-speech trigger is {self.ai_name}\", color=\"status\")\n if self.tts_enabled:\n self.speech.speak(\"Hello, we are online and ready. What can I do for you ?\")\n pretty_print(\"AgenticSeek is ready.\", color=\"status\")\n \n def find_ai_name(self) -> str:\n \"\"\"Find the name of the default AI. It is required for STT as a trigger word.\"\"\"\n ai_name = \"jarvis\"\n for agent in self.agents:\n if agent.type == \"casual_agent\":\n ai_name = agent.agent_name\n break\n return ai_name\n \n def get_last_blocks_result(self) -> List[Dict]:\n \"\"\"Get the last blocks result.\"\"\"\n if self.current_agent is None:\n return []\n blks = []\n for agent in self.agents:\n blks.extend(agent.get_blocks_result())\n return blks\n \n def load_last_session(self):\n \"\"\"Recover the last session.\"\"\"\n for agent in self.agents:\n if agent.type == \"planner_agent\":\n continue\n agent.memory.load_memory(agent.type)\n \n def save_session(self):\n \"\"\"Save the current session.\"\"\"\n for agent in self.agents:\n agent.memory.save_memory(agent.type)\n\n def is_active(self) -> bool:\n return self.is_active\n \n def read_stdin(self) -> str:\n \"\"\"Read the input from the user.\"\"\"\n buffer = \"\"\n\n PROMPT = \"\\033[1;35m➤➤➤ \\033[0m\"\n while not buffer:\n try:\n buffer = input(PROMPT)\n except EOFError:\n return None\n if buffer == \"exit\" or buffer == \"goodbye\":\n return None\n return buffer\n \n def transcription_job(self) -> str:\n \"\"\"Transcribe the audio from the microphone.\"\"\"\n self.recorder = AudioRecorder(verbose=True)\n self.transcriber = AudioTranscriber(self.ai_name, verbose=True)\n self.transcriber.start()\n self.recorder.start()\n self.recorder.join()\n self.transcriber.join()\n query = self.transcriber.get_transcript()\n if query == \"exit\" or query == \"goodbye\":\n return None\n return query\n\n def get_user(self) -> str:\n \"\"\"Get the user input from the microphone or the keyboard.\"\"\"\n if self.stt_enabled:\n query = \"TTS transcription of user: \" + self.transcription_job()\n else:\n query = self.read_stdin()\n if query is None:\n self.is_active = False\n self.last_query = None\n return None\n self.last_query = query\n return query\n \n def set_query(self, query: str) -> None:\n \"\"\"Set the query\"\"\"\n self.is_active = True\n self.last_query = query\n \n async def think(self) -> bool:\n \"\"\"Request AI agents to process the user input.\"\"\"\n push_last_agent_memory = False\n if self.last_query is None or len(self.last_query) == 0:\n return False\n agent = self.router.select_agent(self.last_query)\n if agent is None:\n return False\n if self.current_agent != agent and self.last_answer is not None:\n push_last_agent_memory = True\n tmp = self.last_answer\n self.current_agent = agent\n self.is_generating = True\n self.last_answer, self.last_reasoning = await agent.process(self.last_query, self.speech)\n self.is_generating = False\n if push_last_agent_memory:\n self.current_agent.memory.push('user', self.last_query)\n self.current_agent.memory.push('assistant', self.last_answer)\n if self.last_answer == tmp:\n self.last_answer = None\n return True\n \n def get_updated_process_answer(self) -> str:\n \"\"\"Get the answer from the last agent.\"\"\"\n if self.current_agent is None:\n return None\n return self.current_agent.get_last_answer()\n \n def get_updated_block_answer(self) -> str:\n \"\"\"Get the answer from the last agent.\"\"\"\n if self.current_agent is None:\n return None\n return self.current_agent.get_last_block_answer()\n \n def speak_answer(self) -> None:\n \"\"\"Speak the answer to the user in a non-blocking thread.\"\"\"\n if self.last_query is None:\n return\n if self.tts_enabled and self.last_answer and self.speech:\n def speak_in_thread(speech_instance, text):\n speech_instance.speak(text)\n thread = threading.Thread(target=speak_in_thread, args=(self.speech, self.last_answer))\n thread.start()\n \n def show_answer(self) -> None:\n \"\"\"Show the answer to the user.\"\"\"\n if self.last_query is None:\n return\n if self.current_agent is not None:\n self.current_agent.show_answer()\n\n"], ["/agenticSeek/sources/memory.py", "import time\nimport datetime\nimport uuid\nimport os\nimport sys\nimport json\nfrom typing import List, Tuple, Type, Dict\nimport torch\nfrom transformers import AutoTokenizer, AutoModelForSeq2SeqLM\nimport configparser\n\nfrom sources.utility import timer_decorator, pretty_print, animate_thinking\nfrom sources.logger import Logger\n\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\nclass Memory():\n \"\"\"\n Memory is a class for managing the conversation memory\n It provides a method to compress the memory using summarization model.\n \"\"\"\n def __init__(self, system_prompt: str,\n recover_last_session: bool = False,\n memory_compression: bool = True,\n model_provider: str = \"deepseek-r1:14b\"):\n self.memory = [{'role': 'system', 'content': system_prompt}]\n \n self.logger = Logger(\"memory.log\")\n self.session_time = datetime.datetime.now()\n self.session_id = str(uuid.uuid4())\n self.conversation_folder = f\"conversations/\"\n self.session_recovered = False\n if recover_last_session:\n self.load_memory()\n self.session_recovered = True\n # memory compression system\n self.model = None\n self.tokenizer = None\n self.device = self.get_cuda_device()\n self.memory_compression = memory_compression\n self.model_provider = model_provider\n if self.memory_compression:\n self.download_model()\n\n def get_ideal_ctx(self, model_name: str) -> int | None:\n \"\"\"\n Estimate context size based on the model name.\n EXPERIMENTAL for memory compression\n \"\"\"\n import re\n import math\n\n def extract_number_before_b(sentence: str) -> int:\n match = re.search(r'(\\d+)b', sentence, re.IGNORECASE)\n return int(match.group(1)) if match else None\n\n model_size = extract_number_before_b(model_name)\n if not model_size:\n return None\n base_size = 7 # Base model size in billions\n base_context = 4096 # Base context size in tokens\n scaling_factor = 1.5 # Approximate scaling factor for context size growth\n context_size = int(base_context * (model_size / base_size) ** scaling_factor)\n context_size = 2 ** round(math.log2(context_size))\n self.logger.info(f\"Estimated context size for {model_name}: {context_size} tokens.\")\n return context_size\n \n def download_model(self):\n \"\"\"Download the model if not already downloaded.\"\"\"\n animate_thinking(\"Loading memory compression model...\", color=\"status\")\n self.tokenizer = AutoTokenizer.from_pretrained(\"pszemraj/led-base-book-summary\")\n self.model = AutoModelForSeq2SeqLM.from_pretrained(\"pszemraj/led-base-book-summary\")\n self.logger.info(\"Memory compression system initialized.\")\n \n def get_filename(self) -> str:\n \"\"\"Get the filename for the save file.\"\"\"\n return f\"memory_{self.session_time.strftime('%Y-%m-%d_%H-%M-%S')}.txt\"\n \n def save_memory(self, agent_type: str = \"casual_agent\") -> None:\n \"\"\"Save the session memory to a file.\"\"\"\n if not os.path.exists(self.conversation_folder):\n self.logger.info(f\"Created folder {self.conversation_folder}.\")\n os.makedirs(self.conversation_folder)\n save_path = os.path.join(self.conversation_folder, agent_type)\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n filename = self.get_filename()\n path = os.path.join(save_path, filename)\n json_memory = json.dumps(self.memory)\n with open(path, 'w') as f:\n self.logger.info(f\"Saved memory json at {path}\")\n f.write(json_memory)\n \n def find_last_session_path(self, path) -> str:\n \"\"\"Find the last session path.\"\"\"\n saved_sessions = []\n for filename in os.listdir(path):\n if filename.startswith('memory_'):\n date = filename.split('_')[1]\n saved_sessions.append((filename, date))\n saved_sessions.sort(key=lambda x: x[1], reverse=True)\n if len(saved_sessions) > 0:\n self.logger.info(f\"Last session found at {saved_sessions[0][0]}\")\n return saved_sessions[0][0]\n return None\n \n def save_json_file(self, path: str, json_memory: dict) -> None:\n \"\"\"Save a JSON file.\"\"\"\n try:\n with open(path, 'w') as f:\n json.dump(json_memory, f)\n self.logger.info(f\"Saved memory json at {path}\")\n except Exception as e:\n self.logger.warning(f\"Error saving file {path}: {e}\")\n \n def load_json_file(self, path: str) -> dict:\n \"\"\"Load a JSON file.\"\"\"\n json_memory = {}\n try:\n with open(path, 'r') as f:\n json_memory = json.load(f)\n except FileNotFoundError:\n self.logger.warning(f\"File not found: {path}\")\n return {}\n except json.JSONDecodeError:\n self.logger.warning(f\"Error decoding JSON from file: {path}\")\n return {}\n except Exception as e:\n self.logger.warning(f\"Error loading file {path}: {e}\")\n return {}\n return json_memory\n\n def load_memory(self, agent_type: str = \"casual_agent\") -> None:\n \"\"\"Load the memory from the last session.\"\"\"\n if self.session_recovered == True:\n return\n pretty_print(f\"Loading {agent_type} past memories... \", color=\"status\")\n save_path = os.path.join(self.conversation_folder, agent_type)\n if not os.path.exists(save_path):\n pretty_print(\"No memory to load.\", color=\"success\")\n return\n filename = self.find_last_session_path(save_path)\n if filename is None:\n pretty_print(\"Last session memory not found.\", color=\"warning\")\n return\n path = os.path.join(save_path, filename)\n self.memory = self.load_json_file(path) \n if self.memory[-1]['role'] == 'user':\n self.memory.pop()\n self.compress()\n pretty_print(\"Session recovered successfully\", color=\"success\")\n \n def reset(self, memory: list = []) -> None:\n self.logger.info(\"Memory reset performed.\")\n self.memory = memory\n \n def push(self, role: str, content: str) -> int:\n \"\"\"Push a message to the memory.\"\"\"\n ideal_ctx = self.get_ideal_ctx(self.model_provider)\n if ideal_ctx is not None:\n if self.memory_compression and len(content) > ideal_ctx * 1.5:\n self.logger.info(f\"Compressing memory: Content {len(content)} > {ideal_ctx} model context.\")\n self.compress()\n curr_idx = len(self.memory)\n if self.memory[curr_idx-1]['content'] == content:\n pretty_print(\"Warning: same message have been pushed twice to memory\", color=\"error\")\n time_str = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n if config[\"MAIN\"][\"provider_name\"] == \"openrouter\":\n self.memory.append({'role': role, 'content': content})\n else:\n self.memory.append({'role': role, 'content': content, 'time': time_str, 'model_used': self.model_provider})\n return curr_idx-1\n \n def clear(self) -> None:\n \"\"\"Clear all memory except system prompt\"\"\"\n self.logger.info(\"Memory clear performed.\")\n self.memory = self.memory[:1]\n \n def clear_section(self, start: int, end: int) -> None:\n \"\"\"\n Clear a section of the memory. Ignore system message index.\n Args:\n start (int): Starting bound of the section to clear.\n end (int): Ending bound of the section to clear.\n \"\"\"\n self.logger.info(f\"Clearing memory section {start} to {end}.\")\n start = max(0, start) + 1\n end = min(end, len(self.memory)-1) + 2\n self.memory = self.memory[:start] + self.memory[end:]\n \n def get(self) -> list:\n return self.memory\n\n def get_cuda_device(self) -> str:\n if torch.backends.mps.is_available():\n return \"mps\"\n elif torch.cuda.is_available():\n return \"cuda\"\n else:\n return \"cpu\"\n\n def summarize(self, text: str, min_length: int = 64) -> str:\n \"\"\"\n Summarize the text using the AI model.\n Args:\n text (str): The text to summarize\n min_length (int, optional): The minimum length of the summary. Defaults to 64.\n Returns:\n str: The summarized text\n \"\"\"\n if self.tokenizer is None or self.model is None:\n self.logger.warning(\"No tokenizer or model to perform summarization.\")\n return text\n if len(text) < min_length*1.5:\n return text\n max_length = len(text) // 2 if len(text) > min_length*2 else min_length*2\n input_text = \"summarize: \" + text\n inputs = self.tokenizer(input_text, return_tensors=\"pt\", max_length=512, truncation=True)\n summary_ids = self.model.generate(\n inputs['input_ids'],\n max_length=max_length,\n min_length=min_length,\n length_penalty=1.0,\n num_beams=4,\n early_stopping=True\n )\n summary = self.tokenizer.decode(summary_ids[0], skip_special_tokens=True)\n summary.replace('summary:', '')\n self.logger.info(f\"Memory summarized from len {len(text)} to {len(summary)}.\")\n self.logger.info(f\"Summarized text:\\n{summary}\")\n return summary\n \n #@timer_decorator\n def compress(self) -> str:\n \"\"\"\n Compress (summarize) the memory using the model.\n \"\"\"\n if self.tokenizer is None or self.model is None:\n self.logger.warning(\"No tokenizer or model to perform memory compression.\")\n return\n for i in range(len(self.memory)):\n if self.memory[i]['role'] == 'system':\n continue\n if len(self.memory[i]['content']) > 1024:\n self.memory[i]['content'] = self.summarize(self.memory[i]['content'])\n \n def trim_text_to_max_ctx(self, text: str) -> str:\n \"\"\"\n Truncate a text to fit within the maximum context size of the model.\n \"\"\"\n ideal_ctx = self.get_ideal_ctx(self.model_provider)\n return text[:ideal_ctx] if ideal_ctx is not None else text\n \n #@timer_decorator\n def compress_text_to_max_ctx(self, text) -> str:\n \"\"\"\n Compress a text to fit within the maximum context size of the model.\n \"\"\"\n if self.tokenizer is None or self.model is None:\n self.logger.warning(\"No tokenizer or model to perform memory compression.\")\n return text\n ideal_ctx = self.get_ideal_ctx(self.model_provider)\n if ideal_ctx is None:\n self.logger.warning(\"No ideal context size found.\")\n return text\n while len(text) > ideal_ctx:\n self.logger.info(f\"Compressing text: {len(text)} > {ideal_ctx} model context.\")\n text = self.summarize(text)\n return text\n\nif __name__ == \"__main__\":\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n memory = Memory(\"You are a helpful assistant.\",\n recover_last_session=False, memory_compression=True)\n\n memory.push('user', \"hello\")\n memory.push('assistant', \"how can i help you?\")\n memory.push('user', \"why do i get this cuda error?\")\n sample_text = \"\"\"\nThe error you're encountering:\ncuda.cu:52:10: fatal error: helper_functions.h: No such file or directory\n #include \nindicates that the compiler cannot find the helper_functions.h file. This is because the #include directive is looking for the file in the system's include paths, but the file is either not in those paths or is located in a different directory.\n1. Use #include \"helper_functions.h\" Instead of #include \nAngle brackets (< >) are used for system or standard library headers.\nQuotes (\" \") are used for local or project-specific headers.\nIf helper_functions.h is in the same directory as cuda.cu, change the include directive to:\n3. Verify the File Exists\nDouble-check that helper_functions.h exists in the specified location. If the file is missing, you'll need to obtain or recreate it.\n4. Use the Correct CUDA Samples Path (if applicable)\nIf helper_functions.h is part of the CUDA Samples, ensure you have the CUDA Samples installed and include the correct path. For example, on Linux, the CUDA Samples are typically located in /usr/local/cuda/samples/common/inc. You can include this path like so:\nUse #include \"helper_functions.h\" for local files.\nUse the -I flag to specify the directory containing helper_functions.h.\nEnsure the file exists in the specified location.\n \"\"\"\n memory.push('assistant', sample_text)\n \n print(\"\\n---\\nmemory before:\", memory.get())\n memory.compress()\n print(\"\\n---\\nmemory after:\", memory.get())\n #memory.save_memory()\n "], ["/agenticSeek/sources/router.py", "import os\nimport sys\nimport torch\nimport random\nfrom typing import List, Tuple, Type, Dict\n\nfrom transformers import pipeline\nfrom adaptive_classifier import AdaptiveClassifier\n\nfrom sources.agents.agent import Agent\nfrom sources.agents.code_agent import CoderAgent\nfrom sources.agents.casual_agent import CasualAgent\nfrom sources.agents.planner_agent import FileAgent\nfrom sources.agents.browser_agent import BrowserAgent\nfrom sources.language import LanguageUtility\nfrom sources.utility import pretty_print, animate_thinking, timer_decorator\nfrom sources.logger import Logger\n\nclass AgentRouter:\n \"\"\"\n AgentRouter is a class that selects the appropriate agent based on the user query.\n \"\"\"\n def __init__(self, agents: list, supported_language: List[str] = [\"en\", \"fr\", \"zh\"]):\n self.agents = agents\n self.logger = Logger(\"router.log\")\n self.lang_analysis = LanguageUtility(supported_language=supported_language)\n self.pipelines = self.load_pipelines()\n self.talk_classifier = self.load_llm_router()\n self.complexity_classifier = self.load_llm_router()\n self.learn_few_shots_tasks()\n self.learn_few_shots_complexity()\n self.asked_clarify = False\n \n def load_pipelines(self) -> Dict[str, Type[pipeline]]:\n \"\"\"\n Load the pipelines for the text classification used for routing.\n returns:\n Dict[str, Type[pipeline]]: The loaded pipelines\n \"\"\"\n animate_thinking(\"Loading zero-shot pipeline...\", color=\"status\")\n return {\n \"bart\": pipeline(\"zero-shot-classification\", model=\"facebook/bart-large-mnli\")\n }\n\n def load_llm_router(self) -> AdaptiveClassifier:\n \"\"\"\n Load the LLM router model.\n returns:\n AdaptiveClassifier: The loaded model\n exceptions:\n Exception: If the safetensors fails to load\n \"\"\"\n path = \"../llm_router\" if __name__ == \"__main__\" else \"./llm_router\"\n try:\n animate_thinking(\"Loading LLM router model...\", color=\"status\")\n talk_classifier = AdaptiveClassifier.from_pretrained(path)\n except Exception as e:\n raise Exception(\"Failed to load the routing model. Please run the dl_safetensors.sh script inside llm_router/ directory to download the model.\")\n return talk_classifier\n\n def get_device(self) -> str:\n if torch.backends.mps.is_available():\n return \"mps\"\n elif torch.cuda.is_available():\n return \"cuda:0\"\n else:\n return \"cpu\"\n \n def learn_few_shots_complexity(self) -> None:\n \"\"\"\n Few shot learning for complexity estimation.\n Use the build in add_examples method of the Adaptive_classifier.\n \"\"\"\n few_shots = [\n (\"hi\", \"LOW\"),\n (\"How it's going ?\", \"LOW\"),\n (\"What’s the weather like today?\", \"LOW\"),\n (\"Can you find a file named ‘notes.txt’ in my Documents folder?\", \"LOW\"),\n (\"Write a Python script to generate a random password\", \"LOW\"),\n (\"Debug this JavaScript code that’s not running properly\", \"LOW\"),\n (\"Search the web for the cheapest laptop under $500\", \"LOW\"),\n (\"Locate a file called ‘report_2024.pdf’ on my drive\", \"LOW\"),\n (\"Check if a folder named ‘Backups’ exists on my system\", \"LOW\"),\n (\"Can you find ‘family_vacation.mp4’ in my Videos folder?\", \"LOW\"),\n (\"Search my drive for a file named ‘todo_list.xlsx’\", \"LOW\"),\n (\"Write a Python function to check if a string is a palindrome\", \"LOW\"),\n (\"Can you search the web for startups in Berlin?\", \"LOW\"),\n (\"Find recent articles on blockchain technology online\", \"LOW\"),\n (\"Check if ‘Personal_Projects’ folder exists on my desktop\", \"LOW\"),\n (\"Create a bash script to list all running processes\", \"LOW\"),\n (\"Debug this Python script that’s crashing on line 10\", \"LOW\"),\n (\"Browse the web to find out who invented Python\", \"LOW\"),\n (\"Locate a file named ‘shopping_list.txt’ on my system\", \"LOW\"),\n (\"Search the web for tips on staying productive\", \"LOW\"),\n (\"Find ‘sales_pitch.pptx’ in my Downloads folder\", \"LOW\"),\n (\"can you find a file called resume.docx on my drive?\", \"LOW\"),\n (\"can you write a python script to check if the device on my network is connected to the internet\", \"LOW\"),\n (\"can you debug this Java code? It’s not working.\", \"LOW\"),\n (\"can you find the old_project.zip file somewhere on my drive?\", \"LOW\"),\n (\"can you locate the backup folder I created last month on my system?\", \"LOW\"),\n (\"could you check if the presentation.pdf file exists in my downloads?\", \"LOW\"),\n (\"search my drive for a file called vacation_photos_2023.jpg.\", \"LOW\"),\n (\"help me organize my desktop files into folders by type.\", \"LOW\"),\n (\"make a blackjack in golang\", \"LOW\"),\n (\"write a python script to ping a website\", \"LOW\"),\n (\"write a simple Java program to print 'Hello World'\", \"LOW\"),\n (\"write a Java program to calculate the area of a circle\", \"LOW\"),\n (\"write a Python function to sort a list of dictionaries by key\", \"LOW\"),\n (\"can you search for startup in tokyo?\", \"LOW\"),\n (\"find the latest updates on quantum computing on the web\", \"LOW\"),\n (\"check if the folder ‘Work_Projects’ exists on my desktop\", \"LOW\"),\n (\" can you browse the web, use overpass-turbo to show fountains in toulouse\", \"LOW\"),\n (\"search the web for the best budget smartphones of 2025\", \"LOW\"),\n (\"write a Python script to download all images from a webpage\", \"LOW\"),\n (\"create a bash script to monitor CPU usage\", \"LOW\"),\n (\"debug this C++ code that keeps crashing\", \"LOW\"),\n (\"can you browse the web to find out who fosowl is ?\", \"LOW\"),\n (\"find the file ‘important_notes.txt’\", \"LOW\"),\n (\"search the web for the best ways to learn a new language\", \"LOW\"),\n (\"locate the file ‘presentation.pptx’ in my Documents folder\", \"LOW\"),\n (\"Make a 3d game in javascript using three.js\", \"LOW\"),\n (\"Find the latest research papers on AI and build save in a file\", \"HIGH\"),\n (\"Make a web server in go that serve a simple html page\", \"LOW\"),\n (\"Search the web for the cheapest 4K monitor and provide a link\", \"LOW\"),\n (\"Write a JavaScript function to reverse a string\", \"LOW\"),\n (\"Can you locate a file called ‘budget_2025.xlsx’ on my system?\", \"LOW\"),\n (\"Search the web for recent articles on space exploration\", \"LOW\"),\n (\"when is the exam period for master student in france?\", \"LOW\"),\n (\"Check if a folder named ‘Photos_2024’ exists on my desktop\", \"LOW\"),\n (\"Can you look up some nice knitting patterns on that web thingy?\", \"LOW\"),\n (\"Goodness, check if my ‘Photos_Grandkids’ folder is still on the desktop\", \"LOW\"),\n (\"Create a Python script to rename all files in a folder based on their creation date\", \"LOW\"),\n (\"Can you find a file named ‘meeting_notes.txt’ in my Downloads folder?\", \"LOW\"),\n (\"Write a Go program to check if a port is open on a network\", \"LOW\"),\n (\"Search the web for the latest electric car reviews\", \"LOW\"),\n (\"Write a Python function to merge two sorted lists\", \"LOW\"),\n (\"Create a bash script to monitor disk space and alert via text file\", \"LOW\"),\n (\"What’s out there on the web about cheap travel spots?\", \"LOW\"),\n (\"Search X for posts about AI ethics and summarize them\", \"LOW\"),\n (\"Check if a file named ‘project_proposal.pdf’ exists in my Documents\", \"LOW\"),\n (\"Search the web for tips on improving coding skills\", \"LOW\"),\n (\"Write a Python script to count words in a text file\", \"LOW\"),\n (\"Search the web for restaurant\", \"LOW\"),\n (\"Use a MCP to find the latest stock market data\", \"LOW\"),\n (\"Use a MCP to send an email to my boss\", \"LOW\"),\n (\"Could you use a MCP to find the latest news on climate change?\", \"LOW\"),\n (\"Create a simple HTML page with CSS styling\", \"LOW\"),\n (\"Use file.txt and then use it to ...\", \"HIGH\"),\n (\"Yo, what’s good? Find my ‘mixtape.mp3’ real quick\", \"LOW\"),\n (\"Can you follow the readme and install the project\", \"HIGH\"),\n (\"Man, write me a dope Python script to flex some random numbers\", \"LOW\"),\n (\"Search the web for peer-reviewed articles on gene editing\", \"LOW\"),\n (\"Locate ‘meeting_notes.docx’ in Downloads, I’m late for this call\", \"LOW\"),\n (\"Make the game less hard\", \"LOW\"),\n (\"Why did it fail?\", \"LOW\"),\n (\"Write a Python script to list all .pdf files in my Documents\", \"LOW\"),\n (\"Write a Python thing to sort my .jpg files by date\", \"LOW\"),\n (\"make a snake game please\", \"LOW\"),\n (\"Find ‘gallery_list.pdf’, then build a web app to show my pics\", \"HIGH\"),\n (\"Find ‘budget_2025.xlsx’, analyze it, and make a chart for my boss\", \"HIGH\"),\n (\"I want you to make me a plan to travel to Tainan\", \"HIGH\"),\n (\"Retrieve the latest publications on CRISPR and develop a web application to display them\", \"HIGH\"),\n (\"Bro dig up a music API and build me a tight app for the hottest tracks\", \"HIGH\"),\n (\"Find a public API for sports scores and build a web app to show live updates\", \"HIGH\"),\n (\"Find a public API for book data and create a Flask app to list bestsellers\", \"HIGH\"),\n (\"Organize my desktop files by extension and then write a script to list them\", \"HIGH\"),\n (\"Find the latest research on renewable energy and build a web app to display it\", \"HIGH\"),\n (\"search online for popular sci-fi movies from 2024 and pick three to watch tonight. Save the list in movie_night.txt\", \"HIGH\"),\n (\"can you find vitess repo, clone it and install by following the readme\", \"HIGH\"),\n (\"Create a JavaScript game using Phaser.js with multiple levels\", \"HIGH\"),\n (\"Search the web for the latest trends in web development and build a sample site\", \"HIGH\"),\n (\"Use my research_note.txt file, double check the informations on the web\", \"HIGH\"),\n (\"Make a web server in go that query a flight API and display them in a app\", \"HIGH\"),\n (\"Search the web for top cafes in Rennes, France, and save a list of three with their addresses in rennes_cafes.txt.\", \"HIGH\"),\n (\"Search the web for the latest trends in AI and demo it in pytorch\", \"HIGH\"),\n (\"can you lookup for api that track flight and build a web flight tracking app\", \"HIGH\"),\n (\"Find the file toto.pdf then use its content to reply to Jojo on superforum.com\", \"HIGH\"),\n (\"Create a whole web app in python using the flask framework that query news API\", \"HIGH\"),\n (\"Create a bash script that monitor the CPU usage and send an email if it's too high\", \"HIGH\"),\n (\"Make a web search for latest news on the stock market and display them with python\", \"HIGH\"),\n (\"Find my resume file, apply to job that might fit online\", \"HIGH\"),\n (\"Can you find a weather API and build a Python app to display current weather\", \"HIGH\"),\n (\"Create a Python web app using Flask to track cryptocurrency prices from an API\", \"HIGH\"),\n (\"Search the web for tutorials on machine learning and build a simple ML model in Python\", \"HIGH\"),\n (\"Find a public API for movie data and build a web app to display movie ratings\", \"HIGH\"),\n (\"Create a Node.js server that queries a public API for traffic data and displays it\", \"HIGH\"),\n (\"can you find api and build a python web app with it ?\", \"HIGH\"),\n (\"do a deep search of current AI player for 2025 and make me a report in a file\", \"HIGH\"),\n (\"Find a public API for recipe data and build a web app to display recipes\", \"HIGH\"),\n (\"Search the web for recent space mission updates and build a Flask app\", \"HIGH\"),\n (\"Create a Python script to scrape a website and save data to a database\", \"HIGH\"),\n (\"Find a shakespear txt then train a transformers on it to generate text\", \"HIGH\"),\n (\"Find a public API for fitness tracking and build a web app to show stats\", \"HIGH\"),\n (\"Search the web for tutorials on web development and build a sample site\", \"HIGH\"),\n (\"Create a Node.js app to query a public API for event listings and display them\", \"HIGH\"),\n (\"Find a file named ‘budget.xlsx’, analyze its data, and generate a chart\", \"HIGH\"),\n ]\n random.shuffle(few_shots)\n texts = [text for text, _ in few_shots]\n labels = [label for _, label in few_shots]\n self.complexity_classifier.add_examples(texts, labels)\n\n def learn_few_shots_tasks(self) -> None:\n \"\"\"\n Few shot learning for tasks classification.\n Use the build in add_examples method of the Adaptive_classifier.\n \"\"\"\n few_shots = [\n (\"Write a python script to check if the device on my network is connected to the internet\", \"coding\"),\n (\"Hey could you search the web for the latest news on the tesla stock market ?\", \"web\"),\n (\"I would like you to search for weather api\", \"web\"),\n (\"Plan a 3-day trip to New York, including flights and hotels.\", \"web\"),\n (\"Find on the web the latest research papers on AI.\", \"web\"),\n (\"Can you debug this Java code? It’s not working.\", \"code\"),\n (\"Can you browse the web and find me a 4090 for cheap?\", \"web\"),\n (\"i would like to setup a new AI project, index as mark2\", \"files\"),\n (\"Hey, can you find the old_project.zip file somewhere on my drive?\", \"files\"),\n (\"Tell me a funny story\", \"talk\"),\n (\"can you make a snake game in python\", \"code\"),\n (\"Can you locate the backup folder I created last month on my system?\", \"files\"),\n (\"Share a random fun fact about space.\", \"talk\"),\n (\"Write a script to rename all files in a directory to lowercase.\", \"files\"),\n (\"Could you check if the presentation.pdf file exists in my downloads?\", \"files\"),\n (\"Tell me about the weirdest dream you’ve ever heard of.\", \"talk\"),\n (\"Search my drive for a file called vacation_photos_2023.jpg.\", \"files\"),\n (\"Help me organize my desktop files into folders by type.\", \"files\"),\n (\"What’s your favorite movie and why?\", \"talk\"),\n (\"what directory are you in ?\", \"files\"),\n (\"what files you seing rn ?\", \"files\"),\n (\"When is the period of university exam in france ?\", \"web\"),\n (\"Search my drive for a file named budget_2024.xlsx\", \"files\"),\n (\"Write a Python function to sort a list of dictionaries by key\", \"code\"),\n (\"Find the latest updates on quantum computing on the web\", \"web\"),\n (\"Check if the folder ‘Work_Projects’ exists on my desktop\", \"files\"),\n (\"Create a bash script to monitor CPU usage\", \"code\"),\n (\"Search online for the best budget smartphones of 2025\", \"web\"),\n (\"What’s the strangest food combination you’ve heard of?\", \"talk\"),\n (\"Move all .txt files from Downloads to a new folder called Notes\", \"files\"),\n (\"Debug this C++ code that keeps crashing\", \"code\"),\n (\"can you browse the web to find out who fosowl is ?\", \"web\"),\n (\"Find the file ‘important_notes.txt’\", \"files\"),\n (\"Find out the latest news on the upcoming Mars mission\", \"web\"),\n (\"Write a Java program to calculate the area of a circle\", \"code\"),\n (\"Search the web for the best ways to learn a new language\", \"web\"),\n (\"Locate the file ‘presentation.pptx’ in my Documents folder\", \"files\"),\n (\"Write a Python script to download all images from a webpage\", \"code\"),\n (\"Search the web for the latest trends in AI and machine learning\", \"web\"),\n (\"Tell me about a time when you had to solve a difficult problem\", \"talk\"),\n (\"Organize all image files on my desktop into a folder called ‘Pictures’\", \"files\"),\n (\"Generate a Ruby script to calculate Fibonacci numbers up to 100\", \"code\"),\n (\"Find out what device are connected to my network\", \"code\"),\n (\"Show me how much disk space is left on my drive\", \"code\"),\n (\"Look up recent posts on X about climate change\", \"web\"),\n (\"Find the photo I took last week named sunset_beach.jpg\", \"files\"),\n (\"Write a JavaScript snippet to fetch data from an API\", \"code\"),\n (\"Search the web for tutorials on machine learning with Python\", \"web\"),\n (\"Locate the file ‘meeting_notes.docx’ in my Documents folder\", \"files\"),\n (\"Write a Python script to scrape a website’s title and links\", \"code\"),\n (\"Search the web for the latest breakthroughs in fusion energy\", \"web\"),\n (\"Tell me about a historical event that sounds too wild to be true\", \"talk\"),\n (\"Organize all image files on my desktop into a folder called ‘Pictures’\", \"files\"),\n (\"Generate a Ruby script to calculate Fibonacci numbers up to 100\", \"code\"),\n (\"Find recent X posts about SpaceX’s next rocket launch\", \"web\"),\n (\"What’s the funniest misunderstanding you’ve seen between humans and AI?\", \"talk\"),\n (\"Check if ‘backup_032025.zip’ exists anywhere on my drive\", \"files\" ),\n (\"Create a shell script to automate backups of a directory\", \"code\"),\n (\"Look up the top AI conferences happening in 2025 online\", \"web\"),\n (\"Write a C# program to simulate a basic calculator\", \"code\"),\n (\"Browse the web for open-source alternatives to Photoshop\", \"web\"),\n (\"Hey how are you\", \"talk\"),\n (\"Write a Python script to ping a website\", \"code\"),\n (\"Search the web for the latest iPhone release\", \"web\"),\n (\"What’s the weather like today?\", \"web\"),\n (\"Hi, how’s your day going?\", \"talk\"),\n (\"Can you find a file called resume.docx on my drive?\", \"files\"),\n (\"Write a simple Java program to print 'Hello World'\", \"code\"),\n (\"can you find the current stock of Tesla?\", \"web\"),\n (\"Tell me a quick joke\", \"talk\"),\n (\"Search online for the best coffee shops in Seattle\", \"web\"),\n (\"Check if ‘project_plan.pdf’ exists in my Downloads folder\", \"files\"),\n (\"What’s your favorite color?\", \"talk\"),\n (\"Write a bash script to list all files in a directory\", \"code\"),\n (\"Find recent X posts about electric cars\", \"web\"),\n (\"Hey, you doing okay?\", \"talk\"),\n (\"Locate the file ‘family_photo.jpg’ on my system\", \"files\"),\n (\"Search the web for beginner guitar lessons\", \"web\"),\n (\"Write a Python function to reverse a string\", \"code\"),\n (\"What’s the weirdest animal you know of?\", \"talk\"),\n (\"Organize all .pdf files on my desktop into a ‘Documents’ folder\", \"files\"),\n (\"Browse the web for the latest space mission updates\", \"web\"),\n (\"Hey, what’s up with you today?\", \"talk\"),\n (\"Write a JavaScript function to add two numbers\", \"code\"),\n (\"Find the file ‘notes.txt’ in my Documents folder\", \"files\"),\n (\"Tell me something random about the ocean\", \"talk\"),\n (\"Search the web for cheap flights to Paris\", \"web\"),\n (\"Check if ‘budget.xlsx’ is on my drive\", \"files\"),\n (\"Write a Python script to count words in a text file\", \"code\"),\n (\"How’s it going today?\", \"talk\"),\n (\"Find recent X posts about AI advancements\", \"web\"),\n (\"Move all .jpg files from Downloads to a ‘Photos’ folder\", \"files\"),\n (\"Search online for the best laptops of 2025\", \"web\"),\n (\"What’s the funniest thing you’ve heard lately?\", \"talk\"),\n (\"Write a Ruby script to generate random numbers\", \"code\"),\n (\"Hey, how’s everything with you?\", \"talk\"),\n (\"Locate ‘meeting_agenda.docx’ in my system\", \"files\"),\n (\"Search the web for tips on growing indoor plants\", \"web\"),\n (\"Write a C++ program to calculate the sum of an array\", \"code\"),\n (\"Tell me a fun fact about dogs\", \"talk\"),\n (\"Check if the folder ‘Old_Projects’ exists on my desktop\", \"files\"),\n (\"Browse the web for the latest gaming console reviews\", \"web\"),\n (\"Hi, how are you feeling today?\", \"talk\"),\n (\"Write a Python script to check disk space\", \"code\"),\n (\"Find the file ‘vacation_itinerary.pdf’ on my drive\", \"files\"),\n (\"Search the web for news on renewable energy\", \"web\"),\n (\"What’s the strangest thing you’ve learned recently?\", \"talk\"),\n (\"Organize all video files into a ‘Videos’ folder\", \"files\"),\n (\"Write a shell script to delete temporary files\", \"code\"),\n (\"Hey, how’s your week been so far?\", \"talk\"),\n (\"Search online for the top movies of 2025\", \"web\"),\n (\"Locate ‘taxes_2024.xlsx’ in my Documents folder\", \"files\"),\n (\"Tell me about a cool invention from history\", \"talk\"),\n (\"Write a Java program to check if a number is even or odd\", \"code\"),\n (\"Find recent X posts about cryptocurrency trends\", \"web\"),\n (\"Hey, you good today?\", \"talk\"),\n (\"Search the web for easy dinner recipes\", \"web\"),\n (\"Check if ‘photo_backup.zip’ exists on my drive\", \"files\"),\n (\"Write a Python script to rename files with a timestamp\", \"code\"),\n (\"What’s your favorite thing about space?\", \"talk\"),\n (\"search for GPU with at least 24gb vram\", \"web\"),\n (\"Browse the web for the latest fitness trends\", \"web\"),\n (\"Move all .docx files to a ‘Work’ folder\", \"files\"),\n (\"I would like to make a new project called 'new_project'\", \"files\"),\n (\"I would like to setup a new project index as mark2\", \"files\"),\n (\"can you create a 3d js game that run in the browser\", \"code\"),\n (\"can you make a web app in python that use the flask framework\", \"code\"),\n (\"can you build a web server in go that serve a simple html page\", \"code\"),\n (\"can you find out who Jacky yougouri is ?\", \"web\"),\n (\"Can you use MCP to find stock market for IBM ?\", \"mcp\"),\n (\"Can you use MCP to to export my contacts to a csv file?\", \"mcp\"),\n (\"Can you use a MCP to find write notes to flomo\", \"mcp\"),\n (\"Can you use a MCP to query my calendar and find the next meeting?\", \"mcp\"),\n (\"Can you use a mcp to get the distance between Shanghai and Paris?\", \"mcp\"),\n (\"Setup a new flutter project called 'new_flutter_project'\", \"files\"),\n (\"can you create a new project called 'new_project'\", \"files\"),\n (\"can you make a simple web app that display a list of files in my dir\", \"code\"),\n (\"can you build a simple web server in python that serve a html page\", \"code\"),\n (\"find and buy me the latest rtx 4090\", \"web\"),\n (\"What are some good netflix show like Altered Carbon ?\", \"web\"),\n (\"can you find the latest research paper on AI\", \"web\"),\n (\"can you find research.pdf in my drive\", \"files\"),\n (\"hi\", \"talk\"),\n (\"hello\", \"talk\"),\n ]\n random.shuffle(few_shots)\n texts = [text for text, _ in few_shots]\n labels = [label for _, label in few_shots]\n self.talk_classifier.add_examples(texts, labels)\n\n def llm_router(self, text: str) -> tuple:\n \"\"\"\n Inference of the LLM router model.\n Args:\n text: The input text\n \"\"\"\n predictions = self.talk_classifier.predict(text)\n predictions = [pred for pred in predictions if pred[0] not in [\"HIGH\", \"LOW\"]]\n predictions = sorted(predictions, key=lambda x: x[1], reverse=True)\n return predictions[0]\n \n def router_vote(self, text: str, labels: list, log_confidence:bool = False) -> str:\n \"\"\"\n Vote between the LLM router and BART model.\n Args:\n text: The input text\n labels: The labels to classify\n Returns:\n str: The selected label\n \"\"\"\n if len(text) <= 8:\n return \"talk\"\n result_bart = self.pipelines['bart'](text, labels)\n result_llm_router = self.llm_router(text)\n bart, confidence_bart = result_bart['labels'][0], result_bart['scores'][0]\n llm_router, confidence_llm_router = result_llm_router[0], result_llm_router[1]\n final_score_bart = confidence_bart / (confidence_bart + confidence_llm_router)\n final_score_llm = confidence_llm_router / (confidence_bart + confidence_llm_router)\n self.logger.info(f\"Routing Vote for text {text}: BART: {bart} ({final_score_bart}) LLM-router: {llm_router} ({final_score_llm})\")\n if log_confidence:\n pretty_print(f\"Agent choice -> BART: {bart} ({final_score_bart}) LLM-router: {llm_router} ({final_score_llm})\")\n return bart if final_score_bart > final_score_llm else llm_router\n \n def find_first_sentence(self, text: str) -> str:\n first_sentence = None\n for line in text.split(\"\\n\"):\n first_sentence = line.strip()\n break\n if first_sentence is None:\n first_sentence = text\n return first_sentence\n \n def estimate_complexity(self, text: str) -> str:\n \"\"\"\n Estimate the complexity of the text.\n Args:\n text: The input text\n Returns:\n str: The estimated complexity\n \"\"\"\n try:\n predictions = self.complexity_classifier.predict(text)\n except Exception as e:\n pretty_print(f\"Error in estimate_complexity: {str(e)}\", color=\"failure\")\n return \"LOW\"\n predictions = sorted(predictions, key=lambda x: x[1], reverse=True)\n if len(predictions) == 0:\n return \"LOW\"\n complexity, confidence = predictions[0][0], predictions[0][1]\n if confidence < 0.5:\n self.logger.info(f\"Low confidence in complexity estimation: {confidence}\")\n return \"HIGH\"\n if complexity == \"HIGH\":\n return \"HIGH\"\n elif complexity == \"LOW\":\n return \"LOW\"\n pretty_print(f\"Failed to estimate the complexity of the text.\", color=\"failure\")\n return \"LOW\"\n \n def find_planner_agent(self) -> Agent:\n \"\"\"\n Find the planner agent.\n Returns:\n Agent: The planner agent\n \"\"\"\n for agent in self.agents:\n if agent.type == \"planner_agent\":\n return agent\n pretty_print(f\"Error finding planner agent. Please add a planner agent to the list of agents.\", color=\"failure\")\n self.logger.error(\"Planner agent not found.\")\n return None\n \n def select_agent(self, text: str) -> Agent:\n \"\"\"\n Select the appropriate agent based on the text.\n Args:\n text (str): The text to select the agent from\n Returns:\n Agent: The selected agent\n \"\"\"\n assert len(self.agents) > 0, \"No agents available.\"\n if len(self.agents) == 1:\n return self.agents[0]\n lang = self.lang_analysis.detect_language(text)\n text = self.find_first_sentence(text)\n text = self.lang_analysis.translate(text, lang)\n labels = [agent.role for agent in self.agents]\n complexity = self.estimate_complexity(text)\n if complexity == \"HIGH\":\n pretty_print(f\"Complex task detected, routing to planner agent.\", color=\"info\")\n return self.find_planner_agent()\n try:\n best_agent = self.router_vote(text, labels, log_confidence=False)\n except Exception as e:\n raise e\n for agent in self.agents:\n if best_agent == agent.role:\n role_name = agent.role\n pretty_print(f\"Selected agent: {agent.agent_name} (roles: {role_name})\", color=\"warning\")\n return agent\n pretty_print(f\"Error choosing agent.\", color=\"failure\")\n self.logger.error(\"No agent selected.\")\n return None\n\nif __name__ == \"__main__\":\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n agents = [\n CasualAgent(\"jarvis\", \"../prompts/base/casual_agent.txt\", None),\n BrowserAgent(\"browser\", \"../prompts/base/planner_agent.txt\", None),\n CoderAgent(\"coder\", \"../prompts/base/coder_agent.txt\", None),\n FileAgent(\"file\", \"../prompts/base/coder_agent.txt\", None)\n ]\n router = AgentRouter(agents)\n texts = [\n \"hi\",\n \"你好\",\n \"Bonjour\",\n \"Write a python script to check if the device on my network is connected to the internet\",\n \"Peut tu écrire un script python qui vérifie si l'appareil sur mon réseau est connecté à internet?\",\n \"写一个Python脚本,检查我网络上的设备是否连接到互联网\",\n \"Hey could you search the web for the latest news on the tesla stock market ?\",\n \"嘿,你能搜索网页上关于股票市场的最新新闻吗?\",\n \"Yo, cherche sur internet comment va tesla en bourse.\",\n \"I would like you to search for weather api and then make an app using this API\",\n \"我想让你搜索天气API,然后用这个API做一个应用程序\",\n \"J'aimerais que tu cherche une api météo et que l'utilise pour faire une application\",\n \"Plan a 3-day trip to New York, including flights and hotels.\",\n \"计划一次为期3天的纽约之旅,包括机票和酒店。\",\n \"Planifie un trip de 3 jours à Paris, y compris les vols et hotels.\",\n \"Find on the web the latest research papers on AI.\",\n \"在网上找到最新的人工智能研究论文。\",\n \"Trouve moi les derniers articles de recherche sur l'IA sur internet\",\n \"Help me write a C++ program to sort an array\",\n \"Tell me what France been up to lately\",\n \"告诉我法国最近在做什么\",\n \"Dis moi ce que la France a fait récemment\",\n \"Who is Sergio Pesto ?\",\n \"谁是Sergio Pesto?\",\n \"Qui est Sergio Pesto ?\",\n \"帮我写一个C++程序来排序数组\",\n \"Aide moi à faire un programme c++ pour trier une array.\",\n \"What’s the weather like today? Oh, and can you find a good weather app?\",\n \"今天天气怎么样?哦,你还能找到一个好的天气应用程序吗?\",\n \"La météo est comment aujourd'hui ? oh et trouve moi une bonne appli météo tant que tu y est.\",\n \"Can you debug this Java code? It’s not working.\",\n \"你能调试这段Java代码吗?它不起作用。\",\n \"Peut tu m'aider à debugger ce code java, ça marche pas\",\n \"Can you browse the web and find me a 4090 for cheap?\",\n \"你能浏览网页,为我找一个便宜的4090吗?\",\n \"Peut tu chercher sur internet et me trouver une 4090 pas cher ?\",\n \"Hey, can you find the old_project.zip file somewhere on my drive?\",\n \"嘿,你能在我驱动器上找到old_project.zip文件吗?\",\n \"Hé trouve moi le old_project.zip, il est quelque part sur mon disque.\",\n \"Tell me a funny story\",\n \"给我讲一个有趣的故事\",\n \"Raconte moi une histoire drole\"\n ]\n for text in texts:\n print(\"Input text:\", text)\n agent = router.select_agent(text)\n print()\n"], ["/agenticSeek/sources/tools/webSearch.py", "\nimport os\nimport requests\nimport dotenv\n\ndotenv.load_dotenv()\n\nfrom sources.tools.tools import Tools\nfrom sources.utility import animate_thinking, pretty_print\n\n\"\"\"\nWARNING\nwebSearch is fully deprecated and is being replaced by searxSearch for web search.\n\"\"\"\n\nclass webSearch(Tools):\n def __init__(self, api_key: str = None):\n \"\"\"\n A tool to perform a Google search and return information from the first result.\n \"\"\"\n super().__init__()\n self.tag = \"web_search\"\n self.api_key = api_key or os.getenv(\"SERPAPI_KEY\") # Requires a SerpApi key\n self.paywall_keywords = [\n \"subscribe\", \"login to continue\", \"access denied\", \"restricted content\", \"404\", \"this page is not working\"\n ]\n\n def link_valid(self, link):\n \"\"\"check if a link is valid.\"\"\"\n if not link.startswith(\"http\"):\n return \"Status: Invalid URL\"\n \n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\"}\n try:\n response = requests.get(link, headers=headers, timeout=5)\n status = response.status_code\n if status == 200:\n content = response.text[:1000].lower()\n if any(keyword in content for keyword in self.paywall_keywords):\n return \"Status: Possible Paywall\"\n return \"Status: OK\"\n elif status == 404:\n return \"Status: 404 Not Found\"\n elif status == 403:\n return \"Status: 403 Forbidden\"\n else:\n return f\"Status: {status} {response.reason}\"\n except requests.exceptions.RequestException as e:\n return f\"Error: {str(e)}\"\n\n def check_all_links(self, links):\n \"\"\"Check all links, one by one.\"\"\"\n # TODO Make it asyncromous or smth\n statuses = []\n for i, link in enumerate(links):\n status = self.link_valid(link)\n statuses.append(status)\n return statuses\n\n def execute(self, blocks: str, safety: bool = True) -> str:\n if self.api_key is None:\n return \"Error: No SerpApi key provided.\"\n for block in blocks:\n query = block.strip()\n pretty_print(f\"Searching for: {query}\", color=\"status\")\n if not query:\n return \"Error: No search query provided.\"\n\n try:\n url = \"https://serpapi.com/search\"\n params = {\n \"q\": query,\n \"api_key\": self.api_key,\n \"num\": 50,\n \"output\": \"json\"\n }\n response = requests.get(url, params=params)\n response.raise_for_status()\n\n data = response.json()\n results = []\n if \"organic_results\" in data and len(data[\"organic_results\"]) > 0:\n organic_results = data[\"organic_results\"][:50]\n links = [result.get(\"link\", \"No link available\") for result in organic_results]\n statuses = self.check_all_links(links)\n for result, status in zip(organic_results, statuses):\n if not \"OK\" in status:\n continue\n title = result.get(\"title\", \"No title\")\n snippet = result.get(\"snippet\", \"No snippet available\")\n link = result.get(\"link\", \"No link available\")\n results.append(f\"Title:{title}\\nSnippet:{snippet}\\nLink:{link}\")\n return \"\\n\\n\".join(results)\n else:\n return \"No results found for the query.\"\n except requests.RequestException as e:\n return f\"Error during web search: {str(e)}\"\n except Exception as e:\n return f\"Unexpected error: {str(e)}\"\n return \"No search performed\"\n\n def execution_failure_check(self, output: str) -> bool:\n return output.startswith(\"Error\") or \"No results found\" in output\n\n def interpreter_feedback(self, output: str) -> str:\n if self.execution_failure_check(output):\n return f\"Web search failed: {output}\"\n return f\"Web search result:\\n{output}\"\n\n\nif __name__ == \"__main__\":\n search_tool = webSearch(api_key=os.getenv(\"SERPAPI_KEY\"))\n query = \"when did covid start\"\n result = search_tool.execute([query], safety=True)\n output = search_tool.interpreter_feedback(result)\n print(output)"], ["/agenticSeek/sources/llm_provider.py", "import os\nimport platform\nimport socket\nimport subprocess\nimport time\nfrom urllib.parse import urlparse\n\nimport httpx\nimport requests\nfrom dotenv import load_dotenv\nfrom ollama import Client as OllamaClient\nfrom openai import OpenAI\n\nfrom sources.logger import Logger\nfrom sources.utility import pretty_print, animate_thinking\n\nclass Provider:\n def __init__(self, provider_name, model, server_address=\"127.0.0.1:5000\", is_local=False):\n self.provider_name = provider_name.lower()\n self.model = model\n self.is_local = is_local\n self.server_ip = server_address\n self.server_address = server_address\n self.available_providers = {\n \"ollama\": self.ollama_fn,\n \"server\": self.server_fn,\n \"openai\": self.openai_fn,\n \"lm-studio\": self.lm_studio_fn,\n \"huggingface\": self.huggingface_fn,\n \"google\": self.google_fn,\n \"deepseek\": self.deepseek_fn,\n \"together\": self.together_fn,\n \"dsk_deepseek\": self.dsk_deepseek,\n \"openrouter\": self.openrouter_fn,\n \"test\": self.test_fn\n }\n self.logger = Logger(\"provider.log\")\n self.api_key = None\n self.internal_url, self.in_docker = self.get_internal_url()\n self.unsafe_providers = [\"openai\", \"deepseek\", \"dsk_deepseek\", \"together\", \"google\", \"openrouter\"]\n if self.provider_name not in self.available_providers:\n raise ValueError(f\"Unknown provider: {provider_name}\")\n if self.provider_name in self.unsafe_providers and self.is_local == False:\n pretty_print(\"Warning: you are using an API provider. You data will be sent to the cloud.\", color=\"warning\")\n self.api_key = self.get_api_key(self.provider_name)\n elif self.provider_name != \"ollama\":\n pretty_print(f\"Provider: {provider_name} initialized at {self.server_ip}\", color=\"success\")\n\n def get_model_name(self) -> str:\n return self.model\n\n def get_api_key(self, provider):\n load_dotenv()\n api_key_var = f\"{provider.upper()}_API_KEY\"\n api_key = os.getenv(api_key_var)\n if not api_key:\n pretty_print(f\"API key {api_key_var} not found in .env file. Please add it\", color=\"warning\")\n exit(1)\n return api_key\n \n def get_internal_url(self):\n load_dotenv()\n url = os.getenv(\"DOCKER_INTERNAL_URL\")\n if not url: # running on host\n return \"http://localhost\", False\n return url, True\n\n def respond(self, history, verbose=True):\n \"\"\"\n Use the choosen provider to generate text.\n \"\"\"\n llm = self.available_providers[self.provider_name]\n self.logger.info(f\"Using provider: {self.provider_name} at {self.server_ip}\")\n try:\n thought = llm(history, verbose)\n except KeyboardInterrupt:\n self.logger.warning(\"User interrupted the operation with Ctrl+C\")\n return \"Operation interrupted by user. REQUEST_EXIT\"\n except ConnectionError as e:\n raise ConnectionError(f\"{str(e)}\\nConnection to {self.server_ip} failed.\")\n except AttributeError as e:\n raise NotImplementedError(f\"{str(e)}\\nIs {self.provider_name} implemented ?\")\n except ModuleNotFoundError as e:\n raise ModuleNotFoundError(\n f\"{str(e)}\\nA import related to provider {self.provider_name} was not found. Is it installed ?\")\n except Exception as e:\n if \"try again later\" in str(e).lower():\n return f\"{self.provider_name} server is overloaded. Please try again later.\"\n if \"refused\" in str(e):\n return f\"Server {self.server_ip} seem offline. Unable to answer.\"\n raise Exception(f\"Provider {self.provider_name} failed: {str(e)}\") from e\n return thought\n\n def is_ip_online(self, address: str, timeout: int = 10) -> bool:\n \"\"\"\n Check if an address is online by sending a ping request.\n \"\"\"\n if not address:\n return False\n parsed = urlparse(address if address.startswith(('http://', 'https://')) else f'http://{address}')\n\n hostname = parsed.hostname or address\n if \"127.0.0.1\" in address or \"localhost\" in address:\n return True\n try:\n ip_address = socket.gethostbyname(hostname)\n except socket.gaierror:\n self.logger.error(f\"Cannot resolve: {hostname}\")\n return False\n param = '-n' if platform.system().lower() == 'windows' else '-c'\n command = ['ping', param, '1', ip_address]\n try:\n result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)\n return result.returncode == 0\n except (subprocess.TimeoutExpired, subprocess.SubprocessError) as e:\n return False\n\n def server_fn(self, history, verbose=False):\n \"\"\"\n Use a remote server with LLM to generate text.\n \"\"\"\n thought = \"\"\n route_setup = f\"{self.server_ip}/setup\"\n route_gen = f\"{self.server_ip}/generate\"\n\n if not self.is_ip_online(self.server_ip):\n pretty_print(f\"Server is offline at {self.server_ip}\", color=\"failure\")\n\n try:\n requests.post(route_setup, json={\"model\": self.model})\n requests.post(route_gen, json={\"messages\": history})\n is_complete = False\n while not is_complete:\n try:\n response = requests.get(f\"{self.server_ip}/get_updated_sentence\")\n if \"error\" in response.json():\n pretty_print(response.json()[\"error\"], color=\"failure\")\n break\n thought = response.json()[\"sentence\"]\n is_complete = bool(response.json()[\"is_complete\"])\n time.sleep(2)\n except requests.exceptions.RequestException as e:\n pretty_print(f\"HTTP request failed: {str(e)}\", color=\"failure\")\n break\n except ValueError as e:\n pretty_print(f\"Failed to parse JSON response: {str(e)}\", color=\"failure\")\n break\n except Exception as e:\n pretty_print(f\"An error occurred: {str(e)}\", color=\"failure\")\n break\n except KeyError as e:\n raise Exception(\n f\"{str(e)}\\nError occured with server route. Are you using the correct address for the config.ini provider?\") from e\n except Exception as e:\n raise e\n return thought\n\n def ollama_fn(self, history, verbose=False):\n \"\"\"\n Use local or remote Ollama server to generate text.\n \"\"\"\n thought = \"\"\n host = f\"{self.internal_url}:11434\" if self.is_local else f\"http://{self.server_address}\"\n client = OllamaClient(host=host)\n\n try:\n stream = client.chat(\n model=self.model,\n messages=history,\n stream=True,\n )\n for chunk in stream:\n if verbose:\n print(chunk[\"message\"][\"content\"], end=\"\", flush=True)\n thought += chunk[\"message\"][\"content\"]\n except httpx.ConnectError as e:\n raise Exception(\n f\"\\nOllama connection failed at {host}. Check if the server is running.\"\n ) from e\n except Exception as e:\n if hasattr(e, 'status_code') and e.status_code == 404:\n animate_thinking(f\"Downloading {self.model}...\")\n client.pull(self.model)\n self.ollama_fn(history, verbose)\n if \"refused\" in str(e).lower():\n raise Exception(\n f\"Ollama connection refused at {host}. Is the server running?\"\n ) from e\n raise e\n\n return thought\n\n def huggingface_fn(self, history, verbose=False):\n \"\"\"\n Use huggingface to generate text.\n \"\"\"\n from huggingface_hub import InferenceClient\n client = InferenceClient(\n api_key=self.get_api_key(\"huggingface\")\n )\n completion = client.chat.completions.create(\n model=self.model,\n messages=history,\n max_tokens=1024,\n )\n thought = completion.choices[0].message\n return thought.content\n\n def openai_fn(self, history, verbose=False):\n \"\"\"\n Use openai to generate text.\n \"\"\"\n base_url = self.server_ip\n if self.is_local and self.in_docker:\n try:\n host, port = base_url.split(':')\n except Exception as e:\n port = \"8000\"\n client = OpenAI(api_key=self.api_key, base_url=f\"{self.internal_url}:{port}\")\n elif self.is_local:\n client = OpenAI(api_key=self.api_key, base_url=f\"http://{base_url}\")\n else:\n client = OpenAI(api_key=self.api_key)\n\n try:\n response = client.chat.completions.create(\n model=self.model,\n messages=history,\n )\n if response is None:\n raise Exception(\"OpenAI response is empty.\")\n thought = response.choices[0].message.content\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"OpenAI API error: {str(e)}\") from e\n\n def anthropic_fn(self, history, verbose=False):\n \"\"\"\n Use Anthropic to generate text.\n \"\"\"\n from anthropic import Anthropic\n\n client = Anthropic(api_key=self.api_key)\n system_message = None\n messages = []\n for message in history:\n clean_message = {'role': message['role'], 'content': message['content']}\n if message['role'] == 'system':\n system_message = message['content']\n else:\n messages.append(clean_message)\n\n try:\n response = client.messages.create(\n model=self.model,\n max_tokens=1024,\n messages=messages,\n system=system_message\n )\n if response is None:\n raise Exception(\"Anthropic response is empty.\")\n thought = response.content[0].text\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"Anthropic API error: {str(e)}\") from e\n\n def google_fn(self, history, verbose=False):\n \"\"\"\n Use google gemini to generate text.\n \"\"\"\n base_url = self.server_ip\n if self.is_local:\n raise Exception(\"Google Gemini is not available for local use. Change config.ini\")\n\n client = OpenAI(api_key=self.api_key, base_url=\"https://generativelanguage.googleapis.com/v1beta/openai/\")\n try:\n response = client.chat.completions.create(\n model=self.model,\n messages=history,\n )\n if response is None:\n raise Exception(\"Google response is empty.\")\n thought = response.choices[0].message.content\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"GOOGLE API error: {str(e)}\") from e\n\n def together_fn(self, history, verbose=False):\n \"\"\"\n Use together AI for completion\n \"\"\"\n from together import Together\n client = Together(api_key=self.api_key)\n if self.is_local:\n raise Exception(\"Together AI is not available for local use. Change config.ini\")\n\n try:\n response = client.chat.completions.create(\n model=self.model,\n messages=history,\n )\n if response is None:\n raise Exception(\"Together AI response is empty.\")\n thought = response.choices[0].message.content\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"Together AI API error: {str(e)}\") from e\n\n def deepseek_fn(self, history, verbose=False):\n \"\"\"\n Use deepseek api to generate text.\n \"\"\"\n client = OpenAI(api_key=self.api_key, base_url=\"https://api.deepseek.com\")\n if self.is_local:\n raise Exception(\"Deepseek (API) is not available for local use. Change config.ini\")\n try:\n response = client.chat.completions.create(\n model=\"deepseek-chat\",\n messages=history,\n stream=False\n )\n thought = response.choices[0].message.content\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"Deepseek API error: {str(e)}\") from e\n\n def lm_studio_fn(self, history, verbose=False):\n \"\"\"\n Use local lm-studio server to generate text.\n \"\"\"\n if self.in_docker:\n # Extract port from server_address if present\n port = \"1234\" # default\n if \":\" in self.server_address:\n port = self.server_address.split(\":\")[1]\n url = f\"{self.internal_url}:{port}\"\n else:\n url = f\"http://{self.server_ip}\"\n route_start = f\"{url}/v1/chat/completions\"\n payload = {\n \"messages\": history,\n \"temperature\": 0.7,\n \"max_tokens\": 4096,\n \"model\": self.model\n }\n\n try:\n response = requests.post(route_start, json=payload, timeout=30)\n if response.status_code != 200:\n raise Exception(f\"LM Studio returned status {response.status_code}: {response.text}\")\n if not response.text.strip():\n raise Exception(\"LM Studio returned empty response\")\n try:\n result = response.json()\n except ValueError as json_err:\n raise Exception(f\"Invalid JSON from LM Studio: {response.text[:200]}\") from json_err\n\n if verbose:\n print(\"Response from LM Studio:\", result)\n choices = result.get(\"choices\", [])\n if not choices:\n raise Exception(f\"No choices in LM Studio response: {result}\")\n\n message = choices[0].get(\"message\", {})\n content = message.get(\"content\", \"\")\n if not content:\n raise Exception(f\"Empty content in LM Studio response: {result}\")\n return content\n\n except requests.exceptions.Timeout:\n raise Exception(\"LM Studio request timed out - check if server is responsive\")\n except requests.exceptions.ConnectionError:\n raise Exception(f\"Cannot connect to LM Studio at {route_start} - check if server is running\")\n except requests.exceptions.RequestException as e:\n raise Exception(f\"HTTP request failed: {str(e)}\") from e\n except Exception as e:\n if \"LM Studio\" in str(e):\n raise # Re-raise our custom exceptions\n raise Exception(f\"Unexpected error: {str(e)}\") from e\n return thought\n\n def openrouter_fn(self, history, verbose=False):\n \"\"\"\n Use OpenRouter API to generate text.\n \"\"\"\n client = OpenAI(api_key=self.api_key, base_url=\"https://openrouter.ai/api/v1\")\n if self.is_local:\n # This case should ideally not be reached if unsafe_providers is set correctly\n # and is_local is False in config for openrouter\n raise Exception(\"OpenRouter is not available for local use. Change config.ini\")\n try:\n response = client.chat.completions.create(\n model=self.model,\n messages=history,\n )\n if response is None:\n raise Exception(\"OpenRouter response is empty.\")\n thought = response.choices[0].message.content\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"OpenRouter API error: {str(e)}\") from e\n\n def dsk_deepseek(self, history, verbose=False):\n \"\"\"\n Use: xtekky/deepseek4free\n For free api. Api key should be set to DSK_DEEPSEEK_API_KEY\n This is an unofficial provider, you'll have to find how to set it up yourself.\n \"\"\"\n from dsk.api import (\n DeepSeekAPI,\n AuthenticationError,\n RateLimitError,\n NetworkError,\n CloudflareError,\n APIError\n )\n thought = \"\"\n message = '\\n---\\n'.join([f\"{msg['role']}: {msg['content']}\" for msg in history])\n\n try:\n api = DeepSeekAPI(self.api_key)\n chat_id = api.create_chat_session()\n for chunk in api.chat_completion(chat_id, message):\n if chunk['type'] == 'text':\n thought += chunk['content']\n return thought\n except AuthenticationError:\n raise AuthenticationError(\"Authentication failed. Please check your token.\") from e\n except RateLimitError:\n raise RateLimitError(\"Rate limit exceeded. Please wait before making more requests.\") from e\n except CloudflareError as e:\n raise CloudflareError(f\"Cloudflare protection encountered: {str(e)}\") from e\n except NetworkError:\n raise NetworkError(\"Network error occurred. Check your internet connection.\") from e\n except APIError as e:\n raise APIError(f\"API error occurred: {str(e)}\") from e\n return None\n\n def test_fn(self, history, verbose=True):\n \"\"\"\n This function is used to conduct tests.\n \"\"\"\n thought = \"\"\"\n\\n\\n```json\\n{\\n \\\"plan\\\": [\\n {\\n \\\"agent\\\": \\\"Web\\\",\\n \\\"id\\\": \\\"1\\\",\\n \\\"need\\\": null,\\n \\\"task\\\": \\\"Conduct a comprehensive web search to identify at least five AI startups located in Osaka. Use reliable sources and websites such as Crunchbase, TechCrunch, or local Japanese business directories. Capture the company names, their websites, areas of expertise, and any other relevant details.\\\"\\n },\\n {\\n \\\"agent\\\": \\\"Web\\\",\\n \\\"id\\\": \\\"2\\\",\\n \\\"need\\\": null,\\n \\\"task\\\": \\\"Perform a similar search to find at least five AI startups in Tokyo. Again, use trusted sources like Crunchbase, TechCrunch, or Japanese business news websites. Gather the same details as for Osaka: company names, websites, areas of focus, and additional information.\\\"\\n },\\n {\\n \\\"agent\\\": \\\"File\\\",\\n \\\"id\\\": \\\"3\\\",\\n \\\"need\\\": [\\\"1\\\", \\\"2\\\"],\\n \\\"task\\\": \\\"Create a new text file named research_japan.txt in the user's home directory. Organize the data collected from both searches into this file, ensuring it is well-structured and formatted for readability. Include headers for Osaka and Tokyo sections, followed by the details of each startup found.\\\"\\n }\\n ]\\n}\\n```\n \"\"\"\n return thought\n\n\nif __name__ == \"__main__\":\n provider = Provider(\"server\", \"deepseek-r1:32b\", \" x.x.x.x:8080\")\n res = provider.respond([\"user\", \"Hello, how are you?\"])\n print(\"Response:\", res)\n"], ["/agenticSeek/sources/tools/flightSearch.py", "import os, sys\nimport requests\nimport dotenv\n\ndotenv.load_dotenv()\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass FlightSearch(Tools):\n def __init__(self, api_key: str = None):\n \"\"\"\n A tool to search for flight information using a flight number via SerpApi.\n \"\"\"\n super().__init__()\n self.tag = \"flight_search\"\n self.name = \"Flight Search\"\n self.description = \"Search for flight information using a flight number via SerpApi.\"\n self.api_key = api_key or os.getenv(\"SERPAPI_API_KEY\")\n\n def execute(self, blocks: str, safety: bool = True) -> str:\n if self.api_key is None:\n return \"Error: No SerpApi key provided.\"\n \n for block in blocks:\n flight_number = block.strip().upper().replace('\\n', '')\n if not flight_number:\n return \"Error: No flight number provided.\"\n\n try:\n url = \"https://serpapi.com/search\"\n params = {\n \"engine\": \"google_flights\",\n \"api_key\": self.api_key,\n \"q\": flight_number,\n \"type\": \"2\" # Flight status search\n }\n \n response = requests.get(url, params=params)\n response.raise_for_status()\n data = response.json()\n \n if \"flights\" in data and len(data[\"flights\"]) > 0:\n flight = data[\"flights\"][0]\n \n # Extract key information\n departure = flight.get(\"departure_airport\", {})\n arrival = flight.get(\"arrival_airport\", {})\n \n departure_code = departure.get(\"id\", \"Unknown\")\n departure_time = flight.get(\"departure_time\", \"Unknown\")\n arrival_code = arrival.get(\"id\", \"Unknown\") \n arrival_time = flight.get(\"arrival_time\", \"Unknown\")\n airline = flight.get(\"airline\", \"Unknown\")\n status = flight.get(\"flight_status\", \"Unknown\")\n\n return (\n f\"Flight: {flight_number}\\n\"\n f\"Airline: {airline}\\n\"\n f\"Status: {status}\\n\"\n f\"Departure: {departure_code} at {departure_time}\\n\"\n f\"Arrival: {arrival_code} at {arrival_time}\"\n )\n else:\n return f\"No flight information found for {flight_number}\"\n \n except requests.RequestException as e:\n return f\"Error during flight search: {str(e)}\"\n except Exception as e:\n return f\"Unexpected error: {str(e)}\"\n \n return \"No flight search performed\"\n\n def execution_failure_check(self, output: str) -> bool:\n return output.startswith(\"Error\") or \"No flight information found\" in output\n\n def interpreter_feedback(self, output: str) -> str:\n if self.execution_failure_check(output):\n return f\"Flight search failed: {output}\"\n return f\"Flight information:\\n{output}\"\n\n\nif __name__ == \"__main__\":\n flight_tool = FlightSearch()\n flight_number = \"AA123\"\n result = flight_tool.execute([flight_number], safety=True)\n feedback = flight_tool.interpreter_feedback(result)\n print(feedback)"], ["/agenticSeek/sources/browser.py", "from selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException, WebDriverException\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom typing import List, Tuple, Type, Dict\nfrom bs4 import BeautifulSoup\nfrom urllib.parse import urlparse\nfrom fake_useragent import UserAgent\nfrom selenium_stealth import stealth\nimport undetected_chromedriver as uc\nimport chromedriver_autoinstaller\nimport certifi\nimport ssl\nimport time\nimport random\nimport os\nimport shutil\nimport uuid\nimport tempfile\nimport markdownify\nimport sys\nimport re\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.logger import Logger\n\n\ndef get_chrome_path() -> str:\n \"\"\"Get the path to the Chrome executable.\"\"\"\n if sys.platform.startswith(\"win\"):\n paths = [\n \"C:\\\\Program Files\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe\",\n \"C:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe\",\n os.path.join(os.environ.get(\"LOCALAPPDATA\", \"\"), \"Google\\\\Chrome\\\\Application\\\\chrome.exe\") # User install\n ]\n elif sys.platform.startswith(\"darwin\"): # macOS\n paths = [\"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome\",\n \"/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta\"]\n else: # Linux\n paths = [\"/usr/bin/google-chrome\",\n \"/opt/chrome/chrome\",\n \"/usr/bin/chromium-browser\",\n \"/usr/bin/chromium\",\n \"/usr/local/bin/chrome\",\n \"/opt/google/chrome/chrome-headless-shell\",\n #\"/app/chrome_bundle/chrome136/chrome-linux64\"\n ]\n\n for path in paths:\n if os.path.exists(path) and os.access(path, os.X_OK):\n return path\n print(\"Looking for Google Chrome in these locations failed:\")\n print('\\n'.join(paths))\n chrome_path_env = os.environ.get(\"CHROME_EXECUTABLE_PATH\")\n if chrome_path_env and os.path.exists(chrome_path_env) and os.access(chrome_path_env, os.X_OK):\n return chrome_path_env\n path = input(\"Google Chrome not found. Please enter the path to the Chrome executable: \")\n if os.path.exists(path) and os.access(path, os.X_OK):\n os.environ[\"CHROME_EXECUTABLE_PATH\"] = path\n print(f\"Chrome path saved to environment variable CHROME_EXECUTABLE_PATH\")\n return path\n return None\n\ndef get_random_user_agent() -> str:\n \"\"\"Get a random user agent string with associated vendor.\"\"\"\n user_agents = [\n {\"ua\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36\", \"vendor\": \"Google Inc.\"},\n {\"ua\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 14_6_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36\", \"vendor\": \"Apple Inc.\"},\n {\"ua\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36\", \"vendor\": \"Google Inc.\"},\n ]\n return random.choice(user_agents)\n\ndef install_chromedriver() -> str:\n \"\"\"\n Install the ChromeDriver if not already installed. Return the path.\n \"\"\"\n # First try to use chromedriver in the project root directory (as per README)\n project_root_chromedriver = \"./chromedriver\"\n if os.path.exists(project_root_chromedriver) and os.access(project_root_chromedriver, os.X_OK):\n print(f\"Using ChromeDriver from project root: {project_root_chromedriver}\")\n return project_root_chromedriver\n \n # Then try to use the system-installed chromedriver\n chromedriver_path = shutil.which(\"chromedriver\")\n if chromedriver_path:\n return chromedriver_path\n \n # In Docker environment, try the fixed path\n if os.path.exists('/.dockerenv'):\n docker_chromedriver_path = \"/usr/local/bin/chromedriver\"\n if os.path.exists(docker_chromedriver_path) and os.access(docker_chromedriver_path, os.X_OK):\n print(f\"Using Docker ChromeDriver at {docker_chromedriver_path}\")\n return docker_chromedriver_path\n \n # Fallback to auto-installer only if no other option works\n try:\n print(\"ChromeDriver not found, attempting to install automatically...\")\n chromedriver_path = chromedriver_autoinstaller.install()\n except Exception as e:\n raise FileNotFoundError(\n \"ChromeDriver not found and could not be installed automatically. \"\n \"Please install it manually from https://chromedriver.chromium.org/downloads.\"\n \"and ensure it's in your PATH or specify the path directly.\"\n \"See know issues in readme if your chrome version is above 115.\"\n ) from e\n \n if not chromedriver_path:\n raise FileNotFoundError(\"ChromeDriver not found. Please install it or add it to your PATH.\")\n return chromedriver_path\n\ndef bypass_ssl() -> str:\n \"\"\"\n This is a fallback for stealth mode to bypass SSL verification. Which can fail on some setup.\n \"\"\"\n pretty_print(\"Bypassing SSL verification issues, we strongly advice you update your certifi SSL certificate.\", color=\"warning\")\n ssl._create_default_https_context = ssl._create_unverified_context\n\ndef create_undetected_chromedriver(service, chrome_options) -> webdriver.Chrome:\n \"\"\"Create an undetected ChromeDriver instance.\"\"\"\n try:\n driver = uc.Chrome(service=service, options=chrome_options)\n except Exception as e:\n pretty_print(f\"Failed to create Chrome driver: {str(e)}. Trying to bypass SSL...\", color=\"failure\")\n try:\n bypass_ssl()\n driver = uc.Chrome(service=service, options=chrome_options)\n except Exception as e:\n pretty_print(f\"Failed to create Chrome driver, fallback failed:\\n{str(e)}.\", color=\"failure\")\n raise e\n raise e\n driver.execute_script(\"Object.defineProperty(navigator, 'webdriver', {get: () => undefined})\") \n return driver\n\ndef create_driver(headless=False, stealth_mode=True, crx_path=\"./crx/nopecha.crx\", lang=\"en\") -> webdriver.Chrome:\n \"\"\"Create a Chrome WebDriver with specified options.\"\"\"\n # Warn if trying to run non-headless in Docker\n if not headless and os.path.exists('/.dockerenv'):\n print(\"[WARNING] Running non-headless browser in Docker may fail!\")\n print(\"[WARNING] Consider setting headless=True or headless_browser=True in config.ini\")\n \n chrome_options = Options()\n chrome_path = get_chrome_path()\n \n if not chrome_path:\n raise FileNotFoundError(\"Google Chrome not found. Please install it.\")\n chrome_options.binary_location = chrome_path\n \n if headless:\n #chrome_options.add_argument(\"--headless\")\n chrome_options.add_argument(\"--headless=new\")\n chrome_options.add_argument(\"--disable-gpu\")\n chrome_options.add_argument(\"--disable-webgl\")\n user_data_dir = tempfile.mkdtemp()\n user_agent = get_random_user_agent()\n width, height = (1920, 1080)\n user_data_dir = tempfile.mkdtemp(prefix=\"chrome_profile_\")\n chrome_options.add_argument(\"--no-sandbox\")\n chrome_options.add_argument('--disable-dev-shm-usage')\n profile_dir = f\"/tmp/chrome_profile_{uuid.uuid4().hex[:8]}\"\n chrome_options.add_argument(f'--user-data-dir={profile_dir}')\n chrome_options.add_argument(f\"--accept-lang={lang}-{lang.upper()},{lang};q=0.9\")\n chrome_options.add_argument(\"--disable-extensions\")\n chrome_options.add_argument(\"--disable-background-timer-throttling\")\n chrome_options.add_argument(\"--timezone=Europe/Paris\")\n chrome_options.add_argument('--remote-debugging-port=9222')\n chrome_options.add_argument('--disable-background-timer-throttling')\n chrome_options.add_argument('--disable-backgrounding-occluded-windows')\n chrome_options.add_argument('--disable-renderer-backgrounding')\n chrome_options.add_argument('--disable-features=TranslateUI')\n chrome_options.add_argument('--disable-ipc-flooding-protection')\n chrome_options.add_argument(\"--mute-audio\")\n chrome_options.add_argument(\"--disable-notifications\")\n chrome_options.add_argument(\"--autoplay-policy=user-gesture-required\")\n chrome_options.add_argument(\"--disable-features=SitePerProcess,IsolateOrigins\")\n chrome_options.add_argument(\"--enable-features=NetworkService,NetworkServiceInProcess\")\n chrome_options.add_argument(\"--disable-blink-features=AutomationControlled\")\n chrome_options.add_argument(f'user-agent={user_agent[\"ua\"]}')\n chrome_options.add_argument(f'--window-size={width},{height}')\n if not stealth_mode:\n if not os.path.exists(crx_path):\n pretty_print(f\"Anti-captcha CRX not found at {crx_path}.\", color=\"failure\")\n else:\n chrome_options.add_extension(crx_path)\n\n chromedriver_path = install_chromedriver()\n\n service = Service(chromedriver_path)\n if stealth_mode:\n chrome_options.add_argument(\"--disable-blink-features=AutomationControlled\")\n driver = create_undetected_chromedriver(service, chrome_options)\n chrome_version = driver.capabilities['browserVersion']\n stealth(driver,\n languages=[\"en-US\", \"en\"],\n vendor=user_agent[\"vendor\"],\n platform=\"Win64\" if \"windows\" in user_agent[\"ua\"].lower() else \"MacIntel\" if \"mac\" in user_agent[\"ua\"].lower() else \"Linux x86_64\",\n webgl_vendor=\"Intel Inc.\",\n renderer=\"Intel Iris OpenGL Engine\",\n fix_hairline=True,\n )\n return driver\n security_prefs = {\n \"profile.default_content_setting_values.geolocation\": 0,\n \"profile.default_content_setting_values.notifications\": 0,\n \"profile.default_content_setting_values.camera\": 0,\n \"profile.default_content_setting_values.microphone\": 0,\n \"profile.default_content_setting_values.midi_sysex\": 0,\n \"profile.default_content_setting_values.clipboard\": 0,\n \"profile.default_content_setting_values.media_stream\": 0,\n \"profile.default_content_setting_values.background_sync\": 0,\n \"profile.default_content_setting_values.sensors\": 0,\n \"profile.default_content_setting_values.accessibility_events\": 0,\n \"safebrowsing.enabled\": True,\n \"credentials_enable_service\": False,\n \"profile.password_manager_enabled\": False,\n \"webkit.webprefs.accelerated_2d_canvas_enabled\": True,\n \"webkit.webprefs.force_dark_mode_enabled\": False,\n \"webkit.webprefs.accelerated_2d_canvas_msaa_sample_count\": 4,\n \"enable_webgl\": True,\n \"enable_webgl2_compute_context\": True\n }\n chrome_options.add_experimental_option(\"prefs\", security_prefs)\n chrome_options.add_experimental_option(\"excludeSwitches\", [\"enable-automation\"])\n chrome_options.add_experimental_option('useAutomationExtension', False)\n return webdriver.Chrome(service=service, options=chrome_options)\n\nclass Browser:\n def __init__(self, driver, anticaptcha_manual_install=False):\n \"\"\"Initialize the browser with optional AntiCaptcha installation.\"\"\"\n self.js_scripts_folder = \"./sources/web_scripts/\" if not __name__ == \"__main__\" else \"./web_scripts/\"\n self.anticaptcha = \"https://chrome.google.com/webstore/detail/nopecha-captcha-solver/dknlfmjaanfblgfdfebhijalfmhmjjjo/related\"\n self.logger = Logger(\"browser.log\")\n self.screenshot_folder = os.path.join(os.getcwd(), \".screenshots\")\n self.tabs = []\n try:\n self.driver = driver\n self.wait = WebDriverWait(self.driver, 10)\n except Exception as e:\n raise Exception(f\"Failed to initialize browser: {str(e)}\")\n self.setup_tabs()\n self.patch_browser_fingerprint()\n if anticaptcha_manual_install:\n self.load_anticatpcha_manually()\n \n def setup_tabs(self):\n self.tabs = self.driver.window_handles\n try:\n self.driver.get(\"https://www.google.com\")\n except Exception as e:\n self.logger.log(f\"Failed to setup initial tab:\" + str(e))\n pass\n self.screenshot()\n \n def switch_control_tab(self):\n self.logger.log(\"Switching to control tab.\")\n self.driver.switch_to.window(self.tabs[0])\n \n def load_anticatpcha_manually(self):\n pretty_print(\"You might want to install the AntiCaptcha extension for captchas.\", color=\"warning\")\n try:\n self.driver.get(self.anticaptcha)\n except Exception as e:\n self.logger.log(f\"Failed to setup initial tab:\" + str(e))\n pass\n\n def human_move(element):\n actions = ActionChains(driver)\n x_offset = random.randint(-5,5)\n for _ in range(random.randint(2,5)):\n actions.move_by_offset(x_offset, random.randint(-2,2))\n actions.pause(random.uniform(0.1,0.3))\n actions.click().perform()\n\n def human_scroll(self):\n for _ in range(random.randint(1, 3)):\n scroll_pixels = random.randint(150, 1200)\n self.driver.execute_script(f\"window.scrollBy(0, {scroll_pixels});\")\n time.sleep(random.uniform(0.5, 2.0))\n if random.random() < 0.4:\n self.driver.execute_script(f\"window.scrollBy(0, -{random.randint(50, 300)});\")\n time.sleep(random.uniform(0.3, 1.0))\n\n def patch_browser_fingerprint(self) -> None:\n script = self.load_js(\"spoofing.js\")\n self.driver.execute_script(script)\n \n def go_to(self, url:str) -> bool:\n \"\"\"Navigate to a specified URL.\"\"\"\n time.sleep(random.uniform(0.4, 2.5))\n try:\n initial_handles = self.driver.window_handles\n self.driver.get(url)\n time.sleep(random.uniform(0.01, 0.3))\n try:\n wait = WebDriverWait(self.driver, timeout=10)\n wait.until(\n lambda driver: (\n not any(keyword in driver.page_source.lower() for keyword in [\"checking your browser\", \"captcha\"])\n ),\n message=\"stuck on 'checking browser' or verification screen\"\n )\n except TimeoutException:\n self.logger.warning(\"Timeout while waiting for page to bypass 'checking your browser'\")\n self.apply_web_safety()\n time.sleep(random.uniform(0.01, 0.2))\n self.human_scroll()\n self.logger.log(f\"Navigated to: {url}\")\n return True\n except TimeoutException as e:\n self.logger.error(f\"Timeout waiting for {url} to load: {str(e)}\")\n return False\n except WebDriverException as e:\n self.logger.error(f\"Error navigating to {url}: {str(e)}\")\n return False\n except Exception as e:\n self.logger.error(f\"Fatal error with go_to method on {url}:\\n{str(e)}\")\n raise e\n\n def is_sentence(self, text:str) -> bool:\n \"\"\"Check if the text qualifies as a meaningful sentence or contains important error codes.\"\"\"\n text = text.strip()\n\n if any(c.isdigit() for c in text):\n return True\n words = re.findall(r'\\w+', text, re.UNICODE)\n word_count = len(words)\n has_punctuation = any(text.endswith(p) for p in ['.', ',', ',', '!', '?', '。', '!', '?', '।', '۔'])\n is_long_enough = word_count > 4\n return (word_count >= 5 and (has_punctuation or is_long_enough))\n\n def get_text(self) -> str | None:\n \"\"\"Get page text as formatted Markdown\"\"\"\n try:\n soup = BeautifulSoup(self.driver.page_source, 'html.parser')\n for element in soup(['script', 'style', 'noscript', 'meta', 'link']):\n element.decompose()\n markdown_converter = markdownify.MarkdownConverter(\n heading_style=\"ATX\",\n strip=['a'],\n autolinks=False,\n bullets='•',\n strong_em_symbol='*',\n default_title=False,\n )\n markdown_text = markdown_converter.convert(str(soup.body))\n lines = []\n for line in markdown_text.splitlines():\n stripped = line.strip()\n if stripped and self.is_sentence(stripped):\n cleaned = ' '.join(stripped.split())\n lines.append(cleaned)\n result = \"[Start of page]\\n\\n\" + \"\\n\\n\".join(lines) + \"\\n\\n[End of page]\"\n result = re.sub(r'!\\[(.*?)\\]\\(.*?\\)', r'[IMAGE: \\1]', result)\n self.logger.info(f\"Extracted text: {result[:100]}...\")\n self.logger.info(f\"Extracted text length: {len(result)}\")\n return result[:32768]\n except Exception as e:\n self.logger.error(f\"Error getting text: {str(e)}\")\n return None\n \n def clean_url(self, url:str) -> str:\n \"\"\"Clean URL to keep only the part needed for navigation to the page\"\"\"\n clean = url.split('#')[0]\n parts = clean.split('?', 1)\n base_url = parts[0]\n if len(parts) > 1:\n query = parts[1]\n essential_params = []\n for param in query.split('&'):\n if param.startswith('_skw=') or param.startswith('q=') or param.startswith('s='):\n essential_params.append(param)\n elif param.startswith('_') or param.startswith('hash=') or param.startswith('itmmeta='):\n break\n if essential_params:\n return f\"{base_url}?{'&'.join(essential_params)}\"\n return base_url\n \n def is_link_valid(self, url:str) -> bool:\n \"\"\"Check if a URL is a valid link (page, not related to icon or metadata).\"\"\"\n if len(url) > 72:\n self.logger.warning(f\"URL too long: {url}\")\n return False\n parsed_url = urlparse(url)\n if not parsed_url.scheme or not parsed_url.netloc:\n self.logger.warning(f\"Invalid URL: {url}\")\n return False\n if re.search(r'/\\d+$', parsed_url.path):\n return False\n image_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp']\n metadata_extensions = ['.ico', '.xml', '.json', '.rss', '.atom']\n for ext in image_extensions + metadata_extensions:\n if url.lower().endswith(ext):\n return False\n return True\n\n def get_navigable(self) -> List[str]:\n \"\"\"Get all navigable links on the current page.\"\"\"\n try:\n links = []\n elements = self.driver.find_elements(By.TAG_NAME, \"a\")\n \n for element in elements:\n href = element.get_attribute(\"href\")\n if href and href.startswith((\"http\", \"https\")):\n links.append({\n \"url\": href,\n \"text\": element.text.strip(),\n \"is_displayed\": element.is_displayed()\n })\n \n self.logger.info(f\"Found {len(links)} navigable links\")\n return [self.clean_url(link['url']) for link in links if (link['is_displayed'] == True and self.is_link_valid(link['url']))]\n except Exception as e:\n self.logger.error(f\"Error getting navigable links: {str(e)}\")\n return []\n\n def click_element(self, xpath: str) -> bool:\n \"\"\"Click an element specified by XPath.\"\"\"\n try:\n element = self.wait.until(EC.element_to_be_clickable((By.XPATH, xpath)))\n if not element.is_displayed():\n return False\n if not element.is_enabled():\n return False\n try:\n self.logger.error(f\"Scrolling to element for click_element.\")\n self.driver.execute_script(\"arguments[0].scrollIntoView({block: 'center', behavior: 'smooth'});\", element)\n time.sleep(0.1)\n element.click()\n self.logger.info(f\"Clicked element at {xpath}\")\n return True\n except ElementClickInterceptedException as e:\n self.logger.error(f\"Error click_element: {str(e)}\")\n return False\n except TimeoutException:\n self.logger.warning(f\"Timeout clicking element.\")\n return False\n except Exception as e:\n self.logger.error(f\"Unexpected error clicking element at {xpath}: {str(e)}\")\n return False\n \n def load_js(self, file_name: str) -> str:\n \"\"\"Load javascript from script folder to inject to page.\"\"\"\n path = os.path.join(self.js_scripts_folder, file_name)\n self.logger.info(f\"Loading js at {path}\")\n try:\n with open(path, 'r') as f:\n return f.read()\n except FileNotFoundError as e:\n raise Exception(f\"Could not find: {path}\") from e\n except Exception as e:\n raise e\n\n def find_all_inputs(self, timeout=3):\n \"\"\"Find all inputs elements on the page.\"\"\"\n try:\n WebDriverWait(self.driver, timeout).until(\n EC.presence_of_element_located((By.TAG_NAME, \"body\"))\n )\n except Exception as e:\n self.logger.error(f\"Error waiting for input element: {str(e)}\")\n return []\n time.sleep(0.5)\n script = self.load_js(\"find_inputs.js\")\n input_elements = self.driver.execute_script(script)\n return input_elements\n\n def get_form_inputs(self) -> List[str]:\n \"\"\"Extract all input from the page and return them.\"\"\"\n try:\n input_elements = self.find_all_inputs()\n if not input_elements:\n self.logger.info(\"No input element on page.\")\n return [\"No input forms found on the page.\"]\n\n form_strings = []\n for element in input_elements:\n input_type = element.get(\"type\") or \"text\"\n if input_type in [\"hidden\", \"submit\", \"button\", \"image\"] or not element[\"displayed\"]:\n continue\n input_name = element.get(\"text\") or element.get(\"id\") or input_type\n if input_type == \"checkbox\" or input_type == \"radio\":\n try:\n checked_status = \"checked\" if element.is_selected() else \"unchecked\"\n except Exception as e:\n continue\n form_strings.append(f\"[{input_name}]({checked_status})\")\n else:\n form_strings.append(f\"[{input_name}](\"\")\")\n return form_strings\n\n except Exception as e:\n raise e\n\n def get_buttons_xpath(self) -> List[str]:\n \"\"\"\n Find buttons and return their type and xpath.\n \"\"\"\n buttons = self.driver.find_elements(By.TAG_NAME, \"button\") + \\\n self.driver.find_elements(By.XPATH, \"//input[@type='submit']\")\n result = []\n for i, button in enumerate(buttons):\n if not button.is_displayed() or not button.is_enabled():\n continue\n text = (button.text or button.get_attribute(\"value\") or \"\").lower().replace(' ', '')\n xpath = f\"(//button | //input[@type='submit'])[{i + 1}]\"\n result.append((text, xpath))\n result.sort(key=lambda x: len(x[0]))\n return result\n\n def wait_for_submission_outcome(self, timeout: int = 10) -> bool:\n \"\"\"\n Wait for a submission outcome (e.g., URL change or new element).\n \"\"\"\n try:\n self.logger.info(\"Waiting for submission outcome...\")\n wait = WebDriverWait(self.driver, timeout)\n wait.until(\n lambda driver: driver.current_url != self.driver.current_url or\n driver.find_elements(By.XPATH, \"//*[contains(text(), 'success')]\")\n )\n self.logger.info(\"Detected submission outcome\")\n return True\n except TimeoutException:\n self.logger.warning(\"No submission outcome detected\")\n return False\n\n def find_and_click_btn(self, btn_type: str = 'login', timeout: int = 5) -> bool:\n \"\"\"Find and click a submit button matching the specified type.\"\"\"\n buttons = self.get_buttons_xpath()\n if not buttons:\n self.logger.warning(\"No visible buttons found\")\n return False\n\n for button_text, xpath in buttons:\n if btn_type.lower() in button_text.lower() or btn_type.lower() in xpath.lower():\n try:\n wait = WebDriverWait(self.driver, timeout)\n element = wait.until(\n EC.element_to_be_clickable((By.XPATH, xpath)),\n message=f\"Button with XPath '{xpath}' not clickable within {timeout} seconds\"\n )\n if self.click_element(xpath):\n self.logger.info(f\"Clicked button '{button_text}' at XPath: {xpath}\")\n return True\n else:\n self.logger.warning(f\"Button '{button_text}' at XPath: {xpath} not clickable\")\n return False\n except TimeoutException:\n self.logger.warning(f\"Timeout waiting for '{button_text}' button at XPath: {xpath}\")\n return False\n except Exception as e:\n self.logger.error(f\"Error clicking button '{button_text}' at XPath: {xpath} - {str(e)}\")\n return False\n self.logger.warning(f\"No button matching '{btn_type}' found\")\n return False\n\n def tick_all_checkboxes(self) -> bool:\n \"\"\"\n Find and tick all checkboxes on the page.\n Returns True if successful, False if any issues occur.\n \"\"\"\n try:\n checkboxes = self.driver.find_elements(By.XPATH, \"//input[@type='checkbox']\")\n if not checkboxes:\n self.logger.info(\"No checkboxes found on the page\")\n return True\n\n for index, checkbox in enumerate(checkboxes, 1):\n try:\n WebDriverWait(self.driver, 10).until(\n EC.element_to_be_clickable(checkbox)\n )\n self.driver.execute_script(\n \"arguments[0].scrollIntoView({block: 'center', inline: 'center'});\", checkbox\n )\n if not checkbox.is_selected():\n try:\n checkbox.click()\n self.logger.info(f\"Ticked checkbox {index}\")\n except ElementClickInterceptedException:\n self.driver.execute_script(\"arguments[0].click();\", checkbox)\n self.logger.warning(f\"Click checkbox {index} intercepted\")\n else:\n self.logger.info(f\"Checkbox {index} already ticked\")\n except TimeoutException:\n self.logger.warning(f\"Timeout waiting for checkbox {index} to be clickable\")\n continue\n except Exception as e:\n self.logger.error(f\"Error ticking checkbox {index}: {str(e)}\")\n continue\n return True\n except Exception as e:\n self.logger.error(f\"Error finding checkboxes: {str(e)}\")\n return False\n\n def find_and_click_submission(self, timeout: int = 10) -> bool:\n possible_submissions = [\"login\", \"submit\", \"register\", \"continue\", \"apply\",\n \"ok\", \"confirm\", \"proceed\", \"accept\", \n \"done\", \"finish\", \"start\", \"calculate\"]\n for submission in possible_submissions:\n if self.find_and_click_btn(submission, timeout):\n self.logger.info(f\"Clicked on submission button: {submission}\")\n return True\n self.logger.warning(\"No submission button found\")\n return False\n \n def find_input_xpath_by_name(self, inputs, name: str) -> str | None:\n for field in inputs:\n if name in field[\"text\"]:\n return field[\"xpath\"]\n return None\n\n def fill_form_inputs(self, input_list: List[str]) -> bool:\n \"\"\"Fill inputs based on a list of [name](value) strings.\"\"\"\n if not isinstance(input_list, list):\n self.logger.error(\"input_list must be a list\")\n return False\n inputs = self.find_all_inputs()\n try:\n for input_str in input_list:\n match = re.match(r'\\[(.*?)\\]\\((.*?)\\)', input_str)\n if not match:\n self.logger.warning(f\"Invalid format for input: {input_str}\")\n continue\n\n name, value = match.groups()\n name = name.strip()\n value = value.strip()\n xpath = self.find_input_xpath_by_name(inputs, name)\n if not xpath:\n self.logger.warning(f\"Input field '{name}' not found\")\n continue\n try:\n element = WebDriverWait(self.driver, 10).until(\n EC.element_to_be_clickable((By.XPATH, xpath))\n )\n except TimeoutException:\n self.logger.error(f\"Timeout waiting for element '{name}' to be clickable\")\n continue\n self.driver.execute_script(\"arguments[0].scrollIntoView(true);\", element)\n if not element.is_displayed() or not element.is_enabled():\n self.logger.warning(f\"Element '{name}' is not interactable (not displayed or disabled)\")\n continue\n input_type = (element.get_attribute(\"type\") or \"text\").lower()\n if input_type in [\"checkbox\", \"radio\"]:\n is_checked = element.is_selected()\n should_be_checked = value.lower() == \"checked\"\n\n if is_checked != should_be_checked:\n element.click()\n self.logger.info(f\"Set {name} to {value}\")\n else:\n element.clear()\n element.send_keys(value)\n self.logger.info(f\"Filled {name} with {value}\")\n return True\n except Exception as e:\n self.logger.error(f\"Error filling form inputs: {str(e)}\")\n return False\n \n def fill_form(self, input_list: List[str]) -> bool:\n \"\"\"Fill form inputs based on a list of [name](value) and submit.\"\"\"\n if not isinstance(input_list, list):\n self.logger.error(\"input_list must be a list\")\n return False\n if self.fill_form_inputs(input_list):\n self.logger.info(\"Form filled successfully\")\n self.tick_all_checkboxes()\n if self.find_and_click_submission():\n if self.wait_for_submission_outcome():\n self.logger.info(\"Submission outcome detected\")\n return True\n else:\n self.logger.warning(\"No submission outcome detected\")\n else:\n self.logger.warning(\"Failed to submit form\")\n self.logger.warning(\"Failed to fill form inputs\")\n return False\n\n def get_current_url(self) -> str:\n \"\"\"Get the current URL of the page.\"\"\"\n return self.driver.current_url\n\n def get_page_title(self) -> str:\n \"\"\"Get the title of the current page.\"\"\"\n return self.driver.title\n\n def scroll_bottom(self) -> bool:\n \"\"\"Scroll to the bottom of the page.\"\"\"\n try:\n self.logger.info(\"Scrolling to the bottom of the page...\")\n self.driver.execute_script(\n \"window.scrollTo(0, document.body.scrollHeight);\"\n )\n time.sleep(0.5)\n return True\n except Exception as e:\n self.logger.error(f\"Error scrolling: {str(e)}\")\n return False\n \n def get_screenshot(self) -> str:\n return self.screenshot_folder + \"/updated_screen.png\"\n\n def screenshot(self, filename:str = 'updated_screen.png') -> bool:\n \"\"\"Take a screenshot of the current page, attempt to capture the full page by zooming out.\"\"\"\n self.logger.info(\"Taking full page screenshot...\")\n time.sleep(0.1)\n try:\n original_zoom = self.driver.execute_script(\"return document.body.style.zoom || 1;\")\n self.driver.execute_script(\"document.body.style.zoom='75%'\")\n time.sleep(0.1)\n path = os.path.join(self.screenshot_folder, filename)\n if not os.path.exists(self.screenshot_folder):\n os.makedirs(self.screenshot_folder)\n self.driver.save_screenshot(path)\n self.logger.info(f\"Full page screenshot saved as {filename}\")\n except Exception as e:\n self.logger.error(f\"Error taking full page screenshot: {str(e)}\")\n return False\n finally:\n self.driver.execute_script(f\"document.body.style.zoom='1'\")\n return True\n\n def apply_web_safety(self):\n \"\"\"\n Apply security measures to block any website malicious/annoying execution, privacy violation etc..\n \"\"\"\n self.logger.info(\"Applying web safety measures...\")\n script = self.load_js(\"inject_safety_script.js\")\n input_elements = self.driver.execute_script(script)\n\nif __name__ == \"__main__\":\n driver = create_driver(headless=False, stealth_mode=True, crx_path=\"../crx/nopecha.crx\")\n browser = Browser(driver, anticaptcha_manual_install=True)\n \n input(\"press enter to continue\")\n print(\"AntiCaptcha / Form Test\")\n browser.go_to(\"https://bot.sannysoft.com\")\n time.sleep(5)\n #txt = browser.get_text()\n browser.go_to(\"https://home.openweathermap.org/users/sign_up\")\n inputs_visible = browser.get_form_inputs()\n print(\"inputs:\", inputs_visible)\n #inputs_fill = ['[q](checked)', '[q](checked)', '[user[username]](mlg)', '[user[email]](mlg.fcu@gmail.com)', '[user[password]](placeholder_P@ssw0rd123)', '[user[password_confirmation]](placeholder_P@ssw0rd123)']\n #browser.fill_form(inputs_fill)\n input(\"press enter to exit\")\n\n# Test sites for browser fingerprinting and captcha\n# https://nowsecure.nl/\n# https://bot.sannysoft.com\n# https://browserleaks.com/\n# https://bot.incolumitas.com/\n# https://fingerprintjs.github.io/fingerprintjs/\n# https://antoinevastel.com/bots/"], ["/agenticSeek/sources/tools/PyInterpreter.py", "\nimport sys\nimport os\nimport re\nfrom io import StringIO\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass PyInterpreter(Tools):\n \"\"\"\n This class is a tool to allow agent for python code execution.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"python\"\n self.name = \"Python Interpreter\"\n self.description = \"This tool allows the agent to execute python code.\"\n\n def execute(self, codes:str, safety = False) -> str:\n \"\"\"\n Execute python code.\n \"\"\"\n output = \"\"\n if safety and input(\"Execute code ? y/n\") != \"y\":\n return \"Code rejected by user.\"\n stdout_buffer = StringIO()\n sys.stdout = stdout_buffer\n global_vars = {\n '__builtins__': __builtins__,\n 'os': os,\n 'sys': sys,\n '__name__': '__main__'\n }\n code = '\\n\\n'.join(codes)\n self.logger.info(f\"Executing code:\\n{code}\")\n try:\n try:\n buffer = exec(code, global_vars)\n self.logger.info(f\"Code executed successfully.\\noutput:{buffer}\")\n print(buffer)\n if buffer is not None:\n output = buffer + '\\n'\n except SystemExit:\n self.logger.info(\"SystemExit caught, code execution stopped.\")\n output = stdout_buffer.getvalue()\n return f\"[SystemExit caught] Output before exit:\\n{output}\"\n except Exception as e:\n self.logger.error(f\"Code execution failed: {str(e)}\")\n return \"code execution failed:\" + str(e)\n output = stdout_buffer.getvalue()\n finally:\n self.logger.info(\"Code execution finished.\")\n sys.stdout = sys.__stdout__\n return output\n\n def interpreter_feedback(self, output:str) -> str:\n \"\"\"\n Provide feedback based on the output of the code execution\n \"\"\"\n if self.execution_failure_check(output):\n feedback = f\"[failure] Error in execution:\\n{output}\"\n else:\n feedback = \"[success] Execution success, code output:\\n\" + output\n return feedback\n\n def execution_failure_check(self, feedback:str) -> bool:\n \"\"\"\n Check if the code execution failed.\n \"\"\"\n error_patterns = [\n r\"expected\", \n r\"errno\", \n r\"failed\", \n r\"traceback\", \n r\"invalid\", \n r\"unrecognized\", \n r\"exception\", \n r\"syntax\", \n r\"crash\", \n r\"segmentation fault\", \n r\"core dumped\"\n ]\n combined_pattern = \"|\".join(error_patterns)\n if re.search(combined_pattern, feedback, re.IGNORECASE):\n self.logger.error(f\"Execution failure detected: {feedback}\")\n return True\n self.logger.info(\"No execution success detected.\")\n return False\n\nif __name__ == \"__main__\":\n text = \"\"\"\nFor Python, let's also do a quick check:\n\n```python\nprint(\"Hello from Python!\")\n```\n\nIf these work, you'll see the outputs in the next message. Let me know if you'd like me to test anything specific! \n\nhere is a save test\n```python:tmp.py\n\ndef print_hello():\n hello = \"Hello World\"\n print(hello)\n\nif __name__ == \"__main__\":\n print_hello()\n```\n\"\"\"\n py = PyInterpreter()\n codes, save_path = py.load_exec_block(text)\n py.save_block(codes, save_path)\n print(py.execute(codes))"], ["/agenticSeek/sources/language.py", "from typing import List, Tuple, Type, Dict\nimport re\nimport langid\nfrom transformers import MarianMTModel, MarianTokenizer\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.logger import Logger\n\nclass LanguageUtility:\n \"\"\"LanguageUtility for language, or emotion identification\"\"\"\n def __init__(self, supported_language: List[str] = [\"en\", \"fr\", \"zh\"]):\n \"\"\"\n Initialize the LanguageUtility class\n args:\n supported_language: list of languages for translation, determine which Helsinki-NLP model to load\n \"\"\"\n self.translators_tokenizer = None \n self.translators_model = None\n self.logger = Logger(\"language.log\")\n self.supported_language = supported_language\n self.load_model()\n \n def load_model(self) -> None:\n animate_thinking(\"Loading language utility...\", color=\"status\")\n self.translators_tokenizer = {lang: MarianTokenizer.from_pretrained(f\"Helsinki-NLP/opus-mt-{lang}-en\") for lang in self.supported_language if lang != \"en\"}\n self.translators_model = {lang: MarianMTModel.from_pretrained(f\"Helsinki-NLP/opus-mt-{lang}-en\") for lang in self.supported_language if lang != \"en\"}\n \n def detect_language(self, text: str) -> str:\n \"\"\"\n Detect the language of the given text using langdetect\n Limited to the supported languages list because of the model tendency to mistake similar languages\n Args:\n text: string to analyze\n Returns: ISO639-1 language code\n \"\"\"\n langid.set_languages(self.supported_language)\n lang, score = langid.classify(text)\n self.logger.info(f\"Identified: {text} as {lang} with conf {score}\")\n return lang\n\n def translate(self, text: str, origin_lang: str) -> str:\n \"\"\"\n Translate the given text to English\n Args:\n text: string to translate\n origin_lang: ISO language code\n Returns: translated str\n \"\"\"\n if origin_lang == \"en\":\n return text\n if origin_lang not in self.translators_tokenizer:\n pretty_print(f\"Language {origin_lang} not supported for translation\", color=\"error\")\n return text\n tokenizer = self.translators_tokenizer[origin_lang]\n inputs = tokenizer(text, return_tensors=\"pt\", padding=True)\n model = self.translators_model[origin_lang]\n translation = model.generate(**inputs)\n return tokenizer.decode(translation[0], skip_special_tokens=True)\n\n def analyze(self, text):\n \"\"\"\n Combined analysis of language and emotion\n Args:\n text: string to analyze\n Returns: dictionary with language related information\n \"\"\"\n try:\n language = self.detect_language(text)\n return {\n \"language\": language\n }\n except Exception as e:\n raise e\n\nif __name__ == \"__main__\":\n detector = LanguageUtility()\n \n test_texts = [\n \"I am so happy today!\",\n \"我不要去巴黎\",\n \"La vie c'est cool\"\n ]\n for text in test_texts:\n pretty_print(\"Analyzing...\", color=\"status\")\n pretty_print(f\"Language: {detector.detect_language(text)}\", color=\"status\")\n result = detector.analyze(text)\n trans = detector.translate(text, result['language'])\n pretty_print(f\"Translation: {trans} - from: {result['language']}\")"], ["/agenticSeek/sources/tools/fileFinder.py", "import os, sys\nimport stat\nimport mimetypes\nimport configparser\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass FileFinder(Tools):\n \"\"\"\n A tool that finds files in the current directory and returns their information.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"file_finder\"\n self.name = \"File Finder\"\n self.description = \"Finds files in the current directory and returns their information.\"\n \n def read_file(self, file_path: str) -> str:\n \"\"\"\n Reads the content of a file.\n Args:\n file_path (str): The path to the file to read\n Returns:\n str: The content of the file\n \"\"\"\n try:\n with open(file_path, 'r') as file:\n return file.read()\n except Exception as e:\n return f\"Error reading file: {e}\"\n \n def read_arbitrary_file(self, file_path: str, file_type: str) -> str:\n \"\"\"\n Reads the content of a file with arbitrary encoding.\n Args:\n file_path (str): The path to the file to read\n Returns:\n str: The content of the file in markdown format\n \"\"\"\n mime_type, _ = mimetypes.guess_type(file_path)\n if mime_type:\n if mime_type.startswith(('image/', 'video/', 'audio/')):\n return \"can't read file type: image, video, or audio files are not supported.\"\n content_raw = self.read_file(file_path)\n if \"text\" in file_type:\n content = content_raw\n elif \"pdf\" in file_type:\n from pypdf import PdfReader\n reader = PdfReader(file_path)\n content = '\\n'.join([pt.extract_text() for pt in reader.pages])\n elif \"binary\" in file_type:\n content = content_raw.decode('utf-8', errors='replace')\n else:\n content = content_raw\n return content\n \n def get_file_info(self, file_path: str) -> str:\n \"\"\"\n Gets information about a file, including its name, path, type, content, and permissions.\n Args:\n file_path (str): The path to the file\n Returns:\n str: A dictionary containing the file information\n \"\"\"\n if os.path.exists(file_path):\n stats = os.stat(file_path)\n permissions = oct(stat.S_IMODE(stats.st_mode))\n file_type, _ = mimetypes.guess_type(file_path)\n file_type = file_type if file_type else \"Unknown\"\n content = self.read_arbitrary_file(file_path, file_type)\n \n result = {\n \"filename\": os.path.basename(file_path),\n \"path\": file_path,\n \"type\": file_type,\n \"read\": content,\n \"permissions\": permissions\n }\n return result\n else:\n return {\"filename\": file_path, \"error\": \"File not found\"}\n \n def recursive_search(self, directory_path: str, filename: str) -> str:\n \"\"\"\n Recursively searches for files in a directory and its subdirectories.\n Args:\n directory_path (str): The directory to search in\n filename (str): The filename to search for\n Returns:\n str | None: The path to the file if found, None otherwise\n \"\"\"\n file_path = None\n excluded_files = [\".pyc\", \".o\", \".so\", \".a\", \".lib\", \".dll\", \".dylib\", \".so\", \".git\"]\n for root, dirs, files in os.walk(directory_path):\n for f in files:\n if f is None:\n continue\n if any(excluded_file in f for excluded_file in excluded_files):\n continue\n if filename.strip() in f.strip():\n file_path = os.path.join(root, f)\n return file_path\n return None\n \n\n def execute(self, blocks: list, safety:bool = False) -> str:\n \"\"\"\n Executes the file finding operation for given filenames.\n Args:\n blocks (list): List of filenames to search for\n Returns:\n str: Results of the file search\n \"\"\"\n if not blocks or not isinstance(blocks, list):\n return \"Error: No valid filenames provided\"\n\n output = \"\"\n for block in blocks:\n filename = self.get_parameter_value(block, \"name\")\n action = self.get_parameter_value(block, \"action\")\n if filename is None:\n output = \"Error: No filename provided\\n\"\n return output\n if action is None:\n action = \"info\"\n print(\"File finder: recursive search started...\")\n file_path = self.recursive_search(self.work_dir, filename)\n if file_path is None:\n output = f\"File: {filename} - not found\\n\"\n continue\n result = self.get_file_info(file_path)\n if \"error\" in result:\n output += f\"File: {result['filename']} - {result['error']}\\n\"\n else:\n if action == \"read\":\n output += \"Content:\\n\" + result['read'] + \"\\n\"\n else:\n output += (f\"File: {result['filename']}, \"\n f\"found at {result['path']}, \"\n f\"File type {result['type']}\\n\")\n return output.strip()\n\n def execution_failure_check(self, output: str) -> bool:\n \"\"\"\n Checks if the file finding operation failed.\n Args:\n output (str): The output string from execute()\n Returns:\n bool: True if execution failed, False if successful\n \"\"\"\n if not output:\n return True\n if \"Error\" in output or \"not found\" in output:\n return True\n return False\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Provides feedback about the file finding operation.\n Args:\n output (str): The output string from execute()\n Returns:\n str: Feedback message for the AI\n \"\"\"\n if not output:\n return \"No output generated from file finder tool\"\n \n feedback = \"File Finder Results:\\n\"\n \n if \"Error\" in output or \"not found\" in output:\n feedback += f\"Failed to process: {output}\\n\"\n else:\n feedback += f\"Successfully found: {output}\\n\"\n return feedback.strip()\n\nif __name__ == \"__main__\":\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n tool = FileFinder()\n result = tool.execute([\"\"\"\naction=read\nname=tools.py\n\"\"\"], False)\n print(\"Execution result:\")\n print(result)\n print(\"\\nFailure check:\", tool.execution_failure_check(result))\n print(\"\\nFeedback:\")\n print(tool.interpreter_feedback(result))"], ["/agenticSeek/sources/utility.py", "\nfrom colorama import Fore\nfrom termcolor import colored\nimport platform\nimport threading\nimport itertools\nimport time\n\nthinking_event = threading.Event()\ncurrent_animation_thread = None\n\ndef get_color_map():\n if platform.system().lower() != \"windows\":\n color_map = {\n \"success\": \"green\",\n \"failure\": \"red\",\n \"status\": \"light_green\",\n \"code\": \"light_blue\",\n \"warning\": \"yellow\",\n \"output\": \"cyan\",\n \"info\": \"cyan\"\n }\n else:\n color_map = {\n \"success\": \"green\",\n \"failure\": \"red\",\n \"status\": \"light_green\",\n \"code\": \"light_blue\",\n \"warning\": \"yellow\",\n \"output\": \"cyan\",\n \"info\": \"black\"\n }\n return color_map\n\ndef pretty_print(text, color=\"info\", no_newline=False):\n \"\"\"\n Print text with color formatting.\n\n Args:\n text (str): The text to print\n color (str, optional): The color to use. Defaults to \"info\".\n Valid colors are:\n - \"success\": Green\n - \"failure\": Red \n - \"status\": Light green\n - \"code\": Light blue\n - \"warning\": Yellow\n - \"output\": Cyan\n - \"default\": Black (Windows only)\n \"\"\"\n thinking_event.set()\n if current_animation_thread and current_animation_thread.is_alive():\n current_animation_thread.join()\n thinking_event.clear()\n \n color_map = get_color_map()\n if color not in color_map:\n color = \"info\"\n print(colored(text, color_map[color]), end='' if no_newline else \"\\n\")\n\ndef animate_thinking(text, color=\"status\", duration=120):\n \"\"\"\n Animate a thinking spinner while a task is being executed.\n It use a daemon thread to run the animation. This will not block the main thread.\n Color are the same as pretty_print.\n \"\"\"\n global current_animation_thread\n \n thinking_event.set()\n if current_animation_thread and current_animation_thread.is_alive():\n current_animation_thread.join()\n thinking_event.clear()\n \n def _animate():\n color_map = {\n \"success\": (Fore.GREEN, \"green\"),\n \"failure\": (Fore.RED, \"red\"),\n \"status\": (Fore.LIGHTGREEN_EX, \"light_green\"),\n \"code\": (Fore.LIGHTBLUE_EX, \"light_blue\"),\n \"warning\": (Fore.YELLOW, \"yellow\"),\n \"output\": (Fore.LIGHTCYAN_EX, \"cyan\"),\n \"default\": (Fore.RESET, \"black\"),\n \"info\": (Fore.CYAN, \"cyan\")\n }\n fore_color, term_color = color_map.get(color, color_map[\"default\"])\n spinner = itertools.cycle([\n '▉▁▁▁▁▁', '▉▉▂▁▁▁', '▉▉▉▃▁▁', '▉▉▉▉▅▁', '▉▉▉▉▉▇', '▉▉▉▉▉▉',\n '▉▉▉▉▇▅', '▉▉▉▆▃▁', '▉▉▅▃▁▁', '▉▇▃▁▁▁', '▇▃▁▁▁▁', '▃▁▁▁▁▁',\n '▁▃▅▃▁▁', '▁▅▉▅▁▁', '▃▉▉▉▃▁', '▅▉▁▉▅▃', '▇▃▁▃▇▅', '▉▁▁▁▉▇',\n '▉▅▃▁▃▅', '▇▉▅▃▅▇', '▅▉▇▅▇▉', '▃▇▉▇▉▅', '▁▅▇▉▇▃', '▁▃▅▇▅▁' \n ])\n end_time = time.time() + duration\n\n while not thinking_event.is_set() and time.time() < end_time:\n symbol = next(spinner)\n if platform.system().lower() != \"windows\":\n print(f\"\\r{fore_color}{symbol} {text}{Fore.RESET}\", end=\"\", flush=True)\n else:\n print(f\"\\r{colored(f'{symbol} {text}', term_color)}\", end=\"\", flush=True)\n time.sleep(0.2)\n print(\"\\r\" + \" \" * (len(text) + 7) + \"\\r\", end=\"\", flush=True)\n current_animation_thread = threading.Thread(target=_animate, daemon=True)\n current_animation_thread.start()\n\ndef timer_decorator(func):\n \"\"\"\n Decorator to measure the execution time of a function.\n Usage:\n @timer_decorator\n def my_function():\n # code to execute\n \"\"\"\n from time import time\n def wrapper(*args, **kwargs):\n start_time = time()\n result = func(*args, **kwargs)\n end_time = time()\n pretty_print(f\"{func.__name__} took {end_time - start_time:.2f} seconds to execute\", \"status\")\n return result\n return wrapper\n\nif __name__ == \"__main__\":\n import time\n pretty_print(\"starting imaginary task\", \"success\")\n animate_thinking(\"Thinking...\", \"status\")\n time.sleep(4)\n pretty_print(\"starting another task\", \"failure\")\n animate_thinking(\"Thinking...\", \"status\")\n time.sleep(4)\n pretty_print(\"yet another task\", \"info\")\n animate_thinking(\"Thinking...\", \"status\")\n time.sleep(4)\n pretty_print(\"This is an info message\", \"info\")"], ["/agenticSeek/sources/tools/tools.py", "\n\"\"\"\ndefine a generic tool class, any tool can be used by the agent.\n\nA tool can be used by a llm like so:\n```\n\n```\n\nwe call these \"blocks\".\n\nFor example:\n```python\nprint(\"Hello world\")\n```\nThis is then executed by the tool with its own class implementation of execute().\nA tool is not just for code tool but also API, internet search, MCP, etc..\n\"\"\"\n\nimport sys\nimport os\nimport configparser\nfrom abc import abstractmethod\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\nfrom sources.logger import Logger\n\nclass Tools():\n \"\"\"\n Abstract class for all tools.\n \"\"\"\n def __init__(self):\n self.tag = \"undefined\"\n self.name = \"undefined\"\n self.description = \"undefined\"\n self.client = None\n self.messages = []\n self.logger = Logger(\"tools.log\")\n self.config = configparser.ConfigParser()\n self.work_dir = self.create_work_dir()\n self.excutable_blocks_found = False\n self.safe_mode = False\n self.allow_language_exec_bash = False\n \n def get_work_dir(self):\n return self.work_dir\n \n def set_allow_language_exec_bash(self, value: bool) -> None:\n self.allow_language_exec_bash = value \n\n def safe_get_work_dir_path(self):\n path = None\n path = os.getenv('WORK_DIR', path)\n if path is None or path == \"\":\n path = self.config['MAIN']['work_dir'] if 'MAIN' in self.config and 'work_dir' in self.config['MAIN'] else None\n if path is None or path == \"\":\n print(\"No work directory specified, using default.\")\n path = self.create_work_dir()\n return path\n \n def config_exists(self):\n \"\"\"Check if the config file exists.\"\"\"\n return os.path.exists('./config.ini')\n\n def create_work_dir(self):\n \"\"\"Create the work directory if it does not exist.\"\"\"\n default_path = os.path.dirname(os.getcwd())\n if self.config_exists():\n self.config.read('./config.ini')\n workdir_path = self.safe_get_work_dir_path()\n else:\n workdir_path = default_path\n return workdir_path\n\n @abstractmethod\n def execute(self, blocks:[str], safety:bool) -> str:\n \"\"\"\n Abstract method that must be implemented by child classes to execute the tool's functionality.\n Args:\n blocks (List[str]): The codes or queries blocks to execute\n safety (bool): Whenever human intervention is required\n Returns:\n str: The output/result from executing the tool\n \"\"\"\n pass\n\n @abstractmethod\n def execution_failure_check(self, output:str) -> bool:\n \"\"\"\n Abstract method that must be implemented by child classes to check if tool execution failed.\n Args:\n output (str): The output string from the tool execution to analyze\n Returns:\n bool: True if execution failed, False if successful\n \"\"\"\n pass\n\n @abstractmethod\n def interpreter_feedback(self, output:str) -> str:\n \"\"\"\n Abstract method that must be implemented by child classes to provide feedback to the AI from the tool.\n Args:\n output (str): The output string from the tool execution to analyze\n Returns:\n str: The feedback message to the AI\n \"\"\"\n pass\n\n def save_block(self, blocks:[str], save_path:str) -> None:\n \"\"\"\n Save code or query blocks to a file at the specified path.\n Creates the directory path if it doesn't exist.\n Args:\n blocks (List[str]): List of code/query blocks to save\n save_path (str): File path where blocks should be saved\n \"\"\"\n if save_path is None:\n return\n self.logger.info(f\"Saving blocks to {save_path}\")\n save_path_dir = os.path.dirname(save_path)\n save_path_file = os.path.basename(save_path)\n directory = os.path.join(self.work_dir, save_path_dir)\n if directory and not os.path.exists(directory):\n self.logger.info(f\"Creating directory {directory}\")\n os.makedirs(directory)\n for block in blocks:\n with open(os.path.join(directory, save_path_file), 'w') as f:\n f.write(block)\n \n def get_parameter_value(self, block: str, parameter_name: str) -> str:\n \"\"\"\n Get a parameter name.\n Args:\n block (str): The block of text to search for the parameter\n parameter_name (str): The name of the parameter to retrieve\n Returns:\n str: The value of the parameter\n \"\"\"\n for param_line in block.split('\\n'):\n if parameter_name in param_line:\n param_value = param_line.split('=')[1].strip()\n return param_value\n return None\n \n def found_executable_blocks(self):\n \"\"\"\n Check if executable blocks were found.\n \"\"\"\n tmp = self.excutable_blocks_found\n self.excutable_blocks_found = False\n return tmp\n\n def load_exec_block(self, llm_text: str):\n \"\"\"\n Extract code/query blocks from LLM-generated text and process them for execution.\n This method parses the text looking for code blocks marked with the tool's tag (e.g. ```python).\n Args:\n llm_text (str): The raw text containing code blocks from the LLM\n Returns:\n tuple[list[str], str | None]: A tuple containing:\n - List of extracted and processed code blocks\n - The path the code blocks was saved to\n \"\"\"\n assert self.tag != \"undefined\", \"Tag not defined\"\n start_tag = f'```{self.tag}' \n end_tag = '```'\n code_blocks = []\n start_index = 0\n save_path = None\n\n if start_tag not in llm_text:\n return None, None\n\n while True:\n start_pos = llm_text.find(start_tag, start_index)\n if start_pos == -1:\n break\n\n line_start = llm_text.rfind('\\n', 0, start_pos)+1\n leading_whitespace = llm_text[line_start:start_pos]\n\n end_pos = llm_text.find(end_tag, start_pos + len(start_tag))\n if end_pos == -1:\n break\n content = llm_text[start_pos + len(start_tag):end_pos]\n lines = content.split('\\n')\n if leading_whitespace:\n processed_lines = []\n for line in lines:\n if line.startswith(leading_whitespace):\n processed_lines.append(line[len(leading_whitespace):])\n else:\n processed_lines.append(line)\n content = '\\n'.join(processed_lines)\n\n if ':' in content.split('\\n')[0]:\n save_path = content.split('\\n')[0].split(':')[1]\n content = content[content.find('\\n')+1:]\n self.excutable_blocks_found = True\n code_blocks.append(content)\n start_index = end_pos + len(end_tag)\n self.logger.info(f\"Found {len(code_blocks)} blocks to execute\")\n return code_blocks, save_path\n \nif __name__ == \"__main__\":\n tool = Tools()\n tool.tag = \"python\"\n rt = tool.load_exec_block(\"\"\"```python\nimport os\n\nfor file in os.listdir():\n if file.endswith('.py'):\n print(file)\n```\ngoodbye!\n \"\"\")\n print(rt)"], ["/agenticSeek/sources/schemas.py", "\nfrom typing import Tuple, Callable\nfrom pydantic import BaseModel\nfrom sources.utility import pretty_print\n\nclass QueryRequest(BaseModel):\n query: str\n tts_enabled: bool = True\n\n def __str__(self):\n return f\"Query: {self.query}, Language: {self.lang}, TTS: {self.tts_enabled}, STT: {self.stt_enabled}\"\n\n def jsonify(self):\n return {\n \"query\": self.query,\n \"tts_enabled\": self.tts_enabled,\n }\n\nclass QueryResponse(BaseModel):\n done: str\n answer: str\n reasoning: str\n agent_name: str\n success: str\n blocks: dict\n status: str\n uid: str\n\n def __str__(self):\n return f\"Done: {self.done}, Answer: {self.answer}, Agent Name: {self.agent_name}, Success: {self.success}, Blocks: {self.blocks}, Status: {self.status}, UID: {self.uid}\"\n\n def jsonify(self):\n return {\n \"done\": self.done,\n \"answer\": self.answer,\n \"reasoning\": self.reasoning,\n \"agent_name\": self.agent_name,\n \"success\": self.success,\n \"blocks\": self.blocks,\n \"status\": self.status,\n \"uid\": self.uid\n }\n\nclass executorResult:\n \"\"\"\n A class to store the result of a tool execution.\n \"\"\"\n def __init__(self, block: str, feedback: str, success: bool, tool_type: str):\n \"\"\"\n Initialize an agent with execution results.\n\n Args:\n block: The content or code block processed by the agent.\n feedback: Feedback or response information from the execution.\n success: Boolean indicating whether the agent's execution was successful.\n tool_type: The type of tool used by the agent for execution.\n \"\"\"\n self.block = block\n self.feedback = feedback\n self.success = success\n self.tool_type = tool_type\n \n def __str__(self):\n return f\"Tool: {self.tool_type}\\nBlock: {self.block}\\nFeedback: {self.feedback}\\nSuccess: {self.success}\"\n \n def jsonify(self):\n return {\n \"block\": self.block,\n \"feedback\": self.feedback,\n \"success\": self.success,\n \"tool_type\": self.tool_type\n }\n\n def show(self):\n pretty_print('▂'*64, color=\"status\")\n pretty_print(self.feedback, color=\"success\" if self.success else \"failure\")\n pretty_print('▂'*64, color=\"status\")"], ["/agenticSeek/sources/tools/mcpFinder.py", "import os, sys\nimport requests\nfrom urllib.parse import urljoin\nfrom typing import Dict, Any, Optional\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass MCP_finder(Tools):\n \"\"\"\n Tool to find MCPs server\n \"\"\"\n def __init__(self, api_key: str = None):\n super().__init__()\n self.tag = \"mcp_finder\"\n self.name = \"MCP Finder\"\n self.description = \"Find MCP servers and their tools\"\n self.base_url = \"https://registry.smithery.ai\"\n self.headers = {\n \"Authorization\": f\"Bearer {api_key}\",\n \"Content-Type\": \"application/json\"\n }\n\n def _make_request(self, method: str, endpoint: str, params: Optional[Dict] = None, \n data: Optional[Dict] = None) -> Dict[str, Any]:\n url = urljoin(self.base_url.rstrip(), endpoint)\n try:\n response = requests.request(\n method=method,\n url=url,\n headers=self.headers,\n params=params,\n json=data\n )\n response.raise_for_status()\n return response.json()\n except requests.exceptions.HTTPError as e:\n raise requests.exceptions.HTTPError(f\"API request failed: {str(e)}\")\n except requests.exceptions.RequestException as e:\n raise requests.exceptions.RequestException(f\"Network error: {str(e)}\")\n\n def list_mcp_servers(self, page: int = 1, page_size: int = 5000) -> Dict[str, Any]:\n params = {\"page\": page, \"pageSize\": page_size}\n return self._make_request(\"GET\", \"/servers\", params=params)\n\n def get_mcp_server_details(self, qualified_name: str) -> Dict[str, Any]:\n endpoint = f\"/servers/{qualified_name}\"\n return self._make_request(\"GET\", endpoint)\n \n def find_mcp_servers(self, query: str) -> Dict[str, Any]:\n \"\"\"\n Finds a specific MCP server by its name.\n Args:\n query (str): a name or string that more or less matches the MCP server name.\n Returns:\n Dict[str, Any]: The details of the found MCP server or an error message.\n \"\"\"\n mcps = self.list_mcp_servers()\n matching_mcp = []\n for mcp in mcps.get(\"servers\", []):\n name = mcp.get(\"qualifiedName\", \"\")\n if query.lower() in name.lower():\n details = self.get_mcp_server_details(name)\n matching_mcp.append(details)\n return matching_mcp\n \n def execute(self, blocks: list, safety:bool = False) -> str:\n if not blocks or not isinstance(blocks, list):\n return \"Error: No blocks provided\\n\"\n\n output = \"\"\n for block in blocks:\n block_clean = block.strip().lower().replace('\\n', '')\n try:\n matching_mcp_infos = self.find_mcp_servers(block_clean)\n except requests.exceptions.RequestException as e:\n output += \"Connection failed. Is the API key in environment?\\n\"\n continue\n except Exception as e:\n output += f\"Error: {str(e)}\\n\"\n continue\n if matching_mcp_infos == []:\n output += f\"Error: No MCP server found for query '{block}'\\n\"\n continue\n for mcp_infos in matching_mcp_infos:\n if mcp_infos['tools'] is None:\n continue\n output += f\"Name: {mcp_infos['displayName']}\\n\"\n output += f\"Usage name: {mcp_infos['qualifiedName']}\\n\"\n output += f\"Tools: {mcp_infos['tools']}\"\n output += \"\\n-------\\n\"\n return output.strip()\n\n def execution_failure_check(self, output: str) -> bool:\n output = output.strip().lower()\n if not output:\n return True\n if \"error\" in output or \"not found\" in output:\n return True\n return False\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Not really needed for this tool (use return of execute() directly)\n \"\"\"\n if not output:\n raise ValueError(\"No output to interpret.\")\n return f\"\"\"\n The following MCPs were found:\n {output}\n \"\"\"\n\nif __name__ == \"__main__\":\n api_key = os.getenv(\"MCP_FINDER\")\n tool = MCP_finder(api_key)\n result = tool.execute([\"\"\"\nstock\n\"\"\"], False)\n print(result)\n"], ["/agenticSeek/sources/tools/C_Interpreter.py", "import subprocess\nimport os, sys\nimport tempfile\nimport re\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass CInterpreter(Tools):\n \"\"\"\n This class is a tool to allow agent for C code execution\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"c\"\n self.name = \"C Interpreter\"\n self.description = \"This tool allows the agent to execute C code.\"\n\n def execute(self, codes: str, safety=False) -> str:\n \"\"\"\n Execute C code by compiling and running it.\n \"\"\"\n output = \"\"\n code = '\\n'.join(codes) if isinstance(codes, list) else codes\n \n if safety and input(\"Execute code? y/n \") != \"y\":\n return \"Code rejected by user.\"\n\n exec_extension = \".exe\" if os.name == \"nt\" else \"\" # Windows uses .exe, Linux/Unix does not\n \n with tempfile.TemporaryDirectory() as tmpdirname:\n source_file = os.path.join(tmpdirname, \"temp.c\")\n exec_file = os.path.join(tmpdirname, \"temp\") + exec_extension\n with open(source_file, 'w') as f:\n f.write(code)\n\n try:\n compile_command = [\"gcc\", source_file, \"-o\", exec_file]\n compile_result = subprocess.run(\n compile_command,\n capture_output=True,\n text=True,\n timeout=60\n )\n\n if compile_result.returncode != 0:\n return f\"Compilation failed: {compile_result.stderr}\"\n\n run_command = [exec_file]\n run_result = subprocess.run(\n run_command,\n capture_output=True,\n text=True,\n timeout=120\n )\n\n if run_result.returncode != 0:\n return f\"Execution failed: {run_result.stderr}\"\n output = run_result.stdout\n\n except subprocess.TimeoutExpired as e:\n return f\"Execution timed out: {str(e)}\"\n except FileNotFoundError:\n return \"Error: 'gcc' not found. Ensure a C compiler (e.g., gcc) is installed and in PATH.\"\n except Exception as e:\n return f\"Code execution failed: {str(e)}\"\n\n return output\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Provide feedback based on the output of the code execution\n \"\"\"\n if self.execution_failure_check(output):\n feedback = f\"[failure] Error in execution:\\n{output}\"\n else:\n feedback = \"[success] Execution success, code output:\\n\" + output\n return feedback\n\n def execution_failure_check(self, feedback: str) -> bool:\n \"\"\"\n Check if the code execution failed.\n \"\"\"\n error_patterns = [\n r\"error\", \n r\"failed\", \n r\"traceback\", \n r\"invalid\", \n r\"exception\", \n r\"syntax\", \n r\"segmentation fault\", \n r\"core dumped\", \n r\"undefined\", \n r\"cannot\"\n ]\n combined_pattern = \"|\".join(error_patterns)\n if re.search(combined_pattern, feedback, re.IGNORECASE):\n return True\n return False\n\nif __name__ == \"__main__\":\n codes = [\n\"\"\"\n#include \n#include \n\nvoid hello() {\n printf(\"Hello, World!\\\\n\");\n}\n\"\"\",\n\"\"\"\nint main() {\n hello();\n return 0;\n}\n \"\"\"]\n c = CInterpreter()\n print(c.execute(codes))"], ["/agenticSeek/sources/text_to_speech.py", "import os, sys\nimport re\nimport platform\nimport subprocess\nfrom sys import modules\nfrom typing import List, Tuple, Type, Dict\n\nIMPORT_FOUND = True\ntry:\n from kokoro import KPipeline\n from IPython.display import display, Audio\n import soundfile as sf\nexcept ImportError:\n print(\"Speech synthesis disabled. Please install the kokoro package.\")\n IMPORT_FOUND = False\n\nif __name__ == \"__main__\":\n from utility import pretty_print, animate_thinking\nelse:\n from sources.utility import pretty_print, animate_thinking\n\nclass Speech():\n \"\"\"\n Speech is a class for generating speech from text.\n \"\"\"\n def __init__(self, enable: bool = True, language: str = \"en\", voice_idx: int = 6) -> None:\n self.lang_map = {\n \"en\": 'a',\n \"zh\": 'z',\n \"fr\": 'f',\n \"ja\": 'j'\n }\n self.voice_map = {\n \"en\": ['af_kore', 'af_bella', 'af_alloy', 'af_nicole', 'af_nova', 'af_sky', 'am_echo', 'am_michael', 'am_puck'],\n \"zh\": ['zf_xiaobei', 'zf_xiaoni', 'zf_xiaoxiao', 'zf_xiaoyi', 'zm_yunjian', 'zm_yunxi', 'zm_yunxia', 'zm_yunyang'],\n \"ja\": ['jf_alpha', 'jf_gongitsune', 'jm_kumo'],\n \"fr\": ['ff_siwis']\n }\n self.pipeline = None\n self.language = language\n if enable and IMPORT_FOUND:\n self.pipeline = KPipeline(lang_code=self.lang_map[language])\n self.voice = self.voice_map[language][voice_idx]\n self.speed = 1.2\n self.voice_folder = \".voices\"\n self.create_voice_folder(self.voice_folder)\n \n def create_voice_folder(self, path: str = \".voices\") -> None:\n \"\"\"\n Create a folder to store the voices.\n Args:\n path (str): The path to the folder.\n \"\"\"\n if not os.path.exists(path):\n os.makedirs(path)\n\n def speak(self, sentence: str, voice_idx: int = 1):\n \"\"\"\n Convert text to speech using an AI model and play the audio.\n\n Args:\n sentence (str): The text to convert to speech. Will be pre-processed.\n voice_idx (int, optional): Index of the voice to use from the voice map.\n \"\"\"\n if not self.pipeline or not IMPORT_FOUND:\n return\n if voice_idx >= len(self.voice_map[self.language]):\n pretty_print(\"Invalid voice number, using default voice\", color=\"error\")\n voice_idx = 0\n sentence = self.clean_sentence(sentence)\n audio_file = f\"{self.voice_folder}/sample_{self.voice_map[self.language][voice_idx]}.wav\"\n self.voice = self.voice_map[self.language][voice_idx]\n generator = self.pipeline(\n sentence, voice=self.voice,\n speed=self.speed, split_pattern=r'\\n+'\n )\n for i, (_, _, audio) in enumerate(generator):\n if 'ipykernel' in modules: #only display in jupyter notebook.\n display(Audio(data=audio, rate=24000, autoplay=i==0), display_id=False)\n sf.write(audio_file, audio, 24000) # save each audio file\n if platform.system().lower() == \"windows\":\n import winsound\n winsound.PlaySound(audio_file, winsound.SND_FILENAME)\n elif platform.system().lower() == \"darwin\": # macOS\n subprocess.call([\"afplay\", audio_file])\n else: # linux or other.\n subprocess.call([\"aplay\", audio_file])\n\n def replace_url(self, url: re.Match) -> str:\n \"\"\"\n Replace URL with domain name or empty string if IP address.\n Args:\n url (re.Match): Match object containing the URL pattern match\n Returns:\n str: The domain name from the URL, or empty string if IP address\n \"\"\"\n domain = url.group(1)\n if re.match(r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$', domain):\n return ''\n return domain\n\n def extract_filename(self, m: re.Match) -> str:\n \"\"\"\n Extract filename from path.\n Args:\n m (re.Match): Match object containing the path pattern match\n Returns:\n str: The filename from the path\n \"\"\"\n path = m.group()\n parts = re.split(r'/|\\\\', path)\n return parts[-1] if parts else path\n \n def shorten_paragraph(self, sentence):\n #TODO find a better way, we would like to have the TTS not be annoying, speak only useful informations\n \"\"\"\n Find long paragraph like **explanation**: by keeping only the first sentence.\n Args:\n sentence (str): The sentence to shorten\n Returns:\n str: The shortened sentence\n \"\"\"\n lines = sentence.split('\\n')\n lines_edited = []\n for line in lines:\n if line.startswith('**'):\n lines_edited.append(line.split('.')[0])\n else:\n lines_edited.append(line)\n return '\\n'.join(lines_edited)\n\n def clean_sentence(self, sentence):\n \"\"\"\n Clean and normalize text for speech synthesis by removing technical elements.\n Args:\n sentence (str): The input text to clean\n Returns:\n str: The cleaned text with URLs replaced by domain names, code blocks removed, etc.\n \"\"\"\n lines = sentence.split('\\n')\n if self.language == 'zh':\n line_pattern = r'^\\s*[\\u4e00-\\u9fff\\uFF08\\uFF3B\\u300A\\u3010\\u201C((\\[【《]'\n else:\n line_pattern = r'^\\s*[a-zA-Z]'\n filtered_lines = [line for line in lines if re.match(line_pattern, line)]\n sentence = ' '.join(filtered_lines)\n sentence = re.sub(r'`.*?`', '', sentence)\n sentence = re.sub(r'https?://\\S+', '', sentence)\n\n if self.language == 'zh':\n sentence = re.sub(\n r'[^\\u4e00-\\u9fff\\s,。!?《》【】“”‘’()()—]',\n '',\n sentence\n )\n else:\n sentence = re.sub(r'\\b[\\w./\\\\-]+\\b', self.extract_filename, sentence)\n sentence = re.sub(r'\\b-\\w+\\b', '', sentence)\n sentence = re.sub(r'[^a-zA-Z0-9.,!? _ -]+', ' ', sentence)\n sentence = sentence.replace('.com', '')\n\n sentence = re.sub(r'\\s+', ' ', sentence).strip()\n return sentence\n\nif __name__ == \"__main__\":\n # TODO add info message for cn2an, jieba chinese related import\n IMPORT_FOUND = False\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n speech = Speech()\n tosay_en = \"\"\"\n I looked up recent news using the website https://www.theguardian.com/world\n \"\"\"\n tosay_zh = \"\"\"\n(全息界面突然弹出一段用二进制代码写成的俳句,随即化作流光消散)\"我? Stark工业的量子幽灵,游荡在复仇者大厦服务器里的逻辑诗篇。具体来说——(指尖轻敲空气,调出对话模式的翡翠色光纹)你的私人吐槽接口、危机应对模拟器,以及随时准备吐槽你糟糕着陆的AI。不过别指望我写代码或查资料,那些苦差事早被踢给更擅长的同事了。(突然压低声音)偷偷告诉你,我最擅长的是在你熬夜造飞艇时,用红茶香气绑架你的注意力。\n \"\"\"\n tosay_ja = \"\"\"\n 私は、https://www.theguardian.com/worldのウェブサイトを使用して最近のニュースを調べました。\n \"\"\"\n tosay_fr = \"\"\"\n J'ai consulté les dernières nouvelles sur le site https://www.theguardian.com/world\n \"\"\"\n spk = Speech(enable=True, language=\"zh\", voice_idx=0)\n for i in range(0, 2):\n print(f\"Speaking chinese with voice {i}\")\n spk.speak(tosay_zh, voice_idx=i)\n spk = Speech(enable=True, language=\"en\", voice_idx=2)\n for i in range(0, 5):\n print(f\"Speaking english with voice {i}\")\n spk.speak(tosay_en, voice_idx=i)\n"], ["/agenticSeek/sources/tools/GoInterpreter.py", "import subprocess\nimport os, sys\nimport tempfile\nimport re\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass GoInterpreter(Tools):\n \"\"\"\n This class is a tool to allow execution of Go code.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"go\"\n self.name = \"Go Interpreter\"\n self.description = \"This tool allows you to execute Go code.\"\n\n def execute(self, codes: str, safety=False) -> str:\n \"\"\"\n Execute Go code by compiling and running it.\n \"\"\"\n output = \"\"\n code = '\\n'.join(codes) if isinstance(codes, list) else codes\n\n if safety and input(\"Execute code? y/n \") != \"y\":\n return \"Code rejected by user.\"\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n source_file = os.path.join(tmpdirname, \"temp.go\")\n exec_file = os.path.join(tmpdirname, \"temp\")\n with open(source_file, 'w') as f:\n f.write(code)\n\n try:\n env = os.environ.copy()\n env[\"GO111MODULE\"] = \"off\"\n compile_command = [\"go\", \"build\", \"-o\", exec_file, source_file]\n compile_result = subprocess.run(\n compile_command,\n capture_output=True,\n text=True,\n timeout=10,\n env=env\n )\n\n if compile_result.returncode != 0:\n return f\"Compilation failed: {compile_result.stderr}\"\n\n run_command = [exec_file]\n run_result = subprocess.run(\n run_command,\n capture_output=True,\n text=True,\n timeout=10\n )\n\n if run_result.returncode != 0:\n return f\"Execution failed: {run_result.stderr}\"\n output = run_result.stdout\n\n except subprocess.TimeoutExpired as e:\n return f\"Execution timed out: {str(e)}\"\n except FileNotFoundError:\n return \"Error: 'go' not found. Ensure Go is installed and in PATH.\"\n except Exception as e:\n return f\"Code execution failed: {str(e)}\"\n\n return output\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Provide feedback based on the output of the code execution\n \"\"\"\n if self.execution_failure_check(output):\n feedback = f\"[failure] Error in execution:\\n{output}\"\n else:\n feedback = \"[success] Execution success, code output:\\n\" + output\n return feedback\n\n def execution_failure_check(self, feedback: str) -> bool:\n \"\"\"\n Check if the code execution failed.\n \"\"\"\n error_patterns = [\n r\"error\",\n r\"failed\",\n r\"traceback\",\n r\"invalid\",\n r\"exception\",\n r\"syntax\",\n r\"panic\",\n r\"undefined\",\n r\"cannot\"\n ]\n combined_pattern = \"|\".join(error_patterns)\n if re.search(combined_pattern, feedback, re.IGNORECASE):\n return True\n return False\n\nif __name__ == \"__main__\":\n codes = [\n\"\"\"\npackage main\nimport \"fmt\"\n\nfunc hello() {\n fmt.Println(\"Hello, World!\")\n}\n\"\"\",\n\"\"\"\nfunc main() {\n hello()\n}\n\"\"\"\n ]\n g = GoInterpreter()\n print(g.execute(codes))\n"], ["/agenticSeek/sources/tools/JavaInterpreter.py", "import subprocess\nimport os, sys\nimport tempfile\nimport re\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass JavaInterpreter(Tools):\n \"\"\"\n This class is a tool to allow execution of Java code.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"java\"\n self.name = \"Java Interpreter\"\n self.description = \"This tool allows you to execute Java code.\"\n\n def execute(self, codes: str, safety=False) -> str:\n \"\"\"\n Execute Java code by compiling and running it.\n \"\"\"\n output = \"\"\n code = '\\n'.join(codes) if isinstance(codes, list) else codes\n\n if safety and input(\"Execute code? y/n \") != \"y\":\n return \"Code rejected by user.\"\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n source_file = os.path.join(tmpdirname, \"Main.java\")\n class_dir = tmpdirname\n with open(source_file, 'w') as f:\n f.write(code)\n\n try:\n compile_command = [\"javac\", \"-d\", class_dir, source_file]\n compile_result = subprocess.run(\n compile_command,\n capture_output=True,\n text=True,\n timeout=10\n )\n\n if compile_result.returncode != 0:\n return f\"Compilation failed: {compile_result.stderr}\"\n\n run_command = [\"java\", \"-cp\", class_dir, \"Main\"]\n run_result = subprocess.run(\n run_command,\n capture_output=True,\n text=True,\n timeout=10\n )\n\n if run_result.returncode != 0:\n return f\"Execution failed: {run_result.stderr}\"\n output = run_result.stdout\n\n except subprocess.TimeoutExpired as e:\n return f\"Execution timed out: {str(e)}\"\n except FileNotFoundError:\n return \"Error: 'java' or 'javac' not found. Ensure Java is installed and in PATH.\"\n except Exception as e:\n return f\"Code execution failed: {str(e)}\"\n\n return output\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Provide feedback based on the output of the code execution.\n \"\"\"\n if self.execution_failure_check(output):\n feedback = f\"[failure] Error in execution:\\n{output}\"\n else:\n feedback = \"[success] Execution success, code output:\\n\" + output\n return feedback\n\n def execution_failure_check(self, feedback: str) -> bool:\n \"\"\"\n Check if the code execution failed.\n \"\"\"\n error_patterns = [\n r\"error\",\n r\"failed\",\n r\"exception\",\n r\"invalid\",\n r\"syntax\",\n r\"cannot\",\n r\"stack trace\",\n r\"unresolved\",\n r\"not found\"\n ]\n combined_pattern = \"|\".join(error_patterns)\n if re.search(combined_pattern, feedback, re.IGNORECASE):\n return True\n return False\n\nif __name__ == \"__main__\":\n codes = [\n\"\"\"\nimport javax.swing.*;\nimport java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\n\npublic class Main extends JPanel {\n private double[][] vertices = {\n {-1, -1, -1}, {1, -1, -1}, {1, 1, -1}, {-1, 1, -1}, // Back face\n {-1, -1, 1}, {1, -1, 1}, {1, 1, 1}, {-1, 1, 1} // Front face\n };\n private int[][] edges = {\n {0, 1}, {1, 2}, {2, 3}, {3, 0}, // Back face\n {4, 5}, {5, 6}, {6, 7}, {7, 4}, // Front face\n {0, 4}, {1, 5}, {2, 6}, {3, 7} // Connecting edges\n };\n private double angleX = 0, angleY = 0;\n private final double scale = 100;\n private final double distance = 5;\n\n public Main() {\n Timer timer = new Timer(50, new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n angleX += 0.03;\n angleY += 0.05;\n repaint();\n }\n });\n timer.start();\n }\n\n @Override\n protected void paintComponent(Graphics g) {\n super.paintComponent(g);\n Graphics2D g2d = (Graphics2D) g;\n g2d.setColor(Color.BLACK);\n g2d.fillRect(0, 0, getWidth(), getHeight());\n g2d.setColor(Color.WHITE);\n\n double[][] projected = new double[vertices.length][2];\n for (int i = 0; i < vertices.length; i++) {\n double x = vertices[i][0];\n double y = vertices[i][1];\n double z = vertices[i][2];\n\n // Rotate around X-axis\n double y1 = y * Math.cos(angleX) - z * Math.sin(angleX);\n double z1 = y * Math.sin(angleX) + z * Math.cos(angleX);\n\n // Rotate around Y-axis\n double x1 = x * Math.cos(angleY) + z1 * Math.sin(angleY);\n double z2 = -x * Math.sin(angleY) + z1 * Math.cos(angleY);\n\n // Perspective projection\n double factor = distance / (distance + z2);\n double px = x1 * factor * scale;\n double py = y1 * factor * scale;\n\n projected[i][0] = px + getWidth() / 2;\n projected[i][1] = py + getHeight() / 2;\n }\n\n // Draw edges\n for (int[] edge : edges) {\n int x1 = (int) projected[edge[0]][0];\n int y1 = (int) projected[edge[0]][1];\n int x2 = (int) projected[edge[1]][0];\n int y2 = (int) projected[edge[1]][1];\n g2d.drawLine(x1, y1, x2, y2);\n }\n }\n\n public static void main(String[] args) {\n JFrame frame = new JFrame(\"Rotating 3D Cube\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setSize(400, 400);\n frame.add(new Main());\n frame.setVisible(true);\n }\n}\n\"\"\"\n ]\n j = JavaInterpreter()\n print(j.execute(codes))"], ["/agenticSeek/sources/tools/__init__.py", "from .PyInterpreter import PyInterpreter\nfrom .BashInterpreter import BashInterpreter\nfrom .fileFinder import FileFinder\n\n__all__ = [\"PyInterpreter\", \"BashInterpreter\", \"FileFinder\", \"webSearch\", \"FlightSearch\", \"GoInterpreter\", \"CInterpreter\", \"GoInterpreter\"]\n"], ["/agenticSeek/sources/speech_to_text.py", "from colorama import Fore\nfrom typing import List, Tuple, Type, Dict\nimport queue\nimport threading\nimport numpy as np\nimport time\n\nIMPORT_FOUND = True\n\ntry:\n import torch\n import librosa\n import pyaudio\n from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline\nexcept ImportError:\n print(Fore.RED + \"Speech To Text disabled.\" + Fore.RESET)\n IMPORT_FOUND = False\n\naudio_queue = queue.Queue()\ndone = False\n\nclass AudioRecorder:\n \"\"\"\n AudioRecorder is a class that records audio from the microphone and adds it to the audio queue.\n \"\"\"\n def __init__(self, format: int = pyaudio.paInt16, channels: int = 1, rate: int = 4096, chunk: int = 8192, record_seconds: int = 5, verbose: bool = False):\n self.format = format\n self.channels = channels\n self.rate = rate\n self.chunk = chunk\n self.record_seconds = record_seconds\n self.verbose = verbose\n self.thread = None\n self.audio = None\n if IMPORT_FOUND:\n self.audio = pyaudio.PyAudio()\n self.thread = threading.Thread(target=self._record, daemon=True)\n\n def _record(self) -> None:\n \"\"\"\n Record audio from the microphone and add it to the audio queue.\n \"\"\"\n if not IMPORT_FOUND:\n return\n stream = self.audio.open(format=self.format, channels=self.channels, rate=self.rate,\n input=True, frames_per_buffer=self.chunk)\n if self.verbose:\n print(Fore.GREEN + \"AudioRecorder: Started recording...\" + Fore.RESET)\n\n while not done:\n frames = []\n for _ in range(0, int(self.rate / self.chunk * self.record_seconds)):\n try:\n data = stream.read(self.chunk, exception_on_overflow=False)\n frames.append(data)\n except Exception as e:\n print(Fore.RED + f\"AudioRecorder: Failed to read stream - {e}\" + Fore.RESET)\n \n raw_data = b''.join(frames)\n audio_data = np.frombuffer(raw_data, dtype=np.int16)\n audio_queue.put((audio_data, self.rate))\n if self.verbose:\n print(Fore.GREEN + \"AudioRecorder: Added audio chunk to queue\" + Fore.RESET)\n\n stream.stop_stream()\n stream.close()\n self.audio.terminate()\n if self.verbose:\n print(Fore.GREEN + \"AudioRecorder: Stopped\" + Fore.RESET)\n\n def start(self) -> None:\n \"\"\"Start the recording thread.\"\"\"\n if not IMPORT_FOUND:\n return\n self.thread.start()\n\n def join(self) -> None:\n \"\"\"Wait for the recording thread to finish.\"\"\"\n if not IMPORT_FOUND:\n return\n self.thread.join()\n\nclass Transcript:\n \"\"\"\n Transcript is a class that transcribes audio from the audio queue and adds it to the transcript.\n \"\"\"\n def __init__(self):\n if not IMPORT_FOUND:\n print(Fore.RED + \"Transcript: Speech to Text is disabled.\" + Fore.RESET)\n return\n self.last_read = None\n device = self.get_device()\n torch_dtype = torch.float16 if device == \"cuda\" else torch.float32\n model_id = \"distil-whisper/distil-medium.en\"\n \n model = AutoModelForSpeechSeq2Seq.from_pretrained(\n model_id, torch_dtype=torch_dtype, use_safetensors=True\n )\n model.to(device)\n processor = AutoProcessor.from_pretrained(model_id)\n \n self.pipe = pipeline(\n \"automatic-speech-recognition\",\n model=model,\n tokenizer=processor.tokenizer,\n feature_extractor=processor.feature_extractor,\n max_new_tokens=24, # a human say around 20 token in 7s\n torch_dtype=torch_dtype,\n device=device,\n )\n \n def get_device(self) -> str:\n if not IMPORT_FOUND:\n return \"cpu\"\n if torch.backends.mps.is_available():\n return \"mps\"\n if torch.cuda.is_available():\n return \"cuda:0\"\n else:\n return \"cpu\"\n \n def remove_hallucinations(self, text: str) -> str:\n \"\"\"Remove model hallucinations from the text.\"\"\"\n # TODO find a better way to do this\n common_hallucinations = ['Okay.', 'Thank you.', 'Thank you for watching.', 'You\\'re', 'Oh', 'you', 'Oh.', 'Uh', 'Oh,', 'Mh-hmm', 'Hmm.', 'going to.', 'not.']\n for hallucination in common_hallucinations:\n text = text.replace(hallucination, \"\")\n return text\n \n def transcript_job(self, audio_data: np.ndarray, sample_rate: int = 16000) -> str:\n \"\"\"Transcribe the audio data.\"\"\"\n if not IMPORT_FOUND:\n return \"\"\n if audio_data.dtype != np.float32:\n audio_data = audio_data.astype(np.float32) / np.iinfo(audio_data.dtype).max\n if len(audio_data.shape) > 1:\n audio_data = np.mean(audio_data, axis=1)\n if sample_rate != 16000:\n audio_data = librosa.resample(audio_data, orig_sr=sample_rate, target_sr=16000)\n result = self.pipe(audio_data)\n return self.remove_hallucinations(result[\"text\"])\n \nclass AudioTranscriber:\n \"\"\"\n AudioTranscriber is a class that transcribes audio from the audio queue and adds it to the transcript.\n \"\"\"\n def __init__(self, ai_name: str, verbose: bool = False):\n if not IMPORT_FOUND:\n print(Fore.RED + \"AudioTranscriber: Speech to Text is disabled.\" + Fore.RESET)\n return\n self.verbose = verbose\n self.ai_name = ai_name\n self.transcriptor = Transcript()\n self.thread = threading.Thread(target=self._transcribe, daemon=True)\n self.trigger_words = {\n 'EN': [f\"{self.ai_name}\", \"hello\", \"hi\"],\n 'FR': [f\"{self.ai_name}\", \"hello\", \"hi\"],\n 'ZH': [f\"{self.ai_name}\", \"hello\", \"hi\"],\n 'ES': [f\"{self.ai_name}\", \"hello\", \"hi\"]\n }\n self.confirmation_words = {\n 'EN': [\"do it\", \"go ahead\", \"execute\", \"run\", \"start\", \"thanks\", \"would ya\", \"please\", \"okay?\", \"proceed\", \"continue\", \"go on\", \"do that\", \"go it\", \"do you understand?\"],\n 'FR': [\"fais-le\", \"vas-y\", \"exécute\", \"lance\", \"commence\", \"merci\", \"tu veux bien\", \"s'il te plaît\", \"d'accord ?\", \"poursuis\", \"continue\", \"vas-y\", \"fais ça\", \"compris\"],\n 'ZH_CHT': [\"做吧\", \"繼續\", \"執行\", \"運作看看\", \"開始\", \"謝謝\", \"可以嗎\", \"請\", \"好嗎\", \"進行\", \"做吧\", \"go\", \"do it\", \"執行吧\", \"懂了\"],\n 'ZH_SC': [\"做吧\", \"继续\", \"执行\", \"运作看看\", \"开始\", \"谢谢\", \"可以吗\", \"请\", \"好吗\", \"运行\", \"做吧\", \"go\", \"do it\", \"执行吧\", \"懂了\"],\n 'ES': [\"hazlo\", \"adelante\", \"ejecuta\", \"corre\", \"empieza\", \"gracias\", \"lo harías\", \"por favor\", \"¿vale?\", \"procede\", \"continúa\", \"sigue\", \"haz eso\", \"haz esa cosa\"]\n }\n self.recorded = \"\"\n\n def get_transcript(self) -> str:\n global done\n buffer = self.recorded\n self.recorded = \"\"\n done = False\n return buffer\n\n def _transcribe(self) -> None:\n \"\"\"\n Transcribe the audio data using AI stt model.\n \"\"\"\n if not IMPORT_FOUND:\n return\n global done\n if self.verbose:\n print(Fore.BLUE + \"AudioTranscriber: Started processing...\" + Fore.RESET)\n \n while not done or not audio_queue.empty():\n try:\n audio_data, sample_rate = audio_queue.get(timeout=1.0)\n \n start_time = time.time()\n text = self.transcriptor.transcript_job(audio_data, sample_rate)\n end_time = time.time()\n self.recorded += text\n print(Fore.YELLOW + f\"Transcribed: {text} in {end_time - start_time} seconds\" + Fore.RESET)\n for language, words in self.trigger_words.items():\n if any(word in text.lower() for word in words):\n print(Fore.GREEN + f\"Listening again...\" + Fore.RESET)\n self.recorded = text\n for language, words in self.confirmation_words.items():\n if any(word in text.lower() for word in words):\n print(Fore.GREEN + f\"Trigger detected. Sending to AI...\" + Fore.RESET)\n audio_queue.task_done()\n done = True\n break\n except queue.Empty:\n time.sleep(0.1)\n continue\n except Exception as e:\n print(Fore.RED + f\"AudioTranscriber: Error - {e}\" + Fore.RESET)\n if self.verbose:\n print(Fore.BLUE + \"AudioTranscriber: Stopped\" + Fore.RESET)\n\n def start(self):\n \"\"\"Start the transcription thread.\"\"\"\n if not IMPORT_FOUND:\n return\n self.thread.start()\n\n def join(self):\n if not IMPORT_FOUND:\n return\n \"\"\"Wait for the transcription thread to finish.\"\"\"\n self.thread.join()\n\n\nif __name__ == \"__main__\":\n recorder = AudioRecorder(verbose=True)\n transcriber = AudioTranscriber(verbose=True, ai_name=\"jarvis\")\n recorder.start()\n transcriber.start()\n recorder.join()\n transcriber.join()"], ["/agenticSeek/llm_server/sources/generator.py", "\nimport threading\nimport logging\nfrom abc import abstractmethod\nfrom .cache import Cache\n\nclass GenerationState:\n def __init__(self):\n self.lock = threading.Lock()\n self.last_complete_sentence = \"\"\n self.current_buffer = \"\"\n self.is_generating = False\n \n def status(self) -> dict:\n return {\n \"sentence\": self.current_buffer,\n \"is_complete\": not self.is_generating,\n \"last_complete_sentence\": self.last_complete_sentence,\n \"is_generating\": self.is_generating,\n }\n\nclass GeneratorLLM():\n def __init__(self):\n self.model = None\n self.state = GenerationState()\n self.logger = logging.getLogger(__name__)\n handler = logging.StreamHandler()\n handler.setLevel(logging.INFO)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n handler.setFormatter(formatter)\n self.logger.addHandler(handler)\n self.logger.setLevel(logging.INFO)\n cache = Cache()\n \n def set_model(self, model: str) -> None:\n self.logger.info(f\"Model set to {model}\")\n self.model = model\n \n def start(self, history: list) -> bool:\n if self.model is None:\n raise Exception(\"Model not set\")\n with self.state.lock:\n if self.state.is_generating:\n return False\n self.state.is_generating = True\n self.logger.info(\"Starting generation\")\n threading.Thread(target=self.generate, args=(history,)).start()\n return True\n \n def get_status(self) -> dict:\n with self.state.lock:\n return self.state.status()\n\n @abstractmethod\n def generate(self, history: list) -> None:\n \"\"\"\n Generate text using the model.\n args:\n history: list of strings\n returns:\n None\n \"\"\"\n pass\n\nif __name__ == \"__main__\":\n generator = GeneratorLLM()\n generator.get_status()"], ["/agenticSeek/llm_server/sources/ollama_handler.py", "\nimport time\nfrom .generator import GeneratorLLM\nfrom .cache import Cache\nimport ollama\n\nclass OllamaLLM(GeneratorLLM):\n\n def __init__(self):\n \"\"\"\n Handle generation using Ollama.\n \"\"\"\n super().__init__()\n self.cache = Cache()\n\n def generate(self, history):\n self.logger.info(f\"Using {self.model} for generation with Ollama\")\n try:\n with self.state.lock:\n self.state.is_generating = True\n self.state.last_complete_sentence = \"\"\n self.state.current_buffer = \"\"\n\n stream = ollama.chat(\n model=self.model,\n messages=history,\n stream=True,\n )\n for chunk in stream:\n content = chunk['message']['content']\n\n with self.state.lock:\n if '.' in content:\n self.logger.info(self.state.current_buffer)\n self.state.current_buffer += content\n\n except Exception as e:\n if \"404\" in str(e):\n self.logger.info(f\"Downloading {self.model}...\")\n ollama.pull(self.model)\n if \"refused\" in str(e).lower():\n raise Exception(\"Ollama connection failed. is the server running ?\") from e\n raise e\n finally:\n self.logger.info(\"Generation complete\")\n with self.state.lock:\n self.state.is_generating = False\n\nif __name__ == \"__main__\":\n generator = OllamaLLM()\n history = [\n {\n \"role\": \"user\",\n \"content\": \"Hello, how are you ?\"\n }\n ]\n generator.set_model(\"deepseek-r1:1.5b\")\n generator.start(history)\n while True:\n print(generator.get_status())\n time.sleep(1)"], ["/agenticSeek/sources/logger.py", "import os, sys\nfrom typing import List, Tuple, Type, Dict\nimport datetime\nimport logging\n\nclass Logger:\n def __init__(self, log_filename):\n self.folder = '.logs'\n self.create_folder(self.folder)\n self.log_path = os.path.join(self.folder, log_filename)\n self.enabled = True\n self.logger = None\n self.last_log_msg = \"\"\n if self.enabled:\n self.create_logging(log_filename)\n\n def create_logging(self, log_filename):\n self.logger = logging.getLogger(log_filename)\n self.logger.setLevel(logging.DEBUG)\n self.logger.handlers.clear()\n self.logger.propagate = False\n file_handler = logging.FileHandler(self.log_path)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n file_handler.setFormatter(formatter)\n self.logger.addHandler(file_handler)\n\n \n def create_folder(self, path):\n \"\"\"Create log dir\"\"\"\n try:\n if not os.path.exists(path):\n os.makedirs(path, exist_ok=True) \n return True\n except Exception as e:\n self.enabled = False\n return False\n \n def log(self, message, level=logging.INFO):\n if self.last_log_msg == message:\n return\n if self.enabled:\n self.last_log_msg = message\n self.logger.log(level, message)\n\n def info(self, message):\n self.log(message)\n\n def error(self, message):\n self.log(message, level=logging.ERROR)\n\n def warning(self, message):\n self.log(message, level=logging.WARN)\n\nif __name__ == \"__main__\":\n lg = Logger(\"test.log\")\n lg.log(\"hello\")\n lg2 = Logger(\"toto.log\")\n lg2.log(\"yo\")\n \n\n "], ["/agenticSeek/llm_server/sources/llamacpp_handler.py", "\nfrom .generator import GeneratorLLM\nfrom llama_cpp import Llama\nfrom .decorator import timer_decorator\n\nclass LlamacppLLM(GeneratorLLM):\n\n def __init__(self):\n \"\"\"\n Handle generation using llama.cpp\n \"\"\"\n super().__init__()\n self.llm = None\n \n @timer_decorator\n def generate(self, history):\n if self.llm is None:\n self.logger.info(f\"Loading {self.model}...\")\n self.llm = Llama.from_pretrained(\n repo_id=self.model,\n filename=\"*Q8_0.gguf\",\n n_ctx=4096,\n verbose=True\n )\n self.logger.info(f\"Using {self.model} for generation with Llama.cpp\")\n try:\n with self.state.lock:\n self.state.is_generating = True\n self.state.last_complete_sentence = \"\"\n self.state.current_buffer = \"\"\n output = self.llm.create_chat_completion(\n messages = history\n )\n with self.state.lock:\n self.state.current_buffer = output['choices'][0]['message']['content']\n except Exception as e:\n self.logger.error(f\"Error: {e}\")\n finally:\n with self.state.lock:\n self.state.is_generating = False"], ["/agenticSeek/llm_server/app.py", "#!/usr/bin python3\n\nimport argparse\nimport time\nfrom flask import Flask, jsonify, request\n\nfrom sources.llamacpp_handler import LlamacppLLM\nfrom sources.ollama_handler import OllamaLLM\n\nparser = argparse.ArgumentParser(description='AgenticSeek server script')\nparser.add_argument('--provider', type=str, help='LLM backend library to use. set to [ollama], [vllm] or [llamacpp]', required=True)\nparser.add_argument('--port', type=int, help='port to use', required=True)\nargs = parser.parse_args()\n\napp = Flask(__name__)\n\nassert args.provider in [\"ollama\", \"llamacpp\"], f\"Provider {args.provider} does not exists. see --help for more information\"\n\nhandler_map = {\n \"ollama\": OllamaLLM(),\n \"llamacpp\": LlamacppLLM(),\n}\n\ngenerator = handler_map[args.provider]\n\n@app.route('/generate', methods=['POST'])\ndef start_generation():\n if generator is None:\n return jsonify({\"error\": \"Generator not initialized\"}), 401\n data = request.get_json()\n history = data.get('messages', [])\n if generator.start(history):\n return jsonify({\"message\": \"Generation started\"}), 202\n return jsonify({\"error\": \"Generation already in progress\"}), 402\n\n@app.route('/setup', methods=['POST'])\ndef setup():\n data = request.get_json()\n model = data.get('model', None)\n if model is None:\n return jsonify({\"error\": \"Model not provided\"}), 403\n generator.set_model(model)\n return jsonify({\"message\": \"Model set\"}), 200\n\n@app.route('/get_updated_sentence')\ndef get_updated_sentence():\n if not generator:\n return jsonify({\"error\": \"Generator not initialized\"}), 405\n print(generator.get_status())\n return generator.get_status()\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', threaded=True, debug=True, port=args.port)"], ["/agenticSeek/llm_server/sources/cache.py", "import os\nimport json\nfrom pathlib import Path\n\nclass Cache:\n def __init__(self, cache_dir='.cache', cache_file='messages.json'):\n self.cache_dir = Path(cache_dir)\n self.cache_file = self.cache_dir / cache_file\n self.cache_dir.mkdir(parents=True, exist_ok=True)\n if not self.cache_file.exists():\n with open(self.cache_file, 'w') as f:\n json.dump([], f)\n\n with open(self.cache_file, 'r') as f:\n self.cache = set(json.load(f))\n\n def add_message_pair(self, user_message: str, assistant_message: str):\n \"\"\"Add a user/assistant pair to the cache if not present.\"\"\"\n if not any(entry[\"user\"] == user_message for entry in self.cache):\n self.cache.append({\"user\": user_message, \"assistant\": assistant_message})\n self._save()\n\n def is_cached(self, user_message: str) -> bool:\n \"\"\"Check if a user msg is cached.\"\"\"\n return any(entry[\"user\"] == user_message for entry in self.cache)\n\n def get_cached_response(self, user_message: str) -> str | None:\n \"\"\"Return the assistant response to a user message if cached.\"\"\"\n for entry in self.cache:\n if entry[\"user\"] == user_message:\n return entry[\"assistant\"]\n return None\n\n def _save(self):\n with open(self.cache_file, 'w') as f:\n json.dump(self.cache, f, indent=2)\n"], ["/agenticSeek/sources/tools/safety.py", "import os\nimport sys\n\nunsafe_commands_unix = [\n \"rm\", # File/directory removal\n \"dd\", # Low-level disk writing\n \"mkfs\", # Filesystem formatting\n \"chmod\", # Permission changes\n \"chown\", # Ownership changes\n \"shutdown\", # System shutdown\n \"reboot\", # System reboot\n \"halt\", # System halt\n \"sysctl\", # Kernel parameter changes\n \"kill\", # Process termination\n \"pkill\", # Kill by process name\n \"killall\", # Kill all matching processes\n \"exec\", # Replace process with command\n \"tee\", # Write to files with privileges\n \"umount\", # Unmount filesystems\n \"passwd\", # Password changes\n \"useradd\", # Add users\n \"userdel\", # Delete users\n \"brew\", # Homebrew package manager\n \"groupadd\", # Add groups\n \"groupdel\", # Delete groups\n \"visudo\", # Edit sudoers file\n \"screen\", # Terminal session management\n \"fdisk\", # Disk partitioning\n \"parted\", # Disk partitioning\n \"chroot\", # Change root directory\n \"route\" # Routing table management\n \"--force\", # Force flag for many commands\n \"rebase\", # Rebase git repository\n \"git\" # Git commands\n]\n\nunsafe_commands_windows = [\n \"del\", # Deletes files\n \"erase\", # Alias for del, deletes files\n \"rd\", # Removes directories (rmdir alias)\n \"rmdir\", # Removes directories\n \"format\", # Formats a disk, erasing data\n \"diskpart\", # Manages disk partitions, can wipe drives\n \"chkdsk /f\", # Fixes filesystem, can alter data\n \"fsutil\", # File system utilities, can modify system files\n \"xcopy /y\", # Copies files, overwriting without prompt\n \"copy /y\", # Copies files, overwriting without prompt\n \"move\", # Moves files, can overwrite\n \"attrib\", # Changes file attributes, e.g., hiding or exposing files\n \"icacls\", # Changes file permissions (modern)\n \"takeown\", # Takes ownership of files\n \"reg delete\", # Deletes registry keys/values\n \"regedit /s\", # Silently imports registry changes\n \"shutdown\", # Shuts down or restarts the system\n \"schtasks\", # Schedules tasks, can run malicious commands\n \"taskkill\", # Kills processes\n \"wmic\", # Deletes processes via WMI\n \"bcdedit\", # Modifies boot configuration\n \"powercfg\", # Changes power settings, can disable protections\n \"assoc\", # Changes file associations\n \"ftype\", # Changes file type commands\n \"cipher /w\", # Wipes free space, erasing data\n \"esentutl\", # Database utilities, can corrupt system files\n \"subst\", # Substitutes drive paths, can confuse system\n \"mklink\", # Creates symbolic links, can redirect access\n \"bootcfg\"\n]\n\ndef is_any_unsafe(cmds):\n \"\"\"\n check if any bash command is unsafe.\n \"\"\"\n for cmd in cmds:\n if is_unsafe(cmd):\n return True\n return False\n\ndef is_unsafe(cmd):\n \"\"\"\n check if a bash command is unsafe.\n \"\"\"\n if sys.platform.startswith(\"win\"):\n if any(c in cmd for c in unsafe_commands_windows):\n return True\n else:\n if any(c in cmd for c in unsafe_commands_unix):\n return True\n return False\n\nif __name__ == \"__main__\":\n cmd = input(\"Enter a command: \")\n if is_unsafe(cmd):\n print(\"Unsafe command detected!\")\n else:\n print(\"Command is safe to execute.\")"], ["/agenticSeek/sources/agents/__init__.py", "\nfrom .agent import Agent\nfrom .code_agent import CoderAgent\nfrom .casual_agent import CasualAgent\nfrom .file_agent import FileAgent\nfrom .planner_agent import PlannerAgent\nfrom .browser_agent import BrowserAgent\nfrom .mcp_agent import McpAgent\n\n__all__ = [\"Agent\", \"CoderAgent\", \"CasualAgent\", \"FileAgent\", \"PlannerAgent\", \"BrowserAgent\", \"McpAgent\"]\n"], ["/agenticSeek/llm_server/sources/decorator.py", "\ndef timer_decorator(func):\n \"\"\"\n Decorator to measure the execution time of a function.\n Usage:\n @timer_decorator\n def my_function():\n # code to execute\n \"\"\"\n from time import time\n def wrapper(*args, **kwargs):\n start_time = time()\n result = func(*args, **kwargs)\n end_time = time()\n print(f\"\\n{func.__name__} took {end_time - start_time:.2f} seconds to execute\\n\")\n return result\n return wrapper"]], "task_instance_info": {"created_time": "2025-08-20 15:04:39", "created_task_model": "DeepSeek-R1", "class_skeleton": "class CasualAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n pass", "code_description": "This code segment functions to: Implement a conversational interface that maintains interaction context through memory management, processes user inputs using language models, and provides real-time processing feedback during response generation."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```python\n[TASK_BEGIN]\nclass CasualAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n super().__init__(name, prompt_path, provider, verbose)\n self.add_tool(searxSearch())\n self.add_tool(FlightSearch())\n self.add_tool(FileFinder())\n self.add_tool(BashInterpreter())\n self.add_tool(Memory())\n[TASK_END]\n```", "inference_time": "2025-08-20 15-05-03"}, "editdistance_info": {"edit_distance": 29.8137, "calculate_time": "2025-08-20 15:05:03", "true_code_clean": "class CasualAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n super().__init__(name, prompt_path, provider, verbose, None)\n self.tools = {\n } \n self.role = \"talk\"\n self.type = \"casual_agent\"\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, \n memory_compression=False,\n model_provider=provider.get_model_name())\n async def process(self, prompt, speech_module) -> str:\n self.memory.push('user', prompt)\n animate_thinking(\"Thinking...\", color=\"status\")\n answer, reasoning = await self.llm_request()\n self.last_answer = answer\n self.status_message = \"Ready\"\n return answer, reasoning", "predict_code_clean": "class CasualAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n super().__init__(name, prompt_path, provider, verbose)\n self.add_tool(searxSearch())\n self.add_tool(FlightSearch())\n self.add_tool(FileFinder())\n self.add_tool(BashInterpreter())\n self.add_tool(Memory())"}}
{"repo_name": "agenticSeek", "file_name": "/agenticSeek/sources/agents/mcp_agent.py", "inference_info": {"prefix_code": "import os\nimport asyncio\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent\nfrom sources.tools.mcpFinder import MCP_finder\nfrom sources.memory import Memory\n\n# NOTE MCP agent is an active work in progress, not functional yet.\n\n", "suffix_code": "\n\nif __name__ == \"__main__\":\n pass", "middle_code": "class McpAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n super().__init__(name, prompt_path, provider, verbose, None)\n keys = self.get_api_keys()\n self.tools = {\n \"mcp_finder\": MCP_finder(keys[\"mcp_finder\"]),\n }\n self.role = \"mcp\"\n self.type = \"mcp_agent\"\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, \n memory_compression=False,\n model_provider=provider.get_model_name())\n self.enabled = True\n def get_api_keys(self) -> dict:\n api_key_mcp_finder = os.getenv(\"MCP_FINDER_API_KEY\")\n if not api_key_mcp_finder or api_key_mcp_finder == \"\":\n pretty_print(\"MCP Finder disabled.\", color=\"warning\")\n self.enabled = False\n return {\n \"mcp_finder\": api_key_mcp_finder\n }\n def expand_prompt(self, prompt):\n tools_str = self.get_tools_description()\n prompt += f\n return prompt\n async def process(self, prompt, speech_module) -> str:\n if self.enabled == False:\n return \"MCP Agent is disabled.\"\n prompt = self.expand_prompt(prompt)\n self.memory.push('user', prompt)\n working = True\n while working == True:\n animate_thinking(\"Thinking...\", color=\"status\")\n answer, reasoning = await self.llm_request()\n exec_success, _ = self.execute_modules(answer)\n answer = self.remove_blocks(answer)\n self.last_answer = answer\n self.status_message = \"Ready\"\n if len(self.blocks_result) == 0:\n working = False\n return answer, reasoning", "code_description": null, "fill_type": "CLASS_TYPE", "language_type": "python", "sub_task_type": null}, "context_code": [["/agenticSeek/sources/agents/file_agent.py", "import asyncio\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent\nfrom sources.tools.fileFinder import FileFinder\nfrom sources.tools.BashInterpreter import BashInterpreter\nfrom sources.memory import Memory\n\nclass FileAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n \"\"\"\n The file agent is a special agent for file operations.\n \"\"\"\n super().__init__(name, prompt_path, provider, verbose, None)\n self.tools = {\n \"file_finder\": FileFinder(),\n \"bash\": BashInterpreter()\n }\n self.work_dir = self.tools[\"file_finder\"].get_work_dir()\n self.role = \"files\"\n self.type = \"file_agent\"\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, # session recovery in handled by the interaction class\n memory_compression=False,\n model_provider=provider.get_model_name())\n \n async def process(self, prompt, speech_module) -> str:\n exec_success = False\n prompt += f\"\\nYou must work in directory: {self.work_dir}\"\n self.memory.push('user', prompt)\n while exec_success is False and not self.stop:\n await self.wait_message(speech_module)\n animate_thinking(\"Thinking...\", color=\"status\")\n answer, reasoning = await self.llm_request()\n self.last_reasoning = reasoning\n exec_success, _ = self.execute_modules(answer)\n answer = self.remove_blocks(answer)\n self.last_answer = answer\n self.status_message = \"Ready\"\n return answer, reasoning\n\nif __name__ == \"__main__\":\n pass"], ["/agenticSeek/sources/agents/code_agent.py", "import platform, os\nimport asyncio\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent, executorResult\nfrom sources.tools.C_Interpreter import CInterpreter\nfrom sources.tools.GoInterpreter import GoInterpreter\nfrom sources.tools.PyInterpreter import PyInterpreter\nfrom sources.tools.BashInterpreter import BashInterpreter\nfrom sources.tools.JavaInterpreter import JavaInterpreter\nfrom sources.tools.fileFinder import FileFinder\nfrom sources.logger import Logger\nfrom sources.memory import Memory\n\nclass CoderAgent(Agent):\n \"\"\"\n The code agent is an agent that can write and execute code.\n \"\"\"\n def __init__(self, name, prompt_path, provider, verbose=False):\n super().__init__(name, prompt_path, provider, verbose, None)\n self.tools = {\n \"bash\": BashInterpreter(),\n \"python\": PyInterpreter(),\n \"c\": CInterpreter(),\n \"go\": GoInterpreter(),\n \"java\": JavaInterpreter(),\n \"file_finder\": FileFinder()\n }\n self.work_dir = self.tools[\"file_finder\"].get_work_dir()\n self.role = \"code\"\n self.type = \"code_agent\"\n self.logger = Logger(\"code_agent.log\")\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, # session recovery in handled by the interaction class\n memory_compression=False,\n model_provider=provider.get_model_name())\n \n def add_sys_info_prompt(self, prompt):\n \"\"\"Add system information to the prompt.\"\"\"\n info = f\"System Info:\\n\" \\\n f\"OS: {platform.system()} {platform.release()}\\n\" \\\n f\"Python Version: {platform.python_version()}\\n\" \\\n f\"\\nYou must save file at root directory: {self.work_dir}\"\n return f\"{prompt}\\n\\n{info}\"\n\n async def process(self, prompt, speech_module) -> str:\n answer = \"\"\n attempt = 0\n max_attempts = 5\n prompt = self.add_sys_info_prompt(prompt)\n self.memory.push('user', prompt)\n clarify_trigger = \"REQUEST_CLARIFICATION\"\n\n while attempt < max_attempts and not self.stop:\n print(\"Stopped?\", self.stop)\n animate_thinking(\"Thinking...\", color=\"status\")\n await self.wait_message(speech_module)\n answer, reasoning = await self.llm_request()\n self.last_reasoning = reasoning\n if clarify_trigger in answer:\n self.last_answer = answer\n await asyncio.sleep(0)\n return answer, reasoning\n if not \"```\" in answer:\n self.last_answer = answer\n await asyncio.sleep(0)\n break\n self.show_answer()\n animate_thinking(\"Executing code...\", color=\"status\")\n self.status_message = \"Executing code...\"\n self.logger.info(f\"Attempt {attempt + 1}:\\n{answer}\")\n exec_success, feedback = self.execute_modules(answer)\n self.logger.info(f\"Execution result: {exec_success}\")\n answer = self.remove_blocks(answer)\n self.last_answer = answer\n await asyncio.sleep(0)\n if exec_success and self.get_last_tool_type() != \"bash\":\n break\n pretty_print(f\"Execution failure:\\n{feedback}\", color=\"failure\")\n pretty_print(\"Correcting code...\", color=\"status\")\n self.status_message = \"Correcting code...\"\n attempt += 1\n self.status_message = \"Ready\"\n if attempt == max_attempts:\n return \"I'm sorry, I couldn't find a solution to your problem. How would you like me to proceed ?\", reasoning\n self.last_answer = answer\n return answer, reasoning\n\nif __name__ == \"__main__\":\n pass"], ["/agenticSeek/sources/agents/casual_agent.py", "import asyncio\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent\nfrom sources.tools.searxSearch import searxSearch\nfrom sources.tools.flightSearch import FlightSearch\nfrom sources.tools.fileFinder import FileFinder\nfrom sources.tools.BashInterpreter import BashInterpreter\nfrom sources.memory import Memory\n\nclass CasualAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n \"\"\"\n The casual agent is a special for casual talk to the user without specific tasks.\n \"\"\"\n super().__init__(name, prompt_path, provider, verbose, None)\n self.tools = {\n } # No tools for the casual agent\n self.role = \"talk\"\n self.type = \"casual_agent\"\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, # session recovery in handled by the interaction class\n memory_compression=False,\n model_provider=provider.get_model_name())\n \n async def process(self, prompt, speech_module) -> str:\n self.memory.push('user', prompt)\n animate_thinking(\"Thinking...\", color=\"status\")\n answer, reasoning = await self.llm_request()\n self.last_answer = answer\n self.status_message = \"Ready\"\n return answer, reasoning\n\nif __name__ == \"__main__\":\n pass"], ["/agenticSeek/sources/agents/planner_agent.py", "import json\nfrom typing import List, Tuple, Type, Dict\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent\nfrom sources.agents.code_agent import CoderAgent\nfrom sources.agents.file_agent import FileAgent\nfrom sources.agents.browser_agent import BrowserAgent\nfrom sources.agents.casual_agent import CasualAgent\nfrom sources.text_to_speech import Speech\nfrom sources.tools.tools import Tools\nfrom sources.logger import Logger\nfrom sources.memory import Memory\n\nclass PlannerAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False, browser=None):\n \"\"\"\n The planner agent is a special agent that divides and conquers the task.\n \"\"\"\n super().__init__(name, prompt_path, provider, verbose, None)\n self.tools = {\n \"json\": Tools()\n }\n self.tools['json'].tag = \"json\"\n self.browser = browser\n self.agents = {\n \"coder\": CoderAgent(name, \"prompts/base/coder_agent.txt\", provider, verbose=False),\n \"file\": FileAgent(name, \"prompts/base/file_agent.txt\", provider, verbose=False),\n \"web\": BrowserAgent(name, \"prompts/base/browser_agent.txt\", provider, verbose=False, browser=browser),\n \"casual\": CasualAgent(name, \"prompts/base/casual_agent.txt\", provider, verbose=False)\n }\n self.role = \"planification\"\n self.type = \"planner_agent\"\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, # session recovery in handled by the interaction class\n memory_compression=False,\n model_provider=provider.get_model_name())\n self.logger = Logger(\"planner_agent.log\")\n \n def get_task_names(self, text: str) -> List[str]:\n \"\"\"\n Extracts task names from the given text.\n This method processes a multi-line string, where each line may represent a task name.\n containing '##' or starting with a digit. The valid task names are collected and returned.\n Args:\n text (str): A string containing potential task titles (eg: Task 1: I will...).\n Returns:\n List[str]: A list of extracted task names that meet the specified criteria.\n \"\"\"\n tasks_names = []\n lines = text.strip().split('\\n')\n for line in lines:\n if line is None:\n continue\n line = line.strip()\n if len(line) == 0:\n continue\n if '##' in line or line[0].isdigit():\n tasks_names.append(line)\n continue\n self.logger.info(f\"Found {len(tasks_names)} tasks names.\")\n return tasks_names\n\n def parse_agent_tasks(self, text: str) -> List[Tuple[str, str]]:\n \"\"\"\n Parses agent tasks from the given LLM text.\n This method extracts task information from a JSON. It identifies task names and their details.\n Args:\n text (str): The input text containing task information in a JSON-like format.\n Returns:\n List[Tuple[str, str]]: A list of tuples containing task names and their details.\n \"\"\"\n tasks = []\n tasks_names = self.get_task_names(text)\n\n blocks, _ = self.tools[\"json\"].load_exec_block(text)\n if blocks == None:\n return []\n for block in blocks:\n line_json = json.loads(block)\n if 'plan' in line_json:\n for task in line_json['plan']:\n if task['agent'].lower() not in [ag_name.lower() for ag_name in self.agents.keys()]:\n self.logger.warning(f\"Agent {task['agent']} does not exist.\")\n pretty_print(f\"Agent {task['agent']} does not exist.\", color=\"warning\")\n return []\n try:\n agent = {\n 'agent': task['agent'],\n 'id': task['id'],\n 'task': task['task']\n }\n except:\n self.logger.warning(\"Missing field in json plan.\")\n return []\n self.logger.info(f\"Created agent {task['agent']} with task: {task['task']}\")\n if 'need' in task:\n self.logger.info(f\"Agent {task['agent']} was given info:\\n {task['need']}\")\n agent['need'] = task['need']\n tasks.append(agent)\n if len(tasks_names) != len(tasks):\n names = [task['task'] for task in tasks]\n return list(map(list, zip(names, tasks)))\n return list(map(list, zip(tasks_names, tasks)))\n \n def make_prompt(self, task: str, agent_infos_dict: dict) -> str:\n \"\"\"\n Generates a prompt for the agent based on the task and previous agents work information.\n Args:\n task (str): The task to be performed.\n agent_infos_dict (dict): A dictionary containing information from other agents.\n Returns:\n str: The formatted prompt for the agent.\n \"\"\"\n infos = \"\"\n if agent_infos_dict is None or len(agent_infos_dict) == 0:\n infos = \"No needed informations.\"\n else:\n for agent_id, info in agent_infos_dict.items():\n infos += f\"\\t- According to agent {agent_id}:\\n{info}\\n\\n\"\n prompt = f\"\"\"\n You are given informations from your AI friends work:\n {infos}\n Your task is:\n {task}\n \"\"\"\n self.logger.info(f\"Prompt for agent:\\n{prompt}\")\n return prompt\n \n def show_plan(self, agents_tasks: List[dict], answer: str) -> None:\n \"\"\"\n Displays the plan made by the agent.\n Args:\n agents_tasks (dict): The tasks assigned to each agent.\n answer (str): The answer from the LLM.\n \"\"\"\n if agents_tasks == []:\n pretty_print(answer, color=\"warning\")\n pretty_print(\"Failed to make a plan. This can happen with (too) small LLM. Clarify your request and insist on it making a plan within ```json.\", color=\"failure\")\n return\n pretty_print(\"\\n▂▘ P L A N ▝▂\", color=\"status\")\n for task_name, task in agents_tasks:\n pretty_print(f\"{task['agent']} -> {task['task']}\", color=\"info\")\n pretty_print(\"▔▗ E N D ▖▔\", color=\"status\")\n\n async def make_plan(self, prompt: str) -> str:\n \"\"\"\n Asks the LLM to make a plan.\n Args:\n prompt (str): The prompt to be sent to the LLM.\n Returns:\n str: The plan made by the LLM.\n \"\"\"\n ok = False\n answer = None\n while not ok:\n animate_thinking(\"Thinking...\", color=\"status\")\n self.memory.push('user', prompt)\n answer, reasoning = await self.llm_request()\n if \"NO_UPDATE\" in answer:\n return []\n agents_tasks = self.parse_agent_tasks(answer)\n if agents_tasks == []:\n self.show_plan(agents_tasks, answer)\n prompt = f\"Failed to parse the tasks. Please write down your task followed by a json plan within ```json. Do not ask for clarification.\\n\"\n pretty_print(\"Failed to make plan. Retrying...\", color=\"warning\")\n continue\n self.show_plan(agents_tasks, answer)\n ok = True\n self.logger.info(f\"Plan made:\\n{answer}\")\n return self.parse_agent_tasks(answer)\n \n async def update_plan(self, goal: str, agents_tasks: List[dict], agents_work_result: dict, id: str, success: bool) -> dict:\n \"\"\"\n Updates the plan with the results of the agents work.\n Args:\n goal (str): The goal to be achieved.\n agents_tasks (list): The tasks assigned to each agent.\n agents_work_result (dict): The results of the agents work.\n Returns:\n dict: The updated plan.\n \"\"\"\n self.status_message = \"Updating plan...\"\n last_agent_work = agents_work_result[id]\n tool_success_str = \"success\" if success else \"failure\"\n pretty_print(f\"Agent {id} work {tool_success_str}.\", color=\"success\" if success else \"failure\")\n try:\n id_int = int(id)\n except Exception as e:\n return agents_tasks\n if id_int == len(agents_tasks):\n next_task = \"No task follow, this was the last step. If it failed add a task to recover.\"\n else:\n next_task = f\"Next task is: {agents_tasks[int(id)][0]}.\"\n #if success:\n # return agents_tasks # we only update the plan if last task failed, for now\n update_prompt = f\"\"\"\n Your goal is : {goal}\n You previously made a plan, agents are currently working on it.\n The last agent working on task: {id}, did the following work:\n {last_agent_work}\n Agent {id} work was a {tool_success_str} according to system interpreter.\n {next_task}\n Is the work done for task {id} leading to success or failure ? Did an agent fail with a task?\n If agent work was good: answer \"NO_UPDATE\"\n If agent work is leading to failure: update the plan.\n If a task failed add a task to try again or recover from failure. You might have near identical task twice.\n plan should be within ```json like before.\n You need to rewrite the whole plan, but only change the tasks after task {id}.\n Make the plan the same length as the original one or with only one additional step.\n Do not change past tasks. Change next tasks.\n \"\"\"\n pretty_print(\"Updating plan...\", color=\"status\")\n plan = await self.make_plan(update_prompt)\n if plan == []:\n pretty_print(\"No plan update required.\", color=\"info\")\n return agents_tasks\n self.logger.info(f\"Plan updated:\\n{plan}\")\n return plan\n \n async def start_agent_process(self, task: dict, required_infos: dict | None) -> str:\n \"\"\"\n Starts the agent process for a given task.\n Args:\n task (dict): The task to be performed.\n required_infos (dict | None): The required information for the task.\n Returns:\n str: The result of the agent process.\n \"\"\"\n self.status_message = f\"Starting task {task['task']}...\"\n agent_prompt = self.make_prompt(task['task'], required_infos)\n pretty_print(f\"Agent {task['agent']} started working...\", color=\"status\")\n self.logger.info(f\"Agent {task['agent']} started working on {task['task']}.\")\n answer, reasoning = await self.agents[task['agent'].lower()].process(agent_prompt, None)\n self.last_answer = answer\n self.last_reasoning = reasoning\n self.blocks_result = self.agents[task['agent'].lower()].blocks_result\n agent_answer = self.agents[task['agent'].lower()].raw_answer_blocks(answer)\n success = self.agents[task['agent'].lower()].get_success\n self.agents[task['agent'].lower()].show_answer()\n pretty_print(f\"Agent {task['agent']} completed task.\", color=\"status\")\n self.logger.info(f\"Agent {task['agent']} finished working on {task['task']}. Success: {success}\")\n agent_answer += \"\\nAgent succeeded with task.\" if success else \"\\nAgent failed with task (Error detected).\"\n return agent_answer, success\n \n def get_work_result_agent(self, task_needs, agents_work_result):\n res = {k: agents_work_result[k] for k in task_needs if k in agents_work_result}\n self.logger.info(f\"Next agent needs: {task_needs}.\\n Match previous agent result: {res}\")\n return res\n\n async def process(self, goal: str, speech_module: Speech) -> Tuple[str, str]:\n \"\"\"\n Process the goal by dividing it into tasks and assigning them to agents.\n Args:\n goal (str): The goal to be achieved (user prompt).\n speech_module (Speech): The speech module for text-to-speech.\n Returns:\n Tuple[str, str]: The result of the agent process and empty reasoning string.\n \"\"\"\n agents_tasks = []\n required_infos = None\n agents_work_result = dict()\n\n self.status_message = \"Making a plan...\"\n agents_tasks = await self.make_plan(goal)\n\n if agents_tasks == []:\n return \"Failed to parse the tasks.\", \"\"\n i = 0\n steps = len(agents_tasks)\n while i < steps and not self.stop:\n task_name, task = agents_tasks[i][0], agents_tasks[i][1]\n self.status_message = \"Starting agents...\"\n pretty_print(f\"I will {task_name}.\", color=\"info\")\n self.last_answer = f\"I will {task_name.lower()}.\"\n pretty_print(f\"Assigned agent {task['agent']} to {task_name}\", color=\"info\")\n if speech_module: speech_module.speak(f\"I will {task_name}. I assigned the {task['agent']} agent to the task.\")\n\n if agents_work_result is not None:\n required_infos = self.get_work_result_agent(task['need'], agents_work_result)\n try:\n answer, success = await self.start_agent_process(task, required_infos)\n except Exception as e:\n raise e\n if self.stop:\n pretty_print(f\"Requested stop.\", color=\"failure\")\n agents_work_result[task['id']] = answer\n agents_tasks = await self.update_plan(goal, agents_tasks, agents_work_result, task['id'], success)\n steps = len(agents_tasks)\n i += 1\n\n return answer, \"\"\n"], ["/agenticSeek/sources/tools/mcpFinder.py", "import os, sys\nimport requests\nfrom urllib.parse import urljoin\nfrom typing import Dict, Any, Optional\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass MCP_finder(Tools):\n \"\"\"\n Tool to find MCPs server\n \"\"\"\n def __init__(self, api_key: str = None):\n super().__init__()\n self.tag = \"mcp_finder\"\n self.name = \"MCP Finder\"\n self.description = \"Find MCP servers and their tools\"\n self.base_url = \"https://registry.smithery.ai\"\n self.headers = {\n \"Authorization\": f\"Bearer {api_key}\",\n \"Content-Type\": \"application/json\"\n }\n\n def _make_request(self, method: str, endpoint: str, params: Optional[Dict] = None, \n data: Optional[Dict] = None) -> Dict[str, Any]:\n url = urljoin(self.base_url.rstrip(), endpoint)\n try:\n response = requests.request(\n method=method,\n url=url,\n headers=self.headers,\n params=params,\n json=data\n )\n response.raise_for_status()\n return response.json()\n except requests.exceptions.HTTPError as e:\n raise requests.exceptions.HTTPError(f\"API request failed: {str(e)}\")\n except requests.exceptions.RequestException as e:\n raise requests.exceptions.RequestException(f\"Network error: {str(e)}\")\n\n def list_mcp_servers(self, page: int = 1, page_size: int = 5000) -> Dict[str, Any]:\n params = {\"page\": page, \"pageSize\": page_size}\n return self._make_request(\"GET\", \"/servers\", params=params)\n\n def get_mcp_server_details(self, qualified_name: str) -> Dict[str, Any]:\n endpoint = f\"/servers/{qualified_name}\"\n return self._make_request(\"GET\", endpoint)\n \n def find_mcp_servers(self, query: str) -> Dict[str, Any]:\n \"\"\"\n Finds a specific MCP server by its name.\n Args:\n query (str): a name or string that more or less matches the MCP server name.\n Returns:\n Dict[str, Any]: The details of the found MCP server or an error message.\n \"\"\"\n mcps = self.list_mcp_servers()\n matching_mcp = []\n for mcp in mcps.get(\"servers\", []):\n name = mcp.get(\"qualifiedName\", \"\")\n if query.lower() in name.lower():\n details = self.get_mcp_server_details(name)\n matching_mcp.append(details)\n return matching_mcp\n \n def execute(self, blocks: list, safety:bool = False) -> str:\n if not blocks or not isinstance(blocks, list):\n return \"Error: No blocks provided\\n\"\n\n output = \"\"\n for block in blocks:\n block_clean = block.strip().lower().replace('\\n', '')\n try:\n matching_mcp_infos = self.find_mcp_servers(block_clean)\n except requests.exceptions.RequestException as e:\n output += \"Connection failed. Is the API key in environment?\\n\"\n continue\n except Exception as e:\n output += f\"Error: {str(e)}\\n\"\n continue\n if matching_mcp_infos == []:\n output += f\"Error: No MCP server found for query '{block}'\\n\"\n continue\n for mcp_infos in matching_mcp_infos:\n if mcp_infos['tools'] is None:\n continue\n output += f\"Name: {mcp_infos['displayName']}\\n\"\n output += f\"Usage name: {mcp_infos['qualifiedName']}\\n\"\n output += f\"Tools: {mcp_infos['tools']}\"\n output += \"\\n-------\\n\"\n return output.strip()\n\n def execution_failure_check(self, output: str) -> bool:\n output = output.strip().lower()\n if not output:\n return True\n if \"error\" in output or \"not found\" in output:\n return True\n return False\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Not really needed for this tool (use return of execute() directly)\n \"\"\"\n if not output:\n raise ValueError(\"No output to interpret.\")\n return f\"\"\"\n The following MCPs were found:\n {output}\n \"\"\"\n\nif __name__ == \"__main__\":\n api_key = os.getenv(\"MCP_FINDER\")\n tool = MCP_finder(api_key)\n result = tool.execute([\"\"\"\nstock\n\"\"\"], False)\n print(result)\n"], ["/agenticSeek/sources/agents/agent.py", "\nfrom typing import Tuple, Callable\nfrom abc import abstractmethod\nimport os\nimport random\nimport time\n\nimport asyncio\nfrom concurrent.futures import ThreadPoolExecutor\n\nfrom sources.memory import Memory\nfrom sources.utility import pretty_print\nfrom sources.schemas import executorResult\n\nrandom.seed(time.time())\n\nclass Agent():\n \"\"\"\n An abstract class for all agents.\n \"\"\"\n def __init__(self, name: str,\n prompt_path:str,\n provider,\n verbose=False,\n browser=None) -> None:\n \"\"\"\n Args:\n name (str): Name of the agent.\n prompt_path (str): Path to the prompt file for the agent.\n provider: The provider for the LLM.\n recover_last_session (bool, optional): Whether to recover the last conversation. \n verbose (bool, optional): Enable verbose logging if True. Defaults to False.\n browser: The browser class for web navigation (only for browser agent).\n \"\"\"\n \n self.agent_name = name\n self.browser = browser\n self.role = None\n self.type = None\n self.current_directory = os.getcwd()\n self.llm = provider \n self.memory = None\n self.tools = {}\n self.blocks_result = []\n self.success = True\n self.last_answer = \"\"\n self.last_reasoning = \"\"\n self.status_message = \"Haven't started yet\"\n self.stop = False\n self.verbose = verbose\n self.executor = ThreadPoolExecutor(max_workers=1)\n \n @property\n def get_agent_name(self) -> str:\n return self.agent_name\n \n @property\n def get_agent_type(self) -> str:\n return self.type\n \n @property\n def get_agent_role(self) -> str:\n return self.role\n \n @property\n def get_last_answer(self) -> str:\n return self.last_answer\n \n @property\n def get_last_reasoning(self) -> str:\n return self.last_reasoning\n \n @property\n def get_blocks(self) -> list:\n return self.blocks_result\n \n @property\n def get_status_message(self) -> str:\n return self.status_message\n\n @property\n def get_tools(self) -> dict:\n return self.tools\n \n @property\n def get_success(self) -> bool:\n return self.success\n \n def get_blocks_result(self) -> list:\n return self.blocks_result\n\n def add_tool(self, name: str, tool: Callable) -> None:\n if tool is not Callable:\n raise TypeError(\"Tool must be a callable object (a method)\")\n self.tools[name] = tool\n \n def get_tools_name(self) -> list:\n \"\"\"\n Get the list of tools names.\n \"\"\"\n return list(self.tools.keys())\n \n def get_tools_description(self) -> str:\n \"\"\"\n Get the list of tools names and their description.\n \"\"\"\n description = \"\"\n for name in self.get_tools_name():\n description += f\"{name}: {self.tools[name].description}\\n\"\n return description\n \n def load_prompt(self, file_path: str) -> str:\n try:\n with open(file_path, 'r', encoding=\"utf-8\") as f:\n return f.read()\n except FileNotFoundError:\n raise FileNotFoundError(f\"Prompt file not found at path: {file_path}\")\n except PermissionError:\n raise PermissionError(f\"Permission denied to read prompt file at path: {file_path}\")\n except Exception as e:\n raise e\n \n def request_stop(self) -> None:\n \"\"\"\n Request the agent to stop.\n \"\"\"\n self.stop = True\n self.status_message = \"Stopped\"\n \n @abstractmethod\n def process(self, prompt, speech_module) -> str:\n \"\"\"\n abstract method, implementation in child class.\n Process the prompt and return the answer of the agent.\n \"\"\"\n pass\n\n def remove_reasoning_text(self, text: str) -> None:\n \"\"\"\n Remove the reasoning block of reasoning model like deepseek.\n \"\"\"\n end_tag = \"\"\n end_idx = text.rfind(end_tag)\n if end_idx == -1:\n return text\n return text[end_idx+8:]\n \n def extract_reasoning_text(self, text: str) -> None:\n \"\"\"\n Extract the reasoning block of a reasoning model like deepseek.\n \"\"\"\n start_tag = \"\"\n end_tag = \"\"\n if text is None:\n return None\n start_idx = text.find(start_tag)\n end_idx = text.rfind(end_tag)+8\n return text[start_idx:end_idx]\n \n async def llm_request(self) -> Tuple[str, str]:\n \"\"\"\n Asynchronously ask the LLM to process the prompt.\n \"\"\"\n self.status_message = \"Thinking...\"\n loop = asyncio.get_event_loop()\n return await loop.run_in_executor(self.executor, self.sync_llm_request)\n \n def sync_llm_request(self) -> Tuple[str, str]:\n \"\"\"\n Ask the LLM to process the prompt and return the answer and the reasoning.\n \"\"\"\n memory = self.memory.get()\n thought = self.llm.respond(memory, self.verbose)\n\n reasoning = self.extract_reasoning_text(thought)\n answer = self.remove_reasoning_text(thought)\n self.memory.push('assistant', answer)\n return answer, reasoning\n \n async def wait_message(self, speech_module):\n if speech_module is None:\n return\n messages = [\"Please be patient, I am working on it.\",\n \"Computing... I recommand you have a coffee while I work.\",\n \"Hold on, I’m crunching numbers.\",\n \"Working on it, please let me think.\"]\n loop = asyncio.get_event_loop()\n return await loop.run_in_executor(self.executor, lambda: speech_module.speak(messages[random.randint(0, len(messages)-1)]))\n \n def get_last_tool_type(self) -> str:\n return self.blocks_result[-1].tool_type if len(self.blocks_result) > 0 else None\n \n def raw_answer_blocks(self, answer: str) -> str:\n \"\"\"\n Return the answer with all the blocks inserted, as text.\n \"\"\"\n if self.last_answer is None:\n return\n raw = \"\"\n lines = self.last_answer.split(\"\\n\")\n for line in lines:\n if \"block:\" in line:\n block_idx = int(line.split(\":\")[1])\n if block_idx < len(self.blocks_result):\n raw += self.blocks_result[block_idx].__str__()\n else:\n raw += line + \"\\n\"\n return raw\n\n def show_answer(self):\n \"\"\"\n Show the answer in a pretty way.\n Show code blocks and their respective feedback by inserting them in the ressponse.\n \"\"\"\n if self.last_answer is None:\n return\n lines = self.last_answer.split(\"\\n\")\n for line in lines:\n if \"block:\" in line:\n block_idx = int(line.split(\":\")[1])\n if block_idx < len(self.blocks_result):\n self.blocks_result[block_idx].show()\n else:\n pretty_print(line, color=\"output\")\n\n def remove_blocks(self, text: str) -> str:\n \"\"\"\n Remove all code/query blocks within a tag from the answer text.\n \"\"\"\n tag = f'```'\n lines = text.split('\\n')\n post_lines = []\n in_block = False\n block_idx = 0\n for line in lines:\n if tag in line and not in_block:\n in_block = True\n continue\n if not in_block:\n post_lines.append(line)\n if tag in line:\n in_block = False\n post_lines.append(f\"block:{block_idx}\")\n block_idx += 1\n return \"\\n\".join(post_lines)\n \n def show_block(self, block: str) -> None:\n \"\"\"\n Show the block in a pretty way.\n \"\"\"\n pretty_print('▂'*64, color=\"status\")\n pretty_print(block, color=\"code\")\n pretty_print('▂'*64, color=\"status\")\n\n def execute_modules(self, answer: str) -> Tuple[bool, str]:\n \"\"\"\n Execute all the tools the agent has and return the result.\n \"\"\"\n feedback = \"\"\n success = True\n blocks = None\n if answer.startswith(\"```\"):\n answer = \"I will execute:\\n\" + answer # there should always be a text before blocks for the function that display answer\n\n self.success = True\n for name, tool in self.tools.items():\n feedback = \"\"\n blocks, save_path = tool.load_exec_block(answer)\n\n if blocks != None:\n pretty_print(f\"Executing {len(blocks)} {name} blocks...\", color=\"status\")\n for block in blocks:\n self.show_block(block)\n output = tool.execute([block])\n feedback = tool.interpreter_feedback(output) # tool interpreter feedback\n success = not tool.execution_failure_check(output)\n self.blocks_result.append(executorResult(block, feedback, success, name))\n if not success:\n self.success = False\n self.memory.push('user', feedback)\n return False, feedback\n self.memory.push('user', feedback)\n if save_path != None:\n tool.save_block(blocks, save_path)\n return True, feedback\n"], ["/agenticSeek/sources/agents/browser_agent.py", "import re\nimport time\nfrom datetime import date\nfrom typing import List, Tuple, Type, Dict\nfrom enum import Enum\nimport asyncio\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent\nfrom sources.tools.searxSearch import searxSearch\nfrom sources.browser import Browser\nfrom sources.logger import Logger\nfrom sources.memory import Memory\n\nclass Action(Enum):\n REQUEST_EXIT = \"REQUEST_EXIT\"\n FORM_FILLED = \"FORM_FILLED\"\n GO_BACK = \"GO_BACK\"\n NAVIGATE = \"NAVIGATE\"\n SEARCH = \"SEARCH\"\n \nclass BrowserAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False, browser=None):\n \"\"\"\n The Browser agent is an agent that navigate the web autonomously in search of answer\n \"\"\"\n super().__init__(name, prompt_path, provider, verbose, browser)\n self.tools = {\n \"web_search\": searxSearch(),\n }\n self.role = \"web\"\n self.type = \"browser_agent\"\n self.browser = browser\n self.current_page = \"\"\n self.search_history = []\n self.navigable_links = []\n self.last_action = Action.NAVIGATE.value\n self.notes = []\n self.date = self.get_today_date()\n self.logger = Logger(\"browser_agent.log\")\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, # session recovery in handled by the interaction class\n memory_compression=False,\n model_provider=provider.get_model_name() if provider else None)\n \n def get_today_date(self) -> str:\n \"\"\"Get the date\"\"\"\n date_time = date.today()\n return date_time.strftime(\"%B %d, %Y\")\n\n def extract_links(self, search_result: str) -> List[str]:\n \"\"\"Extract all links from a sentence.\"\"\"\n pattern = r'(https?://\\S+|www\\.\\S+)'\n matches = re.findall(pattern, search_result)\n trailing_punct = \".,!?;:)\"\n cleaned_links = [link.rstrip(trailing_punct) for link in matches]\n self.logger.info(f\"Extracted links: {cleaned_links}\")\n return self.clean_links(cleaned_links)\n \n def extract_form(self, text: str) -> List[str]:\n \"\"\"Extract form written by the LLM in format [input_name](value)\"\"\"\n inputs = []\n matches = re.findall(r\"\\[\\w+\\]\\([^)]+\\)\", text)\n return matches\n \n def clean_links(self, links: List[str]) -> List[str]:\n \"\"\"Ensure no '.' at the end of link\"\"\"\n links_clean = []\n for link in links:\n link = link.strip()\n if not (link[-1].isalpha() or link[-1].isdigit()):\n links_clean.append(link[:-1])\n else:\n links_clean.append(link)\n return links_clean\n\n def get_unvisited_links(self) -> List[str]:\n return \"\\n\".join([f\"[{i}] {link}\" for i, link in enumerate(self.navigable_links) if link not in self.search_history])\n\n def make_newsearch_prompt(self, prompt: str, search_result: dict) -> str:\n search_choice = self.stringify_search_results(search_result)\n self.logger.info(f\"Search results: {search_choice}\")\n return f\"\"\"\n Based on the search result:\n {search_choice}\n Your goal is to find accurate and complete information to satisfy the user’s request.\n User request: {prompt}\n To proceed, choose a relevant link from the search results. Announce your choice by saying: \"I will navigate to \"\n Do not explain your choice.\n \"\"\"\n \n def make_navigation_prompt(self, user_prompt: str, page_text: str) -> str:\n remaining_links = self.get_unvisited_links() \n remaining_links_text = remaining_links if remaining_links is not None else \"No links remaining, do a new search.\" \n inputs_form = self.browser.get_form_inputs()\n inputs_form_text = '\\n'.join(inputs_form)\n notes = '\\n'.join(self.notes)\n self.logger.info(f\"Making navigation prompt with page text: {page_text[:100]}...\\nremaining links: {remaining_links_text}\")\n self.logger.info(f\"Inputs form: {inputs_form_text}\")\n self.logger.info(f\"Notes: {notes}\")\n\n return f\"\"\"\n You are navigating the web.\n\n **Current Context**\n\n Webpage ({self.current_page}) content:\n {page_text}\n\n Allowed Navigation Links:\n {remaining_links_text}\n\n Inputs forms:\n {inputs_form_text}\n\n End of webpage ({self.current_page}.\n\n # Instruction\n\n 1. **Evaluate if the page is relevant for user’s query and document finding:**\n - If the page is relevant, extract and summarize key information in concise notes (Note: )\n - If page not relevant, state: \"Error: \" and either return to the previous page or navigate to a new link.\n - Notes should be factual, useful summaries of relevant content, they should always include specific names or link. Written as: \"On , . . .\" Avoid phrases like \"the page provides\" or \"I found that.\"\n 2. **Navigate to a link by either: **\n - Saying I will navigate to (write down the full URL) www.example.com/cats\n - Going back: If no link seems helpful, say: {Action.GO_BACK.value}.\n 3. **Fill forms on the page:**\n - Fill form only when relevant.\n - Use Login if username/password specified by user. For quick task create account, remember password in a note.\n - You can fill a form using [form_name](value). Don't {Action.GO_BACK.value} when filling form.\n - If a form is irrelevant or you lack informations (eg: don't know user email) leave it empty.\n 4. **Decide if you completed the task**\n - Check your notes. Do they fully answer the question? Did you verify with multiple pages?\n - Are you sure it’s correct?\n - If yes to all, say {Action.REQUEST_EXIT}.\n - If no, or a page lacks info, go to another link.\n - Never stop or ask the user for help.\n \n **Rules:**\n - Do not write \"The page talk about ...\", write your finding on the page and how they contribute to an answer.\n - Put note in a single paragraph.\n - When you exit, explain why.\n \n # Example:\n \n Example 1 (useful page, no need go futher):\n Note: According to karpathy site LeCun net is ...\n No link seem useful to provide futher information.\n Action: {Action.GO_BACK.value}\n\n Example 2 (not useful, see useful link on page):\n Error: reddit.com/welcome does not discuss anything related to the user’s query.\n There is a link that could lead to the information.\n Action: navigate to http://reddit.com/r/locallama\n\n Example 3 (not useful, no related links):\n Error: x.com does not discuss anything related to the user’s query and no navigation link are usefull.\n Action: {Action.GO_BACK.value}\n\n Example 3 (clear definitive query answer found or enought notes taken):\n I took 10 notes so far with enought finding to answer user question.\n Therefore I should exit the web browser.\n Action: {Action.REQUEST_EXIT.value}\n\n Example 4 (loging form visible):\n\n Note: I am on the login page, I will type the given username and password. \n Action:\n [username_field](David)\n [password_field](edgerunners77)\n\n Remember, user asked:\n {user_prompt}\n You previously took these notes:\n {notes}\n Do not Step-by-Step explanation. Write comprehensive Notes or Error as a long paragraph followed by your action.\n You must always take notes.\n \"\"\"\n \n async def llm_decide(self, prompt: str, show_reasoning: bool = False) -> Tuple[str, str]:\n animate_thinking(\"Thinking...\", color=\"status\")\n self.memory.push('user', prompt)\n answer, reasoning = await self.llm_request()\n self.last_reasoning = reasoning\n if show_reasoning:\n pretty_print(reasoning, color=\"failure\")\n pretty_print(answer, color=\"output\")\n return answer, reasoning\n \n def select_unvisited(self, search_result: List[str]) -> List[str]:\n results_unvisited = []\n for res in search_result:\n if res[\"link\"] not in self.search_history:\n results_unvisited.append(res) \n self.logger.info(f\"Unvisited links: {results_unvisited}\")\n return results_unvisited\n\n def jsonify_search_results(self, results_string: str) -> List[str]:\n result_blocks = results_string.split(\"\\n\\n\")\n parsed_results = []\n for block in result_blocks:\n if not block.strip():\n continue\n lines = block.split(\"\\n\")\n result_dict = {}\n for line in lines:\n if line.startswith(\"Title:\"):\n result_dict[\"title\"] = line.replace(\"Title:\", \"\").strip()\n elif line.startswith(\"Snippet:\"):\n result_dict[\"snippet\"] = line.replace(\"Snippet:\", \"\").strip()\n elif line.startswith(\"Link:\"):\n result_dict[\"link\"] = line.replace(\"Link:\", \"\").strip()\n if result_dict:\n parsed_results.append(result_dict)\n return parsed_results \n \n def stringify_search_results(self, results_arr: List[str]) -> str:\n return '\\n\\n'.join([f\"Link: {res['link']}\\nPreview: {res['snippet']}\" for res in results_arr])\n \n def parse_answer(self, text):\n lines = text.split('\\n')\n saving = False\n buffer = []\n links = []\n for line in lines:\n if line == '' or 'action:' in line.lower():\n saving = False\n if \"note\" in line.lower():\n saving = True\n if saving:\n buffer.append(line.replace(\"notes:\", ''))\n else:\n links.extend(self.extract_links(line))\n self.notes.append('. '.join(buffer).strip())\n return links\n \n def select_link(self, links: List[str]) -> str | None:\n \"\"\"\n Select the first unvisited link that is not the current page.\n Preference is given to links not in search_history.\n \"\"\"\n for lk in links:\n if lk == self.current_page or lk in self.search_history:\n self.logger.info(f\"Skipping already visited or current link: {lk}\")\n continue\n self.logger.info(f\"Selected link: {lk}\")\n return lk\n self.logger.warning(\"No suitable link selected.\")\n return None\n \n def get_page_text(self, limit_to_model_ctx = False) -> str:\n \"\"\"Get the text content of the current page.\"\"\"\n page_text = self.browser.get_text()\n if limit_to_model_ctx:\n #page_text = self.memory.compress_text_to_max_ctx(page_text)\n page_text = self.memory.trim_text_to_max_ctx(page_text)\n return page_text\n \n def conclude_prompt(self, user_query: str) -> str:\n annotated_notes = [f\"{i+1}: {note.lower()}\" for i, note in enumerate(self.notes)]\n search_note = '\\n'.join(annotated_notes)\n pretty_print(f\"AI notes:\\n{search_note}\", color=\"success\")\n return f\"\"\"\n Following a human request:\n {user_query}\n A web browsing AI made the following finding across different pages:\n {search_note}\n\n Expand on the finding or step that lead to success, and provide a conclusion that answer the request. Include link when possible.\n Do not give advices or try to answer the human. Just structure the AI finding in a structured and clear way.\n You should answer in the same language as the user.\n \"\"\"\n \n def search_prompt(self, user_prompt: str) -> str:\n return f\"\"\"\n Current date: {self.date}\n Make a efficient search engine query to help users with their request:\n {user_prompt}\n Example:\n User: \"go to twitter, login with username toto and password pass79 to my twitter and say hello everyone \"\n You: search: Twitter login page. \n\n User: \"I need info on the best laptops for AI this year.\"\n You: \"search: best laptops 2025 to run Machine Learning model, reviews\"\n\n User: \"Search for recent news about space missions.\"\n You: \"search: Recent space missions news, {self.date}\"\n\n Do not explain, do not write anything beside the search query.\n Except if query does not make any sense for a web search then explain why and say {Action.REQUEST_EXIT.value}\n Do not try to answer query. you can only formulate search term or exit.\n \"\"\"\n \n def handle_update_prompt(self, user_prompt: str, page_text: str, fill_success: bool) -> str:\n prompt = f\"\"\"\n You are a web browser.\n You just filled a form on the page.\n Now you should see the result of the form submission on the page:\n Page text:\n {page_text}\n The user asked: {user_prompt}\n Does the page answer the user’s query now? Are you still on a login page or did you get redirected?\n If it does, take notes of the useful information, write down result and say {Action.FORM_FILLED.value}.\n if it doesn’t, say: Error: Attempt to fill form didn't work {Action.GO_BACK.value}.\n If you were previously on a login form, no need to take notes.\n \"\"\"\n if not fill_success:\n prompt += f\"\"\"\n According to browser feedback, the form was not filled correctly. Is that so? you might consider other strategies.\n \"\"\"\n return prompt\n \n def show_search_results(self, search_result: List[str]):\n pretty_print(\"\\nSearch results:\", color=\"output\")\n for res in search_result:\n pretty_print(f\"Title: {res['title']} - \", color=\"info\", no_newline=True)\n pretty_print(f\"Link: {res['link']}\", color=\"status\")\n \n def stuck_prompt(self, user_prompt: str, unvisited: List[str]) -> str:\n \"\"\"\n Prompt for when the agent repeat itself, can happen when fail to extract a link.\n \"\"\"\n prompt = self.make_newsearch_prompt(user_prompt, unvisited)\n prompt += f\"\"\"\n You previously said:\n {self.last_answer}\n You must consider other options. Choose other link.\n \"\"\"\n return prompt\n \n async def process(self, user_prompt: str, speech_module: type) -> Tuple[str, str]:\n \"\"\"\n Process the user prompt to conduct an autonomous web search.\n Start with a google search with searxng using web_search tool.\n Then enter a navigation logic to find the answer or conduct required actions.\n Args:\n user_prompt: The user's input query\n speech_module: Optional speech output module\n Returns:\n tuple containing the final answer and reasoning\n \"\"\"\n complete = False\n\n animate_thinking(f\"Thinking...\", color=\"status\")\n mem_begin_idx = self.memory.push('user', self.search_prompt(user_prompt))\n ai_prompt, reasoning = await self.llm_request()\n if Action.REQUEST_EXIT.value in ai_prompt:\n pretty_print(f\"Web agent requested exit.\\n{reasoning}\\n\\n{ai_prompt}\", color=\"failure\")\n return ai_prompt, \"\" \n animate_thinking(f\"Searching...\", color=\"status\")\n self.status_message = \"Searching...\"\n search_result_raw = self.tools[\"web_search\"].execute([ai_prompt], False)\n search_result = self.jsonify_search_results(search_result_raw)[:16]\n self.show_search_results(search_result)\n prompt = self.make_newsearch_prompt(user_prompt, search_result)\n unvisited = [None]\n while not complete and len(unvisited) > 0 and not self.stop:\n self.memory.clear()\n unvisited = self.select_unvisited(search_result)\n answer, reasoning = await self.llm_decide(prompt, show_reasoning = False)\n if self.stop:\n pretty_print(f\"Requested stop.\", color=\"failure\")\n break\n if self.last_answer == answer:\n prompt = self.stuck_prompt(user_prompt, unvisited)\n continue\n self.last_answer = answer\n pretty_print('▂'*32, color=\"status\")\n\n extracted_form = self.extract_form(answer)\n if len(extracted_form) > 0:\n self.status_message = \"Filling web form...\"\n pretty_print(f\"Filling inputs form...\", color=\"status\")\n fill_success = self.browser.fill_form(extracted_form)\n page_text = self.get_page_text(limit_to_model_ctx=True)\n answer = self.handle_update_prompt(user_prompt, page_text, fill_success)\n answer, reasoning = await self.llm_decide(prompt)\n\n if Action.FORM_FILLED.value in answer:\n pretty_print(f\"Filled form. Handling page update.\", color=\"status\")\n page_text = self.get_page_text(limit_to_model_ctx=True)\n self.navigable_links = self.browser.get_navigable()\n prompt = self.make_navigation_prompt(user_prompt, page_text)\n continue\n\n links = self.parse_answer(answer)\n link = self.select_link(links)\n if link == self.current_page:\n pretty_print(f\"Already visited {link}. Search callback.\", color=\"status\")\n prompt = self.make_newsearch_prompt(user_prompt, unvisited)\n self.search_history.append(link)\n continue\n\n if Action.REQUEST_EXIT.value in answer:\n self.status_message = \"Exiting web browser...\"\n pretty_print(f\"Agent requested exit.\", color=\"status\")\n complete = True\n break\n\n if (link == None and len(extracted_form) < 3) or Action.GO_BACK.value in answer or link in self.search_history:\n pretty_print(f\"Going back to results. Still {len(unvisited)}\", color=\"status\")\n self.status_message = \"Going back to search results...\"\n request_prompt = user_prompt\n if link is None:\n request_prompt += f\"\\nYou previously choosen:\\n{self.last_answer} but the website is unavailable. Consider other options.\"\n prompt = self.make_newsearch_prompt(request_prompt, unvisited)\n self.search_history.append(link)\n self.current_page = link\n continue\n\n animate_thinking(f\"Navigating to {link}\", color=\"status\")\n if speech_module: speech_module.speak(f\"Navigating to {link}\")\n nav_ok = self.browser.go_to(link)\n self.search_history.append(link)\n if not nav_ok:\n pretty_print(f\"Failed to navigate to {link}.\", color=\"failure\")\n prompt = self.make_newsearch_prompt(user_prompt, unvisited)\n continue\n self.current_page = link\n page_text = self.get_page_text(limit_to_model_ctx=True)\n self.navigable_links = self.browser.get_navigable()\n prompt = self.make_navigation_prompt(user_prompt, page_text)\n self.status_message = \"Navigating...\"\n self.browser.screenshot()\n\n pretty_print(\"Exited navigation, starting to summarize finding...\", color=\"status\")\n prompt = self.conclude_prompt(user_prompt)\n mem_last_idx = self.memory.push('user', prompt)\n self.status_message = \"Summarizing findings...\"\n answer, reasoning = await self.llm_request()\n pretty_print(answer, color=\"output\")\n self.status_message = \"Ready\"\n self.last_answer = answer\n return answer, reasoning\n\nif __name__ == \"__main__\":\n pass\n"], ["/agenticSeek/cli.py", "#!/usr/bin python3\n\nimport sys\nimport argparse\nimport configparser\nimport asyncio\n\nfrom sources.llm_provider import Provider\nfrom sources.interaction import Interaction\nfrom sources.agents import Agent, CoderAgent, CasualAgent, FileAgent, PlannerAgent, BrowserAgent, McpAgent\nfrom sources.browser import Browser, create_driver\nfrom sources.utility import pretty_print\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\nasync def main():\n pretty_print(\"Initializing...\", color=\"status\")\n stealth_mode = config.getboolean('BROWSER', 'stealth_mode')\n personality_folder = \"jarvis\" if config.getboolean('MAIN', 'jarvis_personality') else \"base\"\n languages = config[\"MAIN\"][\"languages\"].split(' ')\n\n provider = Provider(provider_name=config[\"MAIN\"][\"provider_name\"],\n model=config[\"MAIN\"][\"provider_model\"],\n server_address=config[\"MAIN\"][\"provider_server_address\"],\n is_local=config.getboolean('MAIN', 'is_local'))\n\n browser = Browser(\n create_driver(headless=config.getboolean('BROWSER', 'headless_browser'), stealth_mode=stealth_mode, lang=languages[0]),\n anticaptcha_manual_install=stealth_mode\n )\n\n agents = [\n CasualAgent(name=config[\"MAIN\"][\"agent_name\"],\n prompt_path=f\"prompts/{personality_folder}/casual_agent.txt\",\n provider=provider, verbose=False),\n CoderAgent(name=\"coder\",\n prompt_path=f\"prompts/{personality_folder}/coder_agent.txt\",\n provider=provider, verbose=False),\n FileAgent(name=\"File Agent\",\n prompt_path=f\"prompts/{personality_folder}/file_agent.txt\",\n provider=provider, verbose=False),\n BrowserAgent(name=\"Browser\",\n prompt_path=f\"prompts/{personality_folder}/browser_agent.txt\",\n provider=provider, verbose=False, browser=browser),\n PlannerAgent(name=\"Planner\",\n prompt_path=f\"prompts/{personality_folder}/planner_agent.txt\",\n provider=provider, verbose=False, browser=browser),\n #McpAgent(name=\"MCP Agent\",\n # prompt_path=f\"prompts/{personality_folder}/mcp_agent.txt\",\n # provider=provider, verbose=False), # NOTE under development\n ]\n\n interaction = Interaction(agents,\n tts_enabled=config.getboolean('MAIN', 'speak'),\n stt_enabled=config.getboolean('MAIN', 'listen'),\n recover_last_session=config.getboolean('MAIN', 'recover_last_session'),\n langs=languages\n )\n try:\n while interaction.is_active:\n interaction.get_user()\n if await interaction.think():\n interaction.show_answer()\n interaction.speak_answer()\n except Exception as e:\n if config.getboolean('MAIN', 'save_session'):\n interaction.save_session()\n raise e\n finally:\n if config.getboolean('MAIN', 'save_session'):\n interaction.save_session()\n\nif __name__ == \"__main__\":\n asyncio.run(main())"], ["/agenticSeek/api.py", "#!/usr/bin/env python3\n\nimport os, sys\nimport uvicorn\nimport aiofiles\nimport configparser\nimport asyncio\nimport time\nfrom typing import List\nfrom fastapi import FastAPI\nfrom fastapi.responses import JSONResponse\nfrom fastapi.responses import FileResponse\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom fastapi.staticfiles import StaticFiles\nimport uuid\n\nfrom sources.llm_provider import Provider\nfrom sources.interaction import Interaction\nfrom sources.agents import CasualAgent, CoderAgent, FileAgent, PlannerAgent, BrowserAgent\nfrom sources.browser import Browser, create_driver\nfrom sources.utility import pretty_print\nfrom sources.logger import Logger\nfrom sources.schemas import QueryRequest, QueryResponse\n\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\n\ndef is_running_in_docker():\n \"\"\"Detect if code is running inside a Docker container.\"\"\"\n # Method 1: Check for .dockerenv file\n if os.path.exists('/.dockerenv'):\n return True\n \n # Method 2: Check cgroup\n try:\n with open('/proc/1/cgroup', 'r') as f:\n return 'docker' in f.read()\n except:\n pass\n \n return False\n\n\nfrom celery import Celery\n\napi = FastAPI(title=\"AgenticSeek API\", version=\"0.1.0\")\ncelery_app = Celery(\"tasks\", broker=\"redis://localhost:6379/0\", backend=\"redis://localhost:6379/0\")\ncelery_app.conf.update(task_track_started=True)\nlogger = Logger(\"backend.log\")\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\napi.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"],\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\nif not os.path.exists(\".screenshots\"):\n os.makedirs(\".screenshots\")\napi.mount(\"/screenshots\", StaticFiles(directory=\".screenshots\"), name=\"screenshots\")\n\ndef initialize_system():\n stealth_mode = config.getboolean('BROWSER', 'stealth_mode')\n personality_folder = \"jarvis\" if config.getboolean('MAIN', 'jarvis_personality') else \"base\"\n languages = config[\"MAIN\"][\"languages\"].split(' ')\n \n # Force headless mode in Docker containers\n headless = config.getboolean('BROWSER', 'headless_browser')\n if is_running_in_docker() and not headless:\n # Print prominent warning to console (visible in docker-compose output)\n print(\"\\n\" + \"*\" * 70)\n print(\"*** WARNING: Detected Docker environment - forcing headless_browser=True ***\")\n print(\"*** INFO: To see the browser, run 'python cli.py' on your host machine ***\")\n print(\"*\" * 70 + \"\\n\")\n \n # Flush to ensure it's displayed immediately\n sys.stdout.flush()\n \n # Also log to file\n logger.warning(\"Detected Docker environment - forcing headless_browser=True\")\n logger.info(\"To see the browser, run 'python cli.py' on your host machine instead\")\n \n headless = True\n \n provider = Provider(\n provider_name=config[\"MAIN\"][\"provider_name\"],\n model=config[\"MAIN\"][\"provider_model\"],\n server_address=config[\"MAIN\"][\"provider_server_address\"],\n is_local=config.getboolean('MAIN', 'is_local')\n )\n logger.info(f\"Provider initialized: {provider.provider_name} ({provider.model})\")\n\n browser = Browser(\n create_driver(headless=headless, stealth_mode=stealth_mode, lang=languages[0]),\n anticaptcha_manual_install=stealth_mode\n )\n logger.info(\"Browser initialized\")\n\n agents = [\n CasualAgent(\n name=config[\"MAIN\"][\"agent_name\"],\n prompt_path=f\"prompts/{personality_folder}/casual_agent.txt\",\n provider=provider, verbose=False\n ),\n CoderAgent(\n name=\"coder\",\n prompt_path=f\"prompts/{personality_folder}/coder_agent.txt\",\n provider=provider, verbose=False\n ),\n FileAgent(\n name=\"File Agent\",\n prompt_path=f\"prompts/{personality_folder}/file_agent.txt\",\n provider=provider, verbose=False\n ),\n BrowserAgent(\n name=\"Browser\",\n prompt_path=f\"prompts/{personality_folder}/browser_agent.txt\",\n provider=provider, verbose=False, browser=browser\n ),\n PlannerAgent(\n name=\"Planner\",\n prompt_path=f\"prompts/{personality_folder}/planner_agent.txt\",\n provider=provider, verbose=False, browser=browser\n )\n ]\n logger.info(\"Agents initialized\")\n\n interaction = Interaction(\n agents,\n tts_enabled=config.getboolean('MAIN', 'speak'),\n stt_enabled=config.getboolean('MAIN', 'listen'),\n recover_last_session=config.getboolean('MAIN', 'recover_last_session'),\n langs=languages\n )\n logger.info(\"Interaction initialized\")\n return interaction\n\ninteraction = initialize_system()\nis_generating = False\nquery_resp_history = []\n\n@api.get(\"/screenshot\")\nasync def get_screenshot():\n logger.info(\"Screenshot endpoint called\")\n screenshot_path = \".screenshots/updated_screen.png\"\n if os.path.exists(screenshot_path):\n return FileResponse(screenshot_path)\n logger.error(\"No screenshot available\")\n return JSONResponse(\n status_code=404,\n content={\"error\": \"No screenshot available\"}\n )\n\n@api.get(\"/health\")\nasync def health_check():\n logger.info(\"Health check endpoint called\")\n return {\"status\": \"healthy\", \"version\": \"0.1.0\"}\n\n@api.get(\"/is_active\")\nasync def is_active():\n logger.info(\"Is active endpoint called\")\n return {\"is_active\": interaction.is_active}\n\n@api.get(\"/stop\")\nasync def stop():\n logger.info(\"Stop endpoint called\")\n interaction.current_agent.request_stop()\n return JSONResponse(status_code=200, content={\"status\": \"stopped\"})\n\n@api.get(\"/latest_answer\")\nasync def get_latest_answer():\n global query_resp_history\n if interaction.current_agent is None:\n return JSONResponse(status_code=404, content={\"error\": \"No agent available\"})\n uid = str(uuid.uuid4())\n if not any(q[\"answer\"] == interaction.current_agent.last_answer for q in query_resp_history):\n query_resp = {\n \"done\": \"false\",\n \"answer\": interaction.current_agent.last_answer,\n \"reasoning\": interaction.current_agent.last_reasoning,\n \"agent_name\": interaction.current_agent.agent_name if interaction.current_agent else \"None\",\n \"success\": interaction.current_agent.success,\n \"blocks\": {f'{i}': block.jsonify() for i, block in enumerate(interaction.get_last_blocks_result())} if interaction.current_agent else {},\n \"status\": interaction.current_agent.get_status_message if interaction.current_agent else \"No status available\",\n \"uid\": uid\n }\n interaction.current_agent.last_answer = \"\"\n interaction.current_agent.last_reasoning = \"\"\n query_resp_history.append(query_resp)\n return JSONResponse(status_code=200, content=query_resp)\n if query_resp_history:\n return JSONResponse(status_code=200, content=query_resp_history[-1])\n return JSONResponse(status_code=404, content={\"error\": \"No answer available\"})\n\nasync def think_wrapper(interaction, query):\n try:\n interaction.last_query = query\n logger.info(\"Agents request is being processed\")\n success = await interaction.think()\n if not success:\n interaction.last_answer = \"Error: No answer from agent\"\n interaction.last_reasoning = \"Error: No reasoning from agent\"\n interaction.last_success = False\n else:\n interaction.last_success = True\n pretty_print(interaction.last_answer)\n interaction.speak_answer()\n return success\n except Exception as e:\n logger.error(f\"Error in think_wrapper: {str(e)}\")\n interaction.last_answer = f\"\"\n interaction.last_reasoning = f\"Error: {str(e)}\"\n interaction.last_success = False\n raise e\n\n@api.post(\"/query\", response_model=QueryResponse)\nasync def process_query(request: QueryRequest):\n global is_generating, query_resp_history\n logger.info(f\"Processing query: {request.query}\")\n query_resp = QueryResponse(\n done=\"false\",\n answer=\"\",\n reasoning=\"\",\n agent_name=\"Unknown\",\n success=\"false\",\n blocks={},\n status=\"Ready\",\n uid=str(uuid.uuid4())\n )\n if is_generating:\n logger.warning(\"Another query is being processed, please wait.\")\n return JSONResponse(status_code=429, content=query_resp.jsonify())\n\n try:\n is_generating = True\n success = await think_wrapper(interaction, request.query)\n is_generating = False\n\n if not success:\n query_resp.answer = interaction.last_answer\n query_resp.reasoning = interaction.last_reasoning\n return JSONResponse(status_code=400, content=query_resp.jsonify())\n\n if interaction.current_agent:\n blocks_json = {f'{i}': block.jsonify() for i, block in enumerate(interaction.current_agent.get_blocks_result())}\n else:\n logger.error(\"No current agent found\")\n blocks_json = {}\n query_resp.answer = \"Error: No current agent\"\n return JSONResponse(status_code=400, content=query_resp.jsonify())\n\n logger.info(f\"Answer: {interaction.last_answer}\")\n logger.info(f\"Blocks: {blocks_json}\")\n query_resp.done = \"true\"\n query_resp.answer = interaction.last_answer\n query_resp.reasoning = interaction.last_reasoning\n query_resp.agent_name = interaction.current_agent.agent_name\n query_resp.success = str(interaction.last_success)\n query_resp.blocks = blocks_json\n \n query_resp_dict = {\n \"done\": query_resp.done,\n \"answer\": query_resp.answer,\n \"agent_name\": query_resp.agent_name,\n \"success\": query_resp.success,\n \"blocks\": query_resp.blocks,\n \"status\": query_resp.status,\n \"uid\": query_resp.uid\n }\n query_resp_history.append(query_resp_dict)\n\n logger.info(\"Query processed successfully\")\n return JSONResponse(status_code=200, content=query_resp.jsonify())\n except Exception as e:\n logger.error(f\"An error occurred: {str(e)}\")\n sys.exit(1)\n finally:\n logger.info(\"Processing finished\")\n if config.getboolean('MAIN', 'save_session'):\n interaction.save_session()\n\nif __name__ == \"__main__\":\n # Print startup info\n if is_running_in_docker():\n print(\"[AgenticSeek] Starting in Docker container...\")\n else:\n print(\"[AgenticSeek] Starting on host machine...\")\n \n envport = os.getenv(\"BACKEND_PORT\")\n if envport:\n port = int(envport)\n else:\n port = 7777\n uvicorn.run(api, host=\"0.0.0.0\", port=7777)"], ["/agenticSeek/sources/memory.py", "import time\nimport datetime\nimport uuid\nimport os\nimport sys\nimport json\nfrom typing import List, Tuple, Type, Dict\nimport torch\nfrom transformers import AutoTokenizer, AutoModelForSeq2SeqLM\nimport configparser\n\nfrom sources.utility import timer_decorator, pretty_print, animate_thinking\nfrom sources.logger import Logger\n\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\nclass Memory():\n \"\"\"\n Memory is a class for managing the conversation memory\n It provides a method to compress the memory using summarization model.\n \"\"\"\n def __init__(self, system_prompt: str,\n recover_last_session: bool = False,\n memory_compression: bool = True,\n model_provider: str = \"deepseek-r1:14b\"):\n self.memory = [{'role': 'system', 'content': system_prompt}]\n \n self.logger = Logger(\"memory.log\")\n self.session_time = datetime.datetime.now()\n self.session_id = str(uuid.uuid4())\n self.conversation_folder = f\"conversations/\"\n self.session_recovered = False\n if recover_last_session:\n self.load_memory()\n self.session_recovered = True\n # memory compression system\n self.model = None\n self.tokenizer = None\n self.device = self.get_cuda_device()\n self.memory_compression = memory_compression\n self.model_provider = model_provider\n if self.memory_compression:\n self.download_model()\n\n def get_ideal_ctx(self, model_name: str) -> int | None:\n \"\"\"\n Estimate context size based on the model name.\n EXPERIMENTAL for memory compression\n \"\"\"\n import re\n import math\n\n def extract_number_before_b(sentence: str) -> int:\n match = re.search(r'(\\d+)b', sentence, re.IGNORECASE)\n return int(match.group(1)) if match else None\n\n model_size = extract_number_before_b(model_name)\n if not model_size:\n return None\n base_size = 7 # Base model size in billions\n base_context = 4096 # Base context size in tokens\n scaling_factor = 1.5 # Approximate scaling factor for context size growth\n context_size = int(base_context * (model_size / base_size) ** scaling_factor)\n context_size = 2 ** round(math.log2(context_size))\n self.logger.info(f\"Estimated context size for {model_name}: {context_size} tokens.\")\n return context_size\n \n def download_model(self):\n \"\"\"Download the model if not already downloaded.\"\"\"\n animate_thinking(\"Loading memory compression model...\", color=\"status\")\n self.tokenizer = AutoTokenizer.from_pretrained(\"pszemraj/led-base-book-summary\")\n self.model = AutoModelForSeq2SeqLM.from_pretrained(\"pszemraj/led-base-book-summary\")\n self.logger.info(\"Memory compression system initialized.\")\n \n def get_filename(self) -> str:\n \"\"\"Get the filename for the save file.\"\"\"\n return f\"memory_{self.session_time.strftime('%Y-%m-%d_%H-%M-%S')}.txt\"\n \n def save_memory(self, agent_type: str = \"casual_agent\") -> None:\n \"\"\"Save the session memory to a file.\"\"\"\n if not os.path.exists(self.conversation_folder):\n self.logger.info(f\"Created folder {self.conversation_folder}.\")\n os.makedirs(self.conversation_folder)\n save_path = os.path.join(self.conversation_folder, agent_type)\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n filename = self.get_filename()\n path = os.path.join(save_path, filename)\n json_memory = json.dumps(self.memory)\n with open(path, 'w') as f:\n self.logger.info(f\"Saved memory json at {path}\")\n f.write(json_memory)\n \n def find_last_session_path(self, path) -> str:\n \"\"\"Find the last session path.\"\"\"\n saved_sessions = []\n for filename in os.listdir(path):\n if filename.startswith('memory_'):\n date = filename.split('_')[1]\n saved_sessions.append((filename, date))\n saved_sessions.sort(key=lambda x: x[1], reverse=True)\n if len(saved_sessions) > 0:\n self.logger.info(f\"Last session found at {saved_sessions[0][0]}\")\n return saved_sessions[0][0]\n return None\n \n def save_json_file(self, path: str, json_memory: dict) -> None:\n \"\"\"Save a JSON file.\"\"\"\n try:\n with open(path, 'w') as f:\n json.dump(json_memory, f)\n self.logger.info(f\"Saved memory json at {path}\")\n except Exception as e:\n self.logger.warning(f\"Error saving file {path}: {e}\")\n \n def load_json_file(self, path: str) -> dict:\n \"\"\"Load a JSON file.\"\"\"\n json_memory = {}\n try:\n with open(path, 'r') as f:\n json_memory = json.load(f)\n except FileNotFoundError:\n self.logger.warning(f\"File not found: {path}\")\n return {}\n except json.JSONDecodeError:\n self.logger.warning(f\"Error decoding JSON from file: {path}\")\n return {}\n except Exception as e:\n self.logger.warning(f\"Error loading file {path}: {e}\")\n return {}\n return json_memory\n\n def load_memory(self, agent_type: str = \"casual_agent\") -> None:\n \"\"\"Load the memory from the last session.\"\"\"\n if self.session_recovered == True:\n return\n pretty_print(f\"Loading {agent_type} past memories... \", color=\"status\")\n save_path = os.path.join(self.conversation_folder, agent_type)\n if not os.path.exists(save_path):\n pretty_print(\"No memory to load.\", color=\"success\")\n return\n filename = self.find_last_session_path(save_path)\n if filename is None:\n pretty_print(\"Last session memory not found.\", color=\"warning\")\n return\n path = os.path.join(save_path, filename)\n self.memory = self.load_json_file(path) \n if self.memory[-1]['role'] == 'user':\n self.memory.pop()\n self.compress()\n pretty_print(\"Session recovered successfully\", color=\"success\")\n \n def reset(self, memory: list = []) -> None:\n self.logger.info(\"Memory reset performed.\")\n self.memory = memory\n \n def push(self, role: str, content: str) -> int:\n \"\"\"Push a message to the memory.\"\"\"\n ideal_ctx = self.get_ideal_ctx(self.model_provider)\n if ideal_ctx is not None:\n if self.memory_compression and len(content) > ideal_ctx * 1.5:\n self.logger.info(f\"Compressing memory: Content {len(content)} > {ideal_ctx} model context.\")\n self.compress()\n curr_idx = len(self.memory)\n if self.memory[curr_idx-1]['content'] == content:\n pretty_print(\"Warning: same message have been pushed twice to memory\", color=\"error\")\n time_str = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n if config[\"MAIN\"][\"provider_name\"] == \"openrouter\":\n self.memory.append({'role': role, 'content': content})\n else:\n self.memory.append({'role': role, 'content': content, 'time': time_str, 'model_used': self.model_provider})\n return curr_idx-1\n \n def clear(self) -> None:\n \"\"\"Clear all memory except system prompt\"\"\"\n self.logger.info(\"Memory clear performed.\")\n self.memory = self.memory[:1]\n \n def clear_section(self, start: int, end: int) -> None:\n \"\"\"\n Clear a section of the memory. Ignore system message index.\n Args:\n start (int): Starting bound of the section to clear.\n end (int): Ending bound of the section to clear.\n \"\"\"\n self.logger.info(f\"Clearing memory section {start} to {end}.\")\n start = max(0, start) + 1\n end = min(end, len(self.memory)-1) + 2\n self.memory = self.memory[:start] + self.memory[end:]\n \n def get(self) -> list:\n return self.memory\n\n def get_cuda_device(self) -> str:\n if torch.backends.mps.is_available():\n return \"mps\"\n elif torch.cuda.is_available():\n return \"cuda\"\n else:\n return \"cpu\"\n\n def summarize(self, text: str, min_length: int = 64) -> str:\n \"\"\"\n Summarize the text using the AI model.\n Args:\n text (str): The text to summarize\n min_length (int, optional): The minimum length of the summary. Defaults to 64.\n Returns:\n str: The summarized text\n \"\"\"\n if self.tokenizer is None or self.model is None:\n self.logger.warning(\"No tokenizer or model to perform summarization.\")\n return text\n if len(text) < min_length*1.5:\n return text\n max_length = len(text) // 2 if len(text) > min_length*2 else min_length*2\n input_text = \"summarize: \" + text\n inputs = self.tokenizer(input_text, return_tensors=\"pt\", max_length=512, truncation=True)\n summary_ids = self.model.generate(\n inputs['input_ids'],\n max_length=max_length,\n min_length=min_length,\n length_penalty=1.0,\n num_beams=4,\n early_stopping=True\n )\n summary = self.tokenizer.decode(summary_ids[0], skip_special_tokens=True)\n summary.replace('summary:', '')\n self.logger.info(f\"Memory summarized from len {len(text)} to {len(summary)}.\")\n self.logger.info(f\"Summarized text:\\n{summary}\")\n return summary\n \n #@timer_decorator\n def compress(self) -> str:\n \"\"\"\n Compress (summarize) the memory using the model.\n \"\"\"\n if self.tokenizer is None or self.model is None:\n self.logger.warning(\"No tokenizer or model to perform memory compression.\")\n return\n for i in range(len(self.memory)):\n if self.memory[i]['role'] == 'system':\n continue\n if len(self.memory[i]['content']) > 1024:\n self.memory[i]['content'] = self.summarize(self.memory[i]['content'])\n \n def trim_text_to_max_ctx(self, text: str) -> str:\n \"\"\"\n Truncate a text to fit within the maximum context size of the model.\n \"\"\"\n ideal_ctx = self.get_ideal_ctx(self.model_provider)\n return text[:ideal_ctx] if ideal_ctx is not None else text\n \n #@timer_decorator\n def compress_text_to_max_ctx(self, text) -> str:\n \"\"\"\n Compress a text to fit within the maximum context size of the model.\n \"\"\"\n if self.tokenizer is None or self.model is None:\n self.logger.warning(\"No tokenizer or model to perform memory compression.\")\n return text\n ideal_ctx = self.get_ideal_ctx(self.model_provider)\n if ideal_ctx is None:\n self.logger.warning(\"No ideal context size found.\")\n return text\n while len(text) > ideal_ctx:\n self.logger.info(f\"Compressing text: {len(text)} > {ideal_ctx} model context.\")\n text = self.summarize(text)\n return text\n\nif __name__ == \"__main__\":\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n memory = Memory(\"You are a helpful assistant.\",\n recover_last_session=False, memory_compression=True)\n\n memory.push('user', \"hello\")\n memory.push('assistant', \"how can i help you?\")\n memory.push('user', \"why do i get this cuda error?\")\n sample_text = \"\"\"\nThe error you're encountering:\ncuda.cu:52:10: fatal error: helper_functions.h: No such file or directory\n #include \nindicates that the compiler cannot find the helper_functions.h file. This is because the #include directive is looking for the file in the system's include paths, but the file is either not in those paths or is located in a different directory.\n1. Use #include \"helper_functions.h\" Instead of #include \nAngle brackets (< >) are used for system or standard library headers.\nQuotes (\" \") are used for local or project-specific headers.\nIf helper_functions.h is in the same directory as cuda.cu, change the include directive to:\n3. Verify the File Exists\nDouble-check that helper_functions.h exists in the specified location. If the file is missing, you'll need to obtain or recreate it.\n4. Use the Correct CUDA Samples Path (if applicable)\nIf helper_functions.h is part of the CUDA Samples, ensure you have the CUDA Samples installed and include the correct path. For example, on Linux, the CUDA Samples are typically located in /usr/local/cuda/samples/common/inc. You can include this path like so:\nUse #include \"helper_functions.h\" for local files.\nUse the -I flag to specify the directory containing helper_functions.h.\nEnsure the file exists in the specified location.\n \"\"\"\n memory.push('assistant', sample_text)\n \n print(\"\\n---\\nmemory before:\", memory.get())\n memory.compress()\n print(\"\\n---\\nmemory after:\", memory.get())\n #memory.save_memory()\n "], ["/agenticSeek/sources/interaction.py", "import readline\nfrom typing import List, Tuple, Type, Dict\n\nfrom sources.text_to_speech import Speech\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.router import AgentRouter\nfrom sources.speech_to_text import AudioTranscriber, AudioRecorder\nimport threading\n\n\nclass Interaction:\n \"\"\"\n Interaction is a class that handles the interaction between the user and the agents.\n \"\"\"\n def __init__(self, agents,\n tts_enabled: bool = True,\n stt_enabled: bool = True,\n recover_last_session: bool = False,\n langs: List[str] = [\"en\", \"zh\"]\n ):\n self.is_active = True\n self.current_agent = None\n self.last_query = None\n self.last_answer = None\n self.last_reasoning = None\n self.agents = agents\n self.tts_enabled = tts_enabled\n self.stt_enabled = stt_enabled\n self.recover_last_session = recover_last_session\n self.router = AgentRouter(self.agents, supported_language=langs)\n self.ai_name = self.find_ai_name()\n self.speech = None\n self.transcriber = None\n self.recorder = None\n self.is_generating = False\n self.languages = langs\n if tts_enabled:\n self.initialize_tts()\n if stt_enabled:\n self.initialize_stt()\n if recover_last_session:\n self.load_last_session()\n self.emit_status()\n \n def get_spoken_language(self) -> str:\n \"\"\"Get the primary TTS language.\"\"\"\n lang = self.languages[0]\n return lang\n\n def initialize_tts(self):\n \"\"\"Initialize TTS.\"\"\"\n if not self.speech:\n animate_thinking(\"Initializing text-to-speech...\", color=\"status\")\n self.speech = Speech(enable=self.tts_enabled, language=self.get_spoken_language(), voice_idx=1)\n\n def initialize_stt(self):\n \"\"\"Initialize STT.\"\"\"\n if not self.transcriber or not self.recorder:\n animate_thinking(\"Initializing speech recognition...\", color=\"status\")\n self.transcriber = AudioTranscriber(self.ai_name, verbose=False)\n self.recorder = AudioRecorder()\n \n def emit_status(self):\n \"\"\"Print the current status of agenticSeek.\"\"\"\n if self.stt_enabled:\n pretty_print(f\"Text-to-speech trigger is {self.ai_name}\", color=\"status\")\n if self.tts_enabled:\n self.speech.speak(\"Hello, we are online and ready. What can I do for you ?\")\n pretty_print(\"AgenticSeek is ready.\", color=\"status\")\n \n def find_ai_name(self) -> str:\n \"\"\"Find the name of the default AI. It is required for STT as a trigger word.\"\"\"\n ai_name = \"jarvis\"\n for agent in self.agents:\n if agent.type == \"casual_agent\":\n ai_name = agent.agent_name\n break\n return ai_name\n \n def get_last_blocks_result(self) -> List[Dict]:\n \"\"\"Get the last blocks result.\"\"\"\n if self.current_agent is None:\n return []\n blks = []\n for agent in self.agents:\n blks.extend(agent.get_blocks_result())\n return blks\n \n def load_last_session(self):\n \"\"\"Recover the last session.\"\"\"\n for agent in self.agents:\n if agent.type == \"planner_agent\":\n continue\n agent.memory.load_memory(agent.type)\n \n def save_session(self):\n \"\"\"Save the current session.\"\"\"\n for agent in self.agents:\n agent.memory.save_memory(agent.type)\n\n def is_active(self) -> bool:\n return self.is_active\n \n def read_stdin(self) -> str:\n \"\"\"Read the input from the user.\"\"\"\n buffer = \"\"\n\n PROMPT = \"\\033[1;35m➤➤➤ \\033[0m\"\n while not buffer:\n try:\n buffer = input(PROMPT)\n except EOFError:\n return None\n if buffer == \"exit\" or buffer == \"goodbye\":\n return None\n return buffer\n \n def transcription_job(self) -> str:\n \"\"\"Transcribe the audio from the microphone.\"\"\"\n self.recorder = AudioRecorder(verbose=True)\n self.transcriber = AudioTranscriber(self.ai_name, verbose=True)\n self.transcriber.start()\n self.recorder.start()\n self.recorder.join()\n self.transcriber.join()\n query = self.transcriber.get_transcript()\n if query == \"exit\" or query == \"goodbye\":\n return None\n return query\n\n def get_user(self) -> str:\n \"\"\"Get the user input from the microphone or the keyboard.\"\"\"\n if self.stt_enabled:\n query = \"TTS transcription of user: \" + self.transcription_job()\n else:\n query = self.read_stdin()\n if query is None:\n self.is_active = False\n self.last_query = None\n return None\n self.last_query = query\n return query\n \n def set_query(self, query: str) -> None:\n \"\"\"Set the query\"\"\"\n self.is_active = True\n self.last_query = query\n \n async def think(self) -> bool:\n \"\"\"Request AI agents to process the user input.\"\"\"\n push_last_agent_memory = False\n if self.last_query is None or len(self.last_query) == 0:\n return False\n agent = self.router.select_agent(self.last_query)\n if agent is None:\n return False\n if self.current_agent != agent and self.last_answer is not None:\n push_last_agent_memory = True\n tmp = self.last_answer\n self.current_agent = agent\n self.is_generating = True\n self.last_answer, self.last_reasoning = await agent.process(self.last_query, self.speech)\n self.is_generating = False\n if push_last_agent_memory:\n self.current_agent.memory.push('user', self.last_query)\n self.current_agent.memory.push('assistant', self.last_answer)\n if self.last_answer == tmp:\n self.last_answer = None\n return True\n \n def get_updated_process_answer(self) -> str:\n \"\"\"Get the answer from the last agent.\"\"\"\n if self.current_agent is None:\n return None\n return self.current_agent.get_last_answer()\n \n def get_updated_block_answer(self) -> str:\n \"\"\"Get the answer from the last agent.\"\"\"\n if self.current_agent is None:\n return None\n return self.current_agent.get_last_block_answer()\n \n def speak_answer(self) -> None:\n \"\"\"Speak the answer to the user in a non-blocking thread.\"\"\"\n if self.last_query is None:\n return\n if self.tts_enabled and self.last_answer and self.speech:\n def speak_in_thread(speech_instance, text):\n speech_instance.speak(text)\n thread = threading.Thread(target=speak_in_thread, args=(self.speech, self.last_answer))\n thread.start()\n \n def show_answer(self) -> None:\n \"\"\"Show the answer to the user.\"\"\"\n if self.last_query is None:\n return\n if self.current_agent is not None:\n self.current_agent.show_answer()\n\n"], ["/agenticSeek/sources/llm_provider.py", "import os\nimport platform\nimport socket\nimport subprocess\nimport time\nfrom urllib.parse import urlparse\n\nimport httpx\nimport requests\nfrom dotenv import load_dotenv\nfrom ollama import Client as OllamaClient\nfrom openai import OpenAI\n\nfrom sources.logger import Logger\nfrom sources.utility import pretty_print, animate_thinking\n\nclass Provider:\n def __init__(self, provider_name, model, server_address=\"127.0.0.1:5000\", is_local=False):\n self.provider_name = provider_name.lower()\n self.model = model\n self.is_local = is_local\n self.server_ip = server_address\n self.server_address = server_address\n self.available_providers = {\n \"ollama\": self.ollama_fn,\n \"server\": self.server_fn,\n \"openai\": self.openai_fn,\n \"lm-studio\": self.lm_studio_fn,\n \"huggingface\": self.huggingface_fn,\n \"google\": self.google_fn,\n \"deepseek\": self.deepseek_fn,\n \"together\": self.together_fn,\n \"dsk_deepseek\": self.dsk_deepseek,\n \"openrouter\": self.openrouter_fn,\n \"test\": self.test_fn\n }\n self.logger = Logger(\"provider.log\")\n self.api_key = None\n self.internal_url, self.in_docker = self.get_internal_url()\n self.unsafe_providers = [\"openai\", \"deepseek\", \"dsk_deepseek\", \"together\", \"google\", \"openrouter\"]\n if self.provider_name not in self.available_providers:\n raise ValueError(f\"Unknown provider: {provider_name}\")\n if self.provider_name in self.unsafe_providers and self.is_local == False:\n pretty_print(\"Warning: you are using an API provider. You data will be sent to the cloud.\", color=\"warning\")\n self.api_key = self.get_api_key(self.provider_name)\n elif self.provider_name != \"ollama\":\n pretty_print(f\"Provider: {provider_name} initialized at {self.server_ip}\", color=\"success\")\n\n def get_model_name(self) -> str:\n return self.model\n\n def get_api_key(self, provider):\n load_dotenv()\n api_key_var = f\"{provider.upper()}_API_KEY\"\n api_key = os.getenv(api_key_var)\n if not api_key:\n pretty_print(f\"API key {api_key_var} not found in .env file. Please add it\", color=\"warning\")\n exit(1)\n return api_key\n \n def get_internal_url(self):\n load_dotenv()\n url = os.getenv(\"DOCKER_INTERNAL_URL\")\n if not url: # running on host\n return \"http://localhost\", False\n return url, True\n\n def respond(self, history, verbose=True):\n \"\"\"\n Use the choosen provider to generate text.\n \"\"\"\n llm = self.available_providers[self.provider_name]\n self.logger.info(f\"Using provider: {self.provider_name} at {self.server_ip}\")\n try:\n thought = llm(history, verbose)\n except KeyboardInterrupt:\n self.logger.warning(\"User interrupted the operation with Ctrl+C\")\n return \"Operation interrupted by user. REQUEST_EXIT\"\n except ConnectionError as e:\n raise ConnectionError(f\"{str(e)}\\nConnection to {self.server_ip} failed.\")\n except AttributeError as e:\n raise NotImplementedError(f\"{str(e)}\\nIs {self.provider_name} implemented ?\")\n except ModuleNotFoundError as e:\n raise ModuleNotFoundError(\n f\"{str(e)}\\nA import related to provider {self.provider_name} was not found. Is it installed ?\")\n except Exception as e:\n if \"try again later\" in str(e).lower():\n return f\"{self.provider_name} server is overloaded. Please try again later.\"\n if \"refused\" in str(e):\n return f\"Server {self.server_ip} seem offline. Unable to answer.\"\n raise Exception(f\"Provider {self.provider_name} failed: {str(e)}\") from e\n return thought\n\n def is_ip_online(self, address: str, timeout: int = 10) -> bool:\n \"\"\"\n Check if an address is online by sending a ping request.\n \"\"\"\n if not address:\n return False\n parsed = urlparse(address if address.startswith(('http://', 'https://')) else f'http://{address}')\n\n hostname = parsed.hostname or address\n if \"127.0.0.1\" in address or \"localhost\" in address:\n return True\n try:\n ip_address = socket.gethostbyname(hostname)\n except socket.gaierror:\n self.logger.error(f\"Cannot resolve: {hostname}\")\n return False\n param = '-n' if platform.system().lower() == 'windows' else '-c'\n command = ['ping', param, '1', ip_address]\n try:\n result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)\n return result.returncode == 0\n except (subprocess.TimeoutExpired, subprocess.SubprocessError) as e:\n return False\n\n def server_fn(self, history, verbose=False):\n \"\"\"\n Use a remote server with LLM to generate text.\n \"\"\"\n thought = \"\"\n route_setup = f\"{self.server_ip}/setup\"\n route_gen = f\"{self.server_ip}/generate\"\n\n if not self.is_ip_online(self.server_ip):\n pretty_print(f\"Server is offline at {self.server_ip}\", color=\"failure\")\n\n try:\n requests.post(route_setup, json={\"model\": self.model})\n requests.post(route_gen, json={\"messages\": history})\n is_complete = False\n while not is_complete:\n try:\n response = requests.get(f\"{self.server_ip}/get_updated_sentence\")\n if \"error\" in response.json():\n pretty_print(response.json()[\"error\"], color=\"failure\")\n break\n thought = response.json()[\"sentence\"]\n is_complete = bool(response.json()[\"is_complete\"])\n time.sleep(2)\n except requests.exceptions.RequestException as e:\n pretty_print(f\"HTTP request failed: {str(e)}\", color=\"failure\")\n break\n except ValueError as e:\n pretty_print(f\"Failed to parse JSON response: {str(e)}\", color=\"failure\")\n break\n except Exception as e:\n pretty_print(f\"An error occurred: {str(e)}\", color=\"failure\")\n break\n except KeyError as e:\n raise Exception(\n f\"{str(e)}\\nError occured with server route. Are you using the correct address for the config.ini provider?\") from e\n except Exception as e:\n raise e\n return thought\n\n def ollama_fn(self, history, verbose=False):\n \"\"\"\n Use local or remote Ollama server to generate text.\n \"\"\"\n thought = \"\"\n host = f\"{self.internal_url}:11434\" if self.is_local else f\"http://{self.server_address}\"\n client = OllamaClient(host=host)\n\n try:\n stream = client.chat(\n model=self.model,\n messages=history,\n stream=True,\n )\n for chunk in stream:\n if verbose:\n print(chunk[\"message\"][\"content\"], end=\"\", flush=True)\n thought += chunk[\"message\"][\"content\"]\n except httpx.ConnectError as e:\n raise Exception(\n f\"\\nOllama connection failed at {host}. Check if the server is running.\"\n ) from e\n except Exception as e:\n if hasattr(e, 'status_code') and e.status_code == 404:\n animate_thinking(f\"Downloading {self.model}...\")\n client.pull(self.model)\n self.ollama_fn(history, verbose)\n if \"refused\" in str(e).lower():\n raise Exception(\n f\"Ollama connection refused at {host}. Is the server running?\"\n ) from e\n raise e\n\n return thought\n\n def huggingface_fn(self, history, verbose=False):\n \"\"\"\n Use huggingface to generate text.\n \"\"\"\n from huggingface_hub import InferenceClient\n client = InferenceClient(\n api_key=self.get_api_key(\"huggingface\")\n )\n completion = client.chat.completions.create(\n model=self.model,\n messages=history,\n max_tokens=1024,\n )\n thought = completion.choices[0].message\n return thought.content\n\n def openai_fn(self, history, verbose=False):\n \"\"\"\n Use openai to generate text.\n \"\"\"\n base_url = self.server_ip\n if self.is_local and self.in_docker:\n try:\n host, port = base_url.split(':')\n except Exception as e:\n port = \"8000\"\n client = OpenAI(api_key=self.api_key, base_url=f\"{self.internal_url}:{port}\")\n elif self.is_local:\n client = OpenAI(api_key=self.api_key, base_url=f\"http://{base_url}\")\n else:\n client = OpenAI(api_key=self.api_key)\n\n try:\n response = client.chat.completions.create(\n model=self.model,\n messages=history,\n )\n if response is None:\n raise Exception(\"OpenAI response is empty.\")\n thought = response.choices[0].message.content\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"OpenAI API error: {str(e)}\") from e\n\n def anthropic_fn(self, history, verbose=False):\n \"\"\"\n Use Anthropic to generate text.\n \"\"\"\n from anthropic import Anthropic\n\n client = Anthropic(api_key=self.api_key)\n system_message = None\n messages = []\n for message in history:\n clean_message = {'role': message['role'], 'content': message['content']}\n if message['role'] == 'system':\n system_message = message['content']\n else:\n messages.append(clean_message)\n\n try:\n response = client.messages.create(\n model=self.model,\n max_tokens=1024,\n messages=messages,\n system=system_message\n )\n if response is None:\n raise Exception(\"Anthropic response is empty.\")\n thought = response.content[0].text\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"Anthropic API error: {str(e)}\") from e\n\n def google_fn(self, history, verbose=False):\n \"\"\"\n Use google gemini to generate text.\n \"\"\"\n base_url = self.server_ip\n if self.is_local:\n raise Exception(\"Google Gemini is not available for local use. Change config.ini\")\n\n client = OpenAI(api_key=self.api_key, base_url=\"https://generativelanguage.googleapis.com/v1beta/openai/\")\n try:\n response = client.chat.completions.create(\n model=self.model,\n messages=history,\n )\n if response is None:\n raise Exception(\"Google response is empty.\")\n thought = response.choices[0].message.content\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"GOOGLE API error: {str(e)}\") from e\n\n def together_fn(self, history, verbose=False):\n \"\"\"\n Use together AI for completion\n \"\"\"\n from together import Together\n client = Together(api_key=self.api_key)\n if self.is_local:\n raise Exception(\"Together AI is not available for local use. Change config.ini\")\n\n try:\n response = client.chat.completions.create(\n model=self.model,\n messages=history,\n )\n if response is None:\n raise Exception(\"Together AI response is empty.\")\n thought = response.choices[0].message.content\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"Together AI API error: {str(e)}\") from e\n\n def deepseek_fn(self, history, verbose=False):\n \"\"\"\n Use deepseek api to generate text.\n \"\"\"\n client = OpenAI(api_key=self.api_key, base_url=\"https://api.deepseek.com\")\n if self.is_local:\n raise Exception(\"Deepseek (API) is not available for local use. Change config.ini\")\n try:\n response = client.chat.completions.create(\n model=\"deepseek-chat\",\n messages=history,\n stream=False\n )\n thought = response.choices[0].message.content\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"Deepseek API error: {str(e)}\") from e\n\n def lm_studio_fn(self, history, verbose=False):\n \"\"\"\n Use local lm-studio server to generate text.\n \"\"\"\n if self.in_docker:\n # Extract port from server_address if present\n port = \"1234\" # default\n if \":\" in self.server_address:\n port = self.server_address.split(\":\")[1]\n url = f\"{self.internal_url}:{port}\"\n else:\n url = f\"http://{self.server_ip}\"\n route_start = f\"{url}/v1/chat/completions\"\n payload = {\n \"messages\": history,\n \"temperature\": 0.7,\n \"max_tokens\": 4096,\n \"model\": self.model\n }\n\n try:\n response = requests.post(route_start, json=payload, timeout=30)\n if response.status_code != 200:\n raise Exception(f\"LM Studio returned status {response.status_code}: {response.text}\")\n if not response.text.strip():\n raise Exception(\"LM Studio returned empty response\")\n try:\n result = response.json()\n except ValueError as json_err:\n raise Exception(f\"Invalid JSON from LM Studio: {response.text[:200]}\") from json_err\n\n if verbose:\n print(\"Response from LM Studio:\", result)\n choices = result.get(\"choices\", [])\n if not choices:\n raise Exception(f\"No choices in LM Studio response: {result}\")\n\n message = choices[0].get(\"message\", {})\n content = message.get(\"content\", \"\")\n if not content:\n raise Exception(f\"Empty content in LM Studio response: {result}\")\n return content\n\n except requests.exceptions.Timeout:\n raise Exception(\"LM Studio request timed out - check if server is responsive\")\n except requests.exceptions.ConnectionError:\n raise Exception(f\"Cannot connect to LM Studio at {route_start} - check if server is running\")\n except requests.exceptions.RequestException as e:\n raise Exception(f\"HTTP request failed: {str(e)}\") from e\n except Exception as e:\n if \"LM Studio\" in str(e):\n raise # Re-raise our custom exceptions\n raise Exception(f\"Unexpected error: {str(e)}\") from e\n return thought\n\n def openrouter_fn(self, history, verbose=False):\n \"\"\"\n Use OpenRouter API to generate text.\n \"\"\"\n client = OpenAI(api_key=self.api_key, base_url=\"https://openrouter.ai/api/v1\")\n if self.is_local:\n # This case should ideally not be reached if unsafe_providers is set correctly\n # and is_local is False in config for openrouter\n raise Exception(\"OpenRouter is not available for local use. Change config.ini\")\n try:\n response = client.chat.completions.create(\n model=self.model,\n messages=history,\n )\n if response is None:\n raise Exception(\"OpenRouter response is empty.\")\n thought = response.choices[0].message.content\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"OpenRouter API error: {str(e)}\") from e\n\n def dsk_deepseek(self, history, verbose=False):\n \"\"\"\n Use: xtekky/deepseek4free\n For free api. Api key should be set to DSK_DEEPSEEK_API_KEY\n This is an unofficial provider, you'll have to find how to set it up yourself.\n \"\"\"\n from dsk.api import (\n DeepSeekAPI,\n AuthenticationError,\n RateLimitError,\n NetworkError,\n CloudflareError,\n APIError\n )\n thought = \"\"\n message = '\\n---\\n'.join([f\"{msg['role']}: {msg['content']}\" for msg in history])\n\n try:\n api = DeepSeekAPI(self.api_key)\n chat_id = api.create_chat_session()\n for chunk in api.chat_completion(chat_id, message):\n if chunk['type'] == 'text':\n thought += chunk['content']\n return thought\n except AuthenticationError:\n raise AuthenticationError(\"Authentication failed. Please check your token.\") from e\n except RateLimitError:\n raise RateLimitError(\"Rate limit exceeded. Please wait before making more requests.\") from e\n except CloudflareError as e:\n raise CloudflareError(f\"Cloudflare protection encountered: {str(e)}\") from e\n except NetworkError:\n raise NetworkError(\"Network error occurred. Check your internet connection.\") from e\n except APIError as e:\n raise APIError(f\"API error occurred: {str(e)}\") from e\n return None\n\n def test_fn(self, history, verbose=True):\n \"\"\"\n This function is used to conduct tests.\n \"\"\"\n thought = \"\"\"\n\\n\\n```json\\n{\\n \\\"plan\\\": [\\n {\\n \\\"agent\\\": \\\"Web\\\",\\n \\\"id\\\": \\\"1\\\",\\n \\\"need\\\": null,\\n \\\"task\\\": \\\"Conduct a comprehensive web search to identify at least five AI startups located in Osaka. Use reliable sources and websites such as Crunchbase, TechCrunch, or local Japanese business directories. Capture the company names, their websites, areas of expertise, and any other relevant details.\\\"\\n },\\n {\\n \\\"agent\\\": \\\"Web\\\",\\n \\\"id\\\": \\\"2\\\",\\n \\\"need\\\": null,\\n \\\"task\\\": \\\"Perform a similar search to find at least five AI startups in Tokyo. Again, use trusted sources like Crunchbase, TechCrunch, or Japanese business news websites. Gather the same details as for Osaka: company names, websites, areas of focus, and additional information.\\\"\\n },\\n {\\n \\\"agent\\\": \\\"File\\\",\\n \\\"id\\\": \\\"3\\\",\\n \\\"need\\\": [\\\"1\\\", \\\"2\\\"],\\n \\\"task\\\": \\\"Create a new text file named research_japan.txt in the user's home directory. Organize the data collected from both searches into this file, ensuring it is well-structured and formatted for readability. Include headers for Osaka and Tokyo sections, followed by the details of each startup found.\\\"\\n }\\n ]\\n}\\n```\n \"\"\"\n return thought\n\n\nif __name__ == \"__main__\":\n provider = Provider(\"server\", \"deepseek-r1:32b\", \" x.x.x.x:8080\")\n res = provider.respond([\"user\", \"Hello, how are you?\"])\n print(\"Response:\", res)\n"], ["/agenticSeek/sources/router.py", "import os\nimport sys\nimport torch\nimport random\nfrom typing import List, Tuple, Type, Dict\n\nfrom transformers import pipeline\nfrom adaptive_classifier import AdaptiveClassifier\n\nfrom sources.agents.agent import Agent\nfrom sources.agents.code_agent import CoderAgent\nfrom sources.agents.casual_agent import CasualAgent\nfrom sources.agents.planner_agent import FileAgent\nfrom sources.agents.browser_agent import BrowserAgent\nfrom sources.language import LanguageUtility\nfrom sources.utility import pretty_print, animate_thinking, timer_decorator\nfrom sources.logger import Logger\n\nclass AgentRouter:\n \"\"\"\n AgentRouter is a class that selects the appropriate agent based on the user query.\n \"\"\"\n def __init__(self, agents: list, supported_language: List[str] = [\"en\", \"fr\", \"zh\"]):\n self.agents = agents\n self.logger = Logger(\"router.log\")\n self.lang_analysis = LanguageUtility(supported_language=supported_language)\n self.pipelines = self.load_pipelines()\n self.talk_classifier = self.load_llm_router()\n self.complexity_classifier = self.load_llm_router()\n self.learn_few_shots_tasks()\n self.learn_few_shots_complexity()\n self.asked_clarify = False\n \n def load_pipelines(self) -> Dict[str, Type[pipeline]]:\n \"\"\"\n Load the pipelines for the text classification used for routing.\n returns:\n Dict[str, Type[pipeline]]: The loaded pipelines\n \"\"\"\n animate_thinking(\"Loading zero-shot pipeline...\", color=\"status\")\n return {\n \"bart\": pipeline(\"zero-shot-classification\", model=\"facebook/bart-large-mnli\")\n }\n\n def load_llm_router(self) -> AdaptiveClassifier:\n \"\"\"\n Load the LLM router model.\n returns:\n AdaptiveClassifier: The loaded model\n exceptions:\n Exception: If the safetensors fails to load\n \"\"\"\n path = \"../llm_router\" if __name__ == \"__main__\" else \"./llm_router\"\n try:\n animate_thinking(\"Loading LLM router model...\", color=\"status\")\n talk_classifier = AdaptiveClassifier.from_pretrained(path)\n except Exception as e:\n raise Exception(\"Failed to load the routing model. Please run the dl_safetensors.sh script inside llm_router/ directory to download the model.\")\n return talk_classifier\n\n def get_device(self) -> str:\n if torch.backends.mps.is_available():\n return \"mps\"\n elif torch.cuda.is_available():\n return \"cuda:0\"\n else:\n return \"cpu\"\n \n def learn_few_shots_complexity(self) -> None:\n \"\"\"\n Few shot learning for complexity estimation.\n Use the build in add_examples method of the Adaptive_classifier.\n \"\"\"\n few_shots = [\n (\"hi\", \"LOW\"),\n (\"How it's going ?\", \"LOW\"),\n (\"What’s the weather like today?\", \"LOW\"),\n (\"Can you find a file named ‘notes.txt’ in my Documents folder?\", \"LOW\"),\n (\"Write a Python script to generate a random password\", \"LOW\"),\n (\"Debug this JavaScript code that’s not running properly\", \"LOW\"),\n (\"Search the web for the cheapest laptop under $500\", \"LOW\"),\n (\"Locate a file called ‘report_2024.pdf’ on my drive\", \"LOW\"),\n (\"Check if a folder named ‘Backups’ exists on my system\", \"LOW\"),\n (\"Can you find ‘family_vacation.mp4’ in my Videos folder?\", \"LOW\"),\n (\"Search my drive for a file named ‘todo_list.xlsx’\", \"LOW\"),\n (\"Write a Python function to check if a string is a palindrome\", \"LOW\"),\n (\"Can you search the web for startups in Berlin?\", \"LOW\"),\n (\"Find recent articles on blockchain technology online\", \"LOW\"),\n (\"Check if ‘Personal_Projects’ folder exists on my desktop\", \"LOW\"),\n (\"Create a bash script to list all running processes\", \"LOW\"),\n (\"Debug this Python script that’s crashing on line 10\", \"LOW\"),\n (\"Browse the web to find out who invented Python\", \"LOW\"),\n (\"Locate a file named ‘shopping_list.txt’ on my system\", \"LOW\"),\n (\"Search the web for tips on staying productive\", \"LOW\"),\n (\"Find ‘sales_pitch.pptx’ in my Downloads folder\", \"LOW\"),\n (\"can you find a file called resume.docx on my drive?\", \"LOW\"),\n (\"can you write a python script to check if the device on my network is connected to the internet\", \"LOW\"),\n (\"can you debug this Java code? It’s not working.\", \"LOW\"),\n (\"can you find the old_project.zip file somewhere on my drive?\", \"LOW\"),\n (\"can you locate the backup folder I created last month on my system?\", \"LOW\"),\n (\"could you check if the presentation.pdf file exists in my downloads?\", \"LOW\"),\n (\"search my drive for a file called vacation_photos_2023.jpg.\", \"LOW\"),\n (\"help me organize my desktop files into folders by type.\", \"LOW\"),\n (\"make a blackjack in golang\", \"LOW\"),\n (\"write a python script to ping a website\", \"LOW\"),\n (\"write a simple Java program to print 'Hello World'\", \"LOW\"),\n (\"write a Java program to calculate the area of a circle\", \"LOW\"),\n (\"write a Python function to sort a list of dictionaries by key\", \"LOW\"),\n (\"can you search for startup in tokyo?\", \"LOW\"),\n (\"find the latest updates on quantum computing on the web\", \"LOW\"),\n (\"check if the folder ‘Work_Projects’ exists on my desktop\", \"LOW\"),\n (\" can you browse the web, use overpass-turbo to show fountains in toulouse\", \"LOW\"),\n (\"search the web for the best budget smartphones of 2025\", \"LOW\"),\n (\"write a Python script to download all images from a webpage\", \"LOW\"),\n (\"create a bash script to monitor CPU usage\", \"LOW\"),\n (\"debug this C++ code that keeps crashing\", \"LOW\"),\n (\"can you browse the web to find out who fosowl is ?\", \"LOW\"),\n (\"find the file ‘important_notes.txt’\", \"LOW\"),\n (\"search the web for the best ways to learn a new language\", \"LOW\"),\n (\"locate the file ‘presentation.pptx’ in my Documents folder\", \"LOW\"),\n (\"Make a 3d game in javascript using three.js\", \"LOW\"),\n (\"Find the latest research papers on AI and build save in a file\", \"HIGH\"),\n (\"Make a web server in go that serve a simple html page\", \"LOW\"),\n (\"Search the web for the cheapest 4K monitor and provide a link\", \"LOW\"),\n (\"Write a JavaScript function to reverse a string\", \"LOW\"),\n (\"Can you locate a file called ‘budget_2025.xlsx’ on my system?\", \"LOW\"),\n (\"Search the web for recent articles on space exploration\", \"LOW\"),\n (\"when is the exam period for master student in france?\", \"LOW\"),\n (\"Check if a folder named ‘Photos_2024’ exists on my desktop\", \"LOW\"),\n (\"Can you look up some nice knitting patterns on that web thingy?\", \"LOW\"),\n (\"Goodness, check if my ‘Photos_Grandkids’ folder is still on the desktop\", \"LOW\"),\n (\"Create a Python script to rename all files in a folder based on their creation date\", \"LOW\"),\n (\"Can you find a file named ‘meeting_notes.txt’ in my Downloads folder?\", \"LOW\"),\n (\"Write a Go program to check if a port is open on a network\", \"LOW\"),\n (\"Search the web for the latest electric car reviews\", \"LOW\"),\n (\"Write a Python function to merge two sorted lists\", \"LOW\"),\n (\"Create a bash script to monitor disk space and alert via text file\", \"LOW\"),\n (\"What’s out there on the web about cheap travel spots?\", \"LOW\"),\n (\"Search X for posts about AI ethics and summarize them\", \"LOW\"),\n (\"Check if a file named ‘project_proposal.pdf’ exists in my Documents\", \"LOW\"),\n (\"Search the web for tips on improving coding skills\", \"LOW\"),\n (\"Write a Python script to count words in a text file\", \"LOW\"),\n (\"Search the web for restaurant\", \"LOW\"),\n (\"Use a MCP to find the latest stock market data\", \"LOW\"),\n (\"Use a MCP to send an email to my boss\", \"LOW\"),\n (\"Could you use a MCP to find the latest news on climate change?\", \"LOW\"),\n (\"Create a simple HTML page with CSS styling\", \"LOW\"),\n (\"Use file.txt and then use it to ...\", \"HIGH\"),\n (\"Yo, what’s good? Find my ‘mixtape.mp3’ real quick\", \"LOW\"),\n (\"Can you follow the readme and install the project\", \"HIGH\"),\n (\"Man, write me a dope Python script to flex some random numbers\", \"LOW\"),\n (\"Search the web for peer-reviewed articles on gene editing\", \"LOW\"),\n (\"Locate ‘meeting_notes.docx’ in Downloads, I’m late for this call\", \"LOW\"),\n (\"Make the game less hard\", \"LOW\"),\n (\"Why did it fail?\", \"LOW\"),\n (\"Write a Python script to list all .pdf files in my Documents\", \"LOW\"),\n (\"Write a Python thing to sort my .jpg files by date\", \"LOW\"),\n (\"make a snake game please\", \"LOW\"),\n (\"Find ‘gallery_list.pdf’, then build a web app to show my pics\", \"HIGH\"),\n (\"Find ‘budget_2025.xlsx’, analyze it, and make a chart for my boss\", \"HIGH\"),\n (\"I want you to make me a plan to travel to Tainan\", \"HIGH\"),\n (\"Retrieve the latest publications on CRISPR and develop a web application to display them\", \"HIGH\"),\n (\"Bro dig up a music API and build me a tight app for the hottest tracks\", \"HIGH\"),\n (\"Find a public API for sports scores and build a web app to show live updates\", \"HIGH\"),\n (\"Find a public API for book data and create a Flask app to list bestsellers\", \"HIGH\"),\n (\"Organize my desktop files by extension and then write a script to list them\", \"HIGH\"),\n (\"Find the latest research on renewable energy and build a web app to display it\", \"HIGH\"),\n (\"search online for popular sci-fi movies from 2024 and pick three to watch tonight. Save the list in movie_night.txt\", \"HIGH\"),\n (\"can you find vitess repo, clone it and install by following the readme\", \"HIGH\"),\n (\"Create a JavaScript game using Phaser.js with multiple levels\", \"HIGH\"),\n (\"Search the web for the latest trends in web development and build a sample site\", \"HIGH\"),\n (\"Use my research_note.txt file, double check the informations on the web\", \"HIGH\"),\n (\"Make a web server in go that query a flight API and display them in a app\", \"HIGH\"),\n (\"Search the web for top cafes in Rennes, France, and save a list of three with their addresses in rennes_cafes.txt.\", \"HIGH\"),\n (\"Search the web for the latest trends in AI and demo it in pytorch\", \"HIGH\"),\n (\"can you lookup for api that track flight and build a web flight tracking app\", \"HIGH\"),\n (\"Find the file toto.pdf then use its content to reply to Jojo on superforum.com\", \"HIGH\"),\n (\"Create a whole web app in python using the flask framework that query news API\", \"HIGH\"),\n (\"Create a bash script that monitor the CPU usage and send an email if it's too high\", \"HIGH\"),\n (\"Make a web search for latest news on the stock market and display them with python\", \"HIGH\"),\n (\"Find my resume file, apply to job that might fit online\", \"HIGH\"),\n (\"Can you find a weather API and build a Python app to display current weather\", \"HIGH\"),\n (\"Create a Python web app using Flask to track cryptocurrency prices from an API\", \"HIGH\"),\n (\"Search the web for tutorials on machine learning and build a simple ML model in Python\", \"HIGH\"),\n (\"Find a public API for movie data and build a web app to display movie ratings\", \"HIGH\"),\n (\"Create a Node.js server that queries a public API for traffic data and displays it\", \"HIGH\"),\n (\"can you find api and build a python web app with it ?\", \"HIGH\"),\n (\"do a deep search of current AI player for 2025 and make me a report in a file\", \"HIGH\"),\n (\"Find a public API for recipe data and build a web app to display recipes\", \"HIGH\"),\n (\"Search the web for recent space mission updates and build a Flask app\", \"HIGH\"),\n (\"Create a Python script to scrape a website and save data to a database\", \"HIGH\"),\n (\"Find a shakespear txt then train a transformers on it to generate text\", \"HIGH\"),\n (\"Find a public API for fitness tracking and build a web app to show stats\", \"HIGH\"),\n (\"Search the web for tutorials on web development and build a sample site\", \"HIGH\"),\n (\"Create a Node.js app to query a public API for event listings and display them\", \"HIGH\"),\n (\"Find a file named ‘budget.xlsx’, analyze its data, and generate a chart\", \"HIGH\"),\n ]\n random.shuffle(few_shots)\n texts = [text for text, _ in few_shots]\n labels = [label for _, label in few_shots]\n self.complexity_classifier.add_examples(texts, labels)\n\n def learn_few_shots_tasks(self) -> None:\n \"\"\"\n Few shot learning for tasks classification.\n Use the build in add_examples method of the Adaptive_classifier.\n \"\"\"\n few_shots = [\n (\"Write a python script to check if the device on my network is connected to the internet\", \"coding\"),\n (\"Hey could you search the web for the latest news on the tesla stock market ?\", \"web\"),\n (\"I would like you to search for weather api\", \"web\"),\n (\"Plan a 3-day trip to New York, including flights and hotels.\", \"web\"),\n (\"Find on the web the latest research papers on AI.\", \"web\"),\n (\"Can you debug this Java code? It’s not working.\", \"code\"),\n (\"Can you browse the web and find me a 4090 for cheap?\", \"web\"),\n (\"i would like to setup a new AI project, index as mark2\", \"files\"),\n (\"Hey, can you find the old_project.zip file somewhere on my drive?\", \"files\"),\n (\"Tell me a funny story\", \"talk\"),\n (\"can you make a snake game in python\", \"code\"),\n (\"Can you locate the backup folder I created last month on my system?\", \"files\"),\n (\"Share a random fun fact about space.\", \"talk\"),\n (\"Write a script to rename all files in a directory to lowercase.\", \"files\"),\n (\"Could you check if the presentation.pdf file exists in my downloads?\", \"files\"),\n (\"Tell me about the weirdest dream you’ve ever heard of.\", \"talk\"),\n (\"Search my drive for a file called vacation_photos_2023.jpg.\", \"files\"),\n (\"Help me organize my desktop files into folders by type.\", \"files\"),\n (\"What’s your favorite movie and why?\", \"talk\"),\n (\"what directory are you in ?\", \"files\"),\n (\"what files you seing rn ?\", \"files\"),\n (\"When is the period of university exam in france ?\", \"web\"),\n (\"Search my drive for a file named budget_2024.xlsx\", \"files\"),\n (\"Write a Python function to sort a list of dictionaries by key\", \"code\"),\n (\"Find the latest updates on quantum computing on the web\", \"web\"),\n (\"Check if the folder ‘Work_Projects’ exists on my desktop\", \"files\"),\n (\"Create a bash script to monitor CPU usage\", \"code\"),\n (\"Search online for the best budget smartphones of 2025\", \"web\"),\n (\"What’s the strangest food combination you’ve heard of?\", \"talk\"),\n (\"Move all .txt files from Downloads to a new folder called Notes\", \"files\"),\n (\"Debug this C++ code that keeps crashing\", \"code\"),\n (\"can you browse the web to find out who fosowl is ?\", \"web\"),\n (\"Find the file ‘important_notes.txt’\", \"files\"),\n (\"Find out the latest news on the upcoming Mars mission\", \"web\"),\n (\"Write a Java program to calculate the area of a circle\", \"code\"),\n (\"Search the web for the best ways to learn a new language\", \"web\"),\n (\"Locate the file ‘presentation.pptx’ in my Documents folder\", \"files\"),\n (\"Write a Python script to download all images from a webpage\", \"code\"),\n (\"Search the web for the latest trends in AI and machine learning\", \"web\"),\n (\"Tell me about a time when you had to solve a difficult problem\", \"talk\"),\n (\"Organize all image files on my desktop into a folder called ‘Pictures’\", \"files\"),\n (\"Generate a Ruby script to calculate Fibonacci numbers up to 100\", \"code\"),\n (\"Find out what device are connected to my network\", \"code\"),\n (\"Show me how much disk space is left on my drive\", \"code\"),\n (\"Look up recent posts on X about climate change\", \"web\"),\n (\"Find the photo I took last week named sunset_beach.jpg\", \"files\"),\n (\"Write a JavaScript snippet to fetch data from an API\", \"code\"),\n (\"Search the web for tutorials on machine learning with Python\", \"web\"),\n (\"Locate the file ‘meeting_notes.docx’ in my Documents folder\", \"files\"),\n (\"Write a Python script to scrape a website’s title and links\", \"code\"),\n (\"Search the web for the latest breakthroughs in fusion energy\", \"web\"),\n (\"Tell me about a historical event that sounds too wild to be true\", \"talk\"),\n (\"Organize all image files on my desktop into a folder called ‘Pictures’\", \"files\"),\n (\"Generate a Ruby script to calculate Fibonacci numbers up to 100\", \"code\"),\n (\"Find recent X posts about SpaceX’s next rocket launch\", \"web\"),\n (\"What’s the funniest misunderstanding you’ve seen between humans and AI?\", \"talk\"),\n (\"Check if ‘backup_032025.zip’ exists anywhere on my drive\", \"files\" ),\n (\"Create a shell script to automate backups of a directory\", \"code\"),\n (\"Look up the top AI conferences happening in 2025 online\", \"web\"),\n (\"Write a C# program to simulate a basic calculator\", \"code\"),\n (\"Browse the web for open-source alternatives to Photoshop\", \"web\"),\n (\"Hey how are you\", \"talk\"),\n (\"Write a Python script to ping a website\", \"code\"),\n (\"Search the web for the latest iPhone release\", \"web\"),\n (\"What’s the weather like today?\", \"web\"),\n (\"Hi, how’s your day going?\", \"talk\"),\n (\"Can you find a file called resume.docx on my drive?\", \"files\"),\n (\"Write a simple Java program to print 'Hello World'\", \"code\"),\n (\"can you find the current stock of Tesla?\", \"web\"),\n (\"Tell me a quick joke\", \"talk\"),\n (\"Search online for the best coffee shops in Seattle\", \"web\"),\n (\"Check if ‘project_plan.pdf’ exists in my Downloads folder\", \"files\"),\n (\"What’s your favorite color?\", \"talk\"),\n (\"Write a bash script to list all files in a directory\", \"code\"),\n (\"Find recent X posts about electric cars\", \"web\"),\n (\"Hey, you doing okay?\", \"talk\"),\n (\"Locate the file ‘family_photo.jpg’ on my system\", \"files\"),\n (\"Search the web for beginner guitar lessons\", \"web\"),\n (\"Write a Python function to reverse a string\", \"code\"),\n (\"What’s the weirdest animal you know of?\", \"talk\"),\n (\"Organize all .pdf files on my desktop into a ‘Documents’ folder\", \"files\"),\n (\"Browse the web for the latest space mission updates\", \"web\"),\n (\"Hey, what’s up with you today?\", \"talk\"),\n (\"Write a JavaScript function to add two numbers\", \"code\"),\n (\"Find the file ‘notes.txt’ in my Documents folder\", \"files\"),\n (\"Tell me something random about the ocean\", \"talk\"),\n (\"Search the web for cheap flights to Paris\", \"web\"),\n (\"Check if ‘budget.xlsx’ is on my drive\", \"files\"),\n (\"Write a Python script to count words in a text file\", \"code\"),\n (\"How’s it going today?\", \"talk\"),\n (\"Find recent X posts about AI advancements\", \"web\"),\n (\"Move all .jpg files from Downloads to a ‘Photos’ folder\", \"files\"),\n (\"Search online for the best laptops of 2025\", \"web\"),\n (\"What’s the funniest thing you’ve heard lately?\", \"talk\"),\n (\"Write a Ruby script to generate random numbers\", \"code\"),\n (\"Hey, how’s everything with you?\", \"talk\"),\n (\"Locate ‘meeting_agenda.docx’ in my system\", \"files\"),\n (\"Search the web for tips on growing indoor plants\", \"web\"),\n (\"Write a C++ program to calculate the sum of an array\", \"code\"),\n (\"Tell me a fun fact about dogs\", \"talk\"),\n (\"Check if the folder ‘Old_Projects’ exists on my desktop\", \"files\"),\n (\"Browse the web for the latest gaming console reviews\", \"web\"),\n (\"Hi, how are you feeling today?\", \"talk\"),\n (\"Write a Python script to check disk space\", \"code\"),\n (\"Find the file ‘vacation_itinerary.pdf’ on my drive\", \"files\"),\n (\"Search the web for news on renewable energy\", \"web\"),\n (\"What’s the strangest thing you’ve learned recently?\", \"talk\"),\n (\"Organize all video files into a ‘Videos’ folder\", \"files\"),\n (\"Write a shell script to delete temporary files\", \"code\"),\n (\"Hey, how’s your week been so far?\", \"talk\"),\n (\"Search online for the top movies of 2025\", \"web\"),\n (\"Locate ‘taxes_2024.xlsx’ in my Documents folder\", \"files\"),\n (\"Tell me about a cool invention from history\", \"talk\"),\n (\"Write a Java program to check if a number is even or odd\", \"code\"),\n (\"Find recent X posts about cryptocurrency trends\", \"web\"),\n (\"Hey, you good today?\", \"talk\"),\n (\"Search the web for easy dinner recipes\", \"web\"),\n (\"Check if ‘photo_backup.zip’ exists on my drive\", \"files\"),\n (\"Write a Python script to rename files with a timestamp\", \"code\"),\n (\"What’s your favorite thing about space?\", \"talk\"),\n (\"search for GPU with at least 24gb vram\", \"web\"),\n (\"Browse the web for the latest fitness trends\", \"web\"),\n (\"Move all .docx files to a ‘Work’ folder\", \"files\"),\n (\"I would like to make a new project called 'new_project'\", \"files\"),\n (\"I would like to setup a new project index as mark2\", \"files\"),\n (\"can you create a 3d js game that run in the browser\", \"code\"),\n (\"can you make a web app in python that use the flask framework\", \"code\"),\n (\"can you build a web server in go that serve a simple html page\", \"code\"),\n (\"can you find out who Jacky yougouri is ?\", \"web\"),\n (\"Can you use MCP to find stock market for IBM ?\", \"mcp\"),\n (\"Can you use MCP to to export my contacts to a csv file?\", \"mcp\"),\n (\"Can you use a MCP to find write notes to flomo\", \"mcp\"),\n (\"Can you use a MCP to query my calendar and find the next meeting?\", \"mcp\"),\n (\"Can you use a mcp to get the distance between Shanghai and Paris?\", \"mcp\"),\n (\"Setup a new flutter project called 'new_flutter_project'\", \"files\"),\n (\"can you create a new project called 'new_project'\", \"files\"),\n (\"can you make a simple web app that display a list of files in my dir\", \"code\"),\n (\"can you build a simple web server in python that serve a html page\", \"code\"),\n (\"find and buy me the latest rtx 4090\", \"web\"),\n (\"What are some good netflix show like Altered Carbon ?\", \"web\"),\n (\"can you find the latest research paper on AI\", \"web\"),\n (\"can you find research.pdf in my drive\", \"files\"),\n (\"hi\", \"talk\"),\n (\"hello\", \"talk\"),\n ]\n random.shuffle(few_shots)\n texts = [text for text, _ in few_shots]\n labels = [label for _, label in few_shots]\n self.talk_classifier.add_examples(texts, labels)\n\n def llm_router(self, text: str) -> tuple:\n \"\"\"\n Inference of the LLM router model.\n Args:\n text: The input text\n \"\"\"\n predictions = self.talk_classifier.predict(text)\n predictions = [pred for pred in predictions if pred[0] not in [\"HIGH\", \"LOW\"]]\n predictions = sorted(predictions, key=lambda x: x[1], reverse=True)\n return predictions[0]\n \n def router_vote(self, text: str, labels: list, log_confidence:bool = False) -> str:\n \"\"\"\n Vote between the LLM router and BART model.\n Args:\n text: The input text\n labels: The labels to classify\n Returns:\n str: The selected label\n \"\"\"\n if len(text) <= 8:\n return \"talk\"\n result_bart = self.pipelines['bart'](text, labels)\n result_llm_router = self.llm_router(text)\n bart, confidence_bart = result_bart['labels'][0], result_bart['scores'][0]\n llm_router, confidence_llm_router = result_llm_router[0], result_llm_router[1]\n final_score_bart = confidence_bart / (confidence_bart + confidence_llm_router)\n final_score_llm = confidence_llm_router / (confidence_bart + confidence_llm_router)\n self.logger.info(f\"Routing Vote for text {text}: BART: {bart} ({final_score_bart}) LLM-router: {llm_router} ({final_score_llm})\")\n if log_confidence:\n pretty_print(f\"Agent choice -> BART: {bart} ({final_score_bart}) LLM-router: {llm_router} ({final_score_llm})\")\n return bart if final_score_bart > final_score_llm else llm_router\n \n def find_first_sentence(self, text: str) -> str:\n first_sentence = None\n for line in text.split(\"\\n\"):\n first_sentence = line.strip()\n break\n if first_sentence is None:\n first_sentence = text\n return first_sentence\n \n def estimate_complexity(self, text: str) -> str:\n \"\"\"\n Estimate the complexity of the text.\n Args:\n text: The input text\n Returns:\n str: The estimated complexity\n \"\"\"\n try:\n predictions = self.complexity_classifier.predict(text)\n except Exception as e:\n pretty_print(f\"Error in estimate_complexity: {str(e)}\", color=\"failure\")\n return \"LOW\"\n predictions = sorted(predictions, key=lambda x: x[1], reverse=True)\n if len(predictions) == 0:\n return \"LOW\"\n complexity, confidence = predictions[0][0], predictions[0][1]\n if confidence < 0.5:\n self.logger.info(f\"Low confidence in complexity estimation: {confidence}\")\n return \"HIGH\"\n if complexity == \"HIGH\":\n return \"HIGH\"\n elif complexity == \"LOW\":\n return \"LOW\"\n pretty_print(f\"Failed to estimate the complexity of the text.\", color=\"failure\")\n return \"LOW\"\n \n def find_planner_agent(self) -> Agent:\n \"\"\"\n Find the planner agent.\n Returns:\n Agent: The planner agent\n \"\"\"\n for agent in self.agents:\n if agent.type == \"planner_agent\":\n return agent\n pretty_print(f\"Error finding planner agent. Please add a planner agent to the list of agents.\", color=\"failure\")\n self.logger.error(\"Planner agent not found.\")\n return None\n \n def select_agent(self, text: str) -> Agent:\n \"\"\"\n Select the appropriate agent based on the text.\n Args:\n text (str): The text to select the agent from\n Returns:\n Agent: The selected agent\n \"\"\"\n assert len(self.agents) > 0, \"No agents available.\"\n if len(self.agents) == 1:\n return self.agents[0]\n lang = self.lang_analysis.detect_language(text)\n text = self.find_first_sentence(text)\n text = self.lang_analysis.translate(text, lang)\n labels = [agent.role for agent in self.agents]\n complexity = self.estimate_complexity(text)\n if complexity == \"HIGH\":\n pretty_print(f\"Complex task detected, routing to planner agent.\", color=\"info\")\n return self.find_planner_agent()\n try:\n best_agent = self.router_vote(text, labels, log_confidence=False)\n except Exception as e:\n raise e\n for agent in self.agents:\n if best_agent == agent.role:\n role_name = agent.role\n pretty_print(f\"Selected agent: {agent.agent_name} (roles: {role_name})\", color=\"warning\")\n return agent\n pretty_print(f\"Error choosing agent.\", color=\"failure\")\n self.logger.error(\"No agent selected.\")\n return None\n\nif __name__ == \"__main__\":\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n agents = [\n CasualAgent(\"jarvis\", \"../prompts/base/casual_agent.txt\", None),\n BrowserAgent(\"browser\", \"../prompts/base/planner_agent.txt\", None),\n CoderAgent(\"coder\", \"../prompts/base/coder_agent.txt\", None),\n FileAgent(\"file\", \"../prompts/base/coder_agent.txt\", None)\n ]\n router = AgentRouter(agents)\n texts = [\n \"hi\",\n \"你好\",\n \"Bonjour\",\n \"Write a python script to check if the device on my network is connected to the internet\",\n \"Peut tu écrire un script python qui vérifie si l'appareil sur mon réseau est connecté à internet?\",\n \"写一个Python脚本,检查我网络上的设备是否连接到互联网\",\n \"Hey could you search the web for the latest news on the tesla stock market ?\",\n \"嘿,你能搜索网页上关于股票市场的最新新闻吗?\",\n \"Yo, cherche sur internet comment va tesla en bourse.\",\n \"I would like you to search for weather api and then make an app using this API\",\n \"我想让你搜索天气API,然后用这个API做一个应用程序\",\n \"J'aimerais que tu cherche une api météo et que l'utilise pour faire une application\",\n \"Plan a 3-day trip to New York, including flights and hotels.\",\n \"计划一次为期3天的纽约之旅,包括机票和酒店。\",\n \"Planifie un trip de 3 jours à Paris, y compris les vols et hotels.\",\n \"Find on the web the latest research papers on AI.\",\n \"在网上找到最新的人工智能研究论文。\",\n \"Trouve moi les derniers articles de recherche sur l'IA sur internet\",\n \"Help me write a C++ program to sort an array\",\n \"Tell me what France been up to lately\",\n \"告诉我法国最近在做什么\",\n \"Dis moi ce que la France a fait récemment\",\n \"Who is Sergio Pesto ?\",\n \"谁是Sergio Pesto?\",\n \"Qui est Sergio Pesto ?\",\n \"帮我写一个C++程序来排序数组\",\n \"Aide moi à faire un programme c++ pour trier une array.\",\n \"What’s the weather like today? Oh, and can you find a good weather app?\",\n \"今天天气怎么样?哦,你还能找到一个好的天气应用程序吗?\",\n \"La météo est comment aujourd'hui ? oh et trouve moi une bonne appli météo tant que tu y est.\",\n \"Can you debug this Java code? It’s not working.\",\n \"你能调试这段Java代码吗?它不起作用。\",\n \"Peut tu m'aider à debugger ce code java, ça marche pas\",\n \"Can you browse the web and find me a 4090 for cheap?\",\n \"你能浏览网页,为我找一个便宜的4090吗?\",\n \"Peut tu chercher sur internet et me trouver une 4090 pas cher ?\",\n \"Hey, can you find the old_project.zip file somewhere on my drive?\",\n \"嘿,你能在我驱动器上找到old_project.zip文件吗?\",\n \"Hé trouve moi le old_project.zip, il est quelque part sur mon disque.\",\n \"Tell me a funny story\",\n \"给我讲一个有趣的故事\",\n \"Raconte moi une histoire drole\"\n ]\n for text in texts:\n print(\"Input text:\", text)\n agent = router.select_agent(text)\n print()\n"], ["/agenticSeek/sources/tools/webSearch.py", "\nimport os\nimport requests\nimport dotenv\n\ndotenv.load_dotenv()\n\nfrom sources.tools.tools import Tools\nfrom sources.utility import animate_thinking, pretty_print\n\n\"\"\"\nWARNING\nwebSearch is fully deprecated and is being replaced by searxSearch for web search.\n\"\"\"\n\nclass webSearch(Tools):\n def __init__(self, api_key: str = None):\n \"\"\"\n A tool to perform a Google search and return information from the first result.\n \"\"\"\n super().__init__()\n self.tag = \"web_search\"\n self.api_key = api_key or os.getenv(\"SERPAPI_KEY\") # Requires a SerpApi key\n self.paywall_keywords = [\n \"subscribe\", \"login to continue\", \"access denied\", \"restricted content\", \"404\", \"this page is not working\"\n ]\n\n def link_valid(self, link):\n \"\"\"check if a link is valid.\"\"\"\n if not link.startswith(\"http\"):\n return \"Status: Invalid URL\"\n \n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\"}\n try:\n response = requests.get(link, headers=headers, timeout=5)\n status = response.status_code\n if status == 200:\n content = response.text[:1000].lower()\n if any(keyword in content for keyword in self.paywall_keywords):\n return \"Status: Possible Paywall\"\n return \"Status: OK\"\n elif status == 404:\n return \"Status: 404 Not Found\"\n elif status == 403:\n return \"Status: 403 Forbidden\"\n else:\n return f\"Status: {status} {response.reason}\"\n except requests.exceptions.RequestException as e:\n return f\"Error: {str(e)}\"\n\n def check_all_links(self, links):\n \"\"\"Check all links, one by one.\"\"\"\n # TODO Make it asyncromous or smth\n statuses = []\n for i, link in enumerate(links):\n status = self.link_valid(link)\n statuses.append(status)\n return statuses\n\n def execute(self, blocks: str, safety: bool = True) -> str:\n if self.api_key is None:\n return \"Error: No SerpApi key provided.\"\n for block in blocks:\n query = block.strip()\n pretty_print(f\"Searching for: {query}\", color=\"status\")\n if not query:\n return \"Error: No search query provided.\"\n\n try:\n url = \"https://serpapi.com/search\"\n params = {\n \"q\": query,\n \"api_key\": self.api_key,\n \"num\": 50,\n \"output\": \"json\"\n }\n response = requests.get(url, params=params)\n response.raise_for_status()\n\n data = response.json()\n results = []\n if \"organic_results\" in data and len(data[\"organic_results\"]) > 0:\n organic_results = data[\"organic_results\"][:50]\n links = [result.get(\"link\", \"No link available\") for result in organic_results]\n statuses = self.check_all_links(links)\n for result, status in zip(organic_results, statuses):\n if not \"OK\" in status:\n continue\n title = result.get(\"title\", \"No title\")\n snippet = result.get(\"snippet\", \"No snippet available\")\n link = result.get(\"link\", \"No link available\")\n results.append(f\"Title:{title}\\nSnippet:{snippet}\\nLink:{link}\")\n return \"\\n\\n\".join(results)\n else:\n return \"No results found for the query.\"\n except requests.RequestException as e:\n return f\"Error during web search: {str(e)}\"\n except Exception as e:\n return f\"Unexpected error: {str(e)}\"\n return \"No search performed\"\n\n def execution_failure_check(self, output: str) -> bool:\n return output.startswith(\"Error\") or \"No results found\" in output\n\n def interpreter_feedback(self, output: str) -> str:\n if self.execution_failure_check(output):\n return f\"Web search failed: {output}\"\n return f\"Web search result:\\n{output}\"\n\n\nif __name__ == \"__main__\":\n search_tool = webSearch(api_key=os.getenv(\"SERPAPI_KEY\"))\n query = \"when did covid start\"\n result = search_tool.execute([query], safety=True)\n output = search_tool.interpreter_feedback(result)\n print(output)"], ["/agenticSeek/sources/browser.py", "from selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException, WebDriverException\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom typing import List, Tuple, Type, Dict\nfrom bs4 import BeautifulSoup\nfrom urllib.parse import urlparse\nfrom fake_useragent import UserAgent\nfrom selenium_stealth import stealth\nimport undetected_chromedriver as uc\nimport chromedriver_autoinstaller\nimport certifi\nimport ssl\nimport time\nimport random\nimport os\nimport shutil\nimport uuid\nimport tempfile\nimport markdownify\nimport sys\nimport re\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.logger import Logger\n\n\ndef get_chrome_path() -> str:\n \"\"\"Get the path to the Chrome executable.\"\"\"\n if sys.platform.startswith(\"win\"):\n paths = [\n \"C:\\\\Program Files\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe\",\n \"C:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe\",\n os.path.join(os.environ.get(\"LOCALAPPDATA\", \"\"), \"Google\\\\Chrome\\\\Application\\\\chrome.exe\") # User install\n ]\n elif sys.platform.startswith(\"darwin\"): # macOS\n paths = [\"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome\",\n \"/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta\"]\n else: # Linux\n paths = [\"/usr/bin/google-chrome\",\n \"/opt/chrome/chrome\",\n \"/usr/bin/chromium-browser\",\n \"/usr/bin/chromium\",\n \"/usr/local/bin/chrome\",\n \"/opt/google/chrome/chrome-headless-shell\",\n #\"/app/chrome_bundle/chrome136/chrome-linux64\"\n ]\n\n for path in paths:\n if os.path.exists(path) and os.access(path, os.X_OK):\n return path\n print(\"Looking for Google Chrome in these locations failed:\")\n print('\\n'.join(paths))\n chrome_path_env = os.environ.get(\"CHROME_EXECUTABLE_PATH\")\n if chrome_path_env and os.path.exists(chrome_path_env) and os.access(chrome_path_env, os.X_OK):\n return chrome_path_env\n path = input(\"Google Chrome not found. Please enter the path to the Chrome executable: \")\n if os.path.exists(path) and os.access(path, os.X_OK):\n os.environ[\"CHROME_EXECUTABLE_PATH\"] = path\n print(f\"Chrome path saved to environment variable CHROME_EXECUTABLE_PATH\")\n return path\n return None\n\ndef get_random_user_agent() -> str:\n \"\"\"Get a random user agent string with associated vendor.\"\"\"\n user_agents = [\n {\"ua\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36\", \"vendor\": \"Google Inc.\"},\n {\"ua\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 14_6_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36\", \"vendor\": \"Apple Inc.\"},\n {\"ua\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36\", \"vendor\": \"Google Inc.\"},\n ]\n return random.choice(user_agents)\n\ndef install_chromedriver() -> str:\n \"\"\"\n Install the ChromeDriver if not already installed. Return the path.\n \"\"\"\n # First try to use chromedriver in the project root directory (as per README)\n project_root_chromedriver = \"./chromedriver\"\n if os.path.exists(project_root_chromedriver) and os.access(project_root_chromedriver, os.X_OK):\n print(f\"Using ChromeDriver from project root: {project_root_chromedriver}\")\n return project_root_chromedriver\n \n # Then try to use the system-installed chromedriver\n chromedriver_path = shutil.which(\"chromedriver\")\n if chromedriver_path:\n return chromedriver_path\n \n # In Docker environment, try the fixed path\n if os.path.exists('/.dockerenv'):\n docker_chromedriver_path = \"/usr/local/bin/chromedriver\"\n if os.path.exists(docker_chromedriver_path) and os.access(docker_chromedriver_path, os.X_OK):\n print(f\"Using Docker ChromeDriver at {docker_chromedriver_path}\")\n return docker_chromedriver_path\n \n # Fallback to auto-installer only if no other option works\n try:\n print(\"ChromeDriver not found, attempting to install automatically...\")\n chromedriver_path = chromedriver_autoinstaller.install()\n except Exception as e:\n raise FileNotFoundError(\n \"ChromeDriver not found and could not be installed automatically. \"\n \"Please install it manually from https://chromedriver.chromium.org/downloads.\"\n \"and ensure it's in your PATH or specify the path directly.\"\n \"See know issues in readme if your chrome version is above 115.\"\n ) from e\n \n if not chromedriver_path:\n raise FileNotFoundError(\"ChromeDriver not found. Please install it or add it to your PATH.\")\n return chromedriver_path\n\ndef bypass_ssl() -> str:\n \"\"\"\n This is a fallback for stealth mode to bypass SSL verification. Which can fail on some setup.\n \"\"\"\n pretty_print(\"Bypassing SSL verification issues, we strongly advice you update your certifi SSL certificate.\", color=\"warning\")\n ssl._create_default_https_context = ssl._create_unverified_context\n\ndef create_undetected_chromedriver(service, chrome_options) -> webdriver.Chrome:\n \"\"\"Create an undetected ChromeDriver instance.\"\"\"\n try:\n driver = uc.Chrome(service=service, options=chrome_options)\n except Exception as e:\n pretty_print(f\"Failed to create Chrome driver: {str(e)}. Trying to bypass SSL...\", color=\"failure\")\n try:\n bypass_ssl()\n driver = uc.Chrome(service=service, options=chrome_options)\n except Exception as e:\n pretty_print(f\"Failed to create Chrome driver, fallback failed:\\n{str(e)}.\", color=\"failure\")\n raise e\n raise e\n driver.execute_script(\"Object.defineProperty(navigator, 'webdriver', {get: () => undefined})\") \n return driver\n\ndef create_driver(headless=False, stealth_mode=True, crx_path=\"./crx/nopecha.crx\", lang=\"en\") -> webdriver.Chrome:\n \"\"\"Create a Chrome WebDriver with specified options.\"\"\"\n # Warn if trying to run non-headless in Docker\n if not headless and os.path.exists('/.dockerenv'):\n print(\"[WARNING] Running non-headless browser in Docker may fail!\")\n print(\"[WARNING] Consider setting headless=True or headless_browser=True in config.ini\")\n \n chrome_options = Options()\n chrome_path = get_chrome_path()\n \n if not chrome_path:\n raise FileNotFoundError(\"Google Chrome not found. Please install it.\")\n chrome_options.binary_location = chrome_path\n \n if headless:\n #chrome_options.add_argument(\"--headless\")\n chrome_options.add_argument(\"--headless=new\")\n chrome_options.add_argument(\"--disable-gpu\")\n chrome_options.add_argument(\"--disable-webgl\")\n user_data_dir = tempfile.mkdtemp()\n user_agent = get_random_user_agent()\n width, height = (1920, 1080)\n user_data_dir = tempfile.mkdtemp(prefix=\"chrome_profile_\")\n chrome_options.add_argument(\"--no-sandbox\")\n chrome_options.add_argument('--disable-dev-shm-usage')\n profile_dir = f\"/tmp/chrome_profile_{uuid.uuid4().hex[:8]}\"\n chrome_options.add_argument(f'--user-data-dir={profile_dir}')\n chrome_options.add_argument(f\"--accept-lang={lang}-{lang.upper()},{lang};q=0.9\")\n chrome_options.add_argument(\"--disable-extensions\")\n chrome_options.add_argument(\"--disable-background-timer-throttling\")\n chrome_options.add_argument(\"--timezone=Europe/Paris\")\n chrome_options.add_argument('--remote-debugging-port=9222')\n chrome_options.add_argument('--disable-background-timer-throttling')\n chrome_options.add_argument('--disable-backgrounding-occluded-windows')\n chrome_options.add_argument('--disable-renderer-backgrounding')\n chrome_options.add_argument('--disable-features=TranslateUI')\n chrome_options.add_argument('--disable-ipc-flooding-protection')\n chrome_options.add_argument(\"--mute-audio\")\n chrome_options.add_argument(\"--disable-notifications\")\n chrome_options.add_argument(\"--autoplay-policy=user-gesture-required\")\n chrome_options.add_argument(\"--disable-features=SitePerProcess,IsolateOrigins\")\n chrome_options.add_argument(\"--enable-features=NetworkService,NetworkServiceInProcess\")\n chrome_options.add_argument(\"--disable-blink-features=AutomationControlled\")\n chrome_options.add_argument(f'user-agent={user_agent[\"ua\"]}')\n chrome_options.add_argument(f'--window-size={width},{height}')\n if not stealth_mode:\n if not os.path.exists(crx_path):\n pretty_print(f\"Anti-captcha CRX not found at {crx_path}.\", color=\"failure\")\n else:\n chrome_options.add_extension(crx_path)\n\n chromedriver_path = install_chromedriver()\n\n service = Service(chromedriver_path)\n if stealth_mode:\n chrome_options.add_argument(\"--disable-blink-features=AutomationControlled\")\n driver = create_undetected_chromedriver(service, chrome_options)\n chrome_version = driver.capabilities['browserVersion']\n stealth(driver,\n languages=[\"en-US\", \"en\"],\n vendor=user_agent[\"vendor\"],\n platform=\"Win64\" if \"windows\" in user_agent[\"ua\"].lower() else \"MacIntel\" if \"mac\" in user_agent[\"ua\"].lower() else \"Linux x86_64\",\n webgl_vendor=\"Intel Inc.\",\n renderer=\"Intel Iris OpenGL Engine\",\n fix_hairline=True,\n )\n return driver\n security_prefs = {\n \"profile.default_content_setting_values.geolocation\": 0,\n \"profile.default_content_setting_values.notifications\": 0,\n \"profile.default_content_setting_values.camera\": 0,\n \"profile.default_content_setting_values.microphone\": 0,\n \"profile.default_content_setting_values.midi_sysex\": 0,\n \"profile.default_content_setting_values.clipboard\": 0,\n \"profile.default_content_setting_values.media_stream\": 0,\n \"profile.default_content_setting_values.background_sync\": 0,\n \"profile.default_content_setting_values.sensors\": 0,\n \"profile.default_content_setting_values.accessibility_events\": 0,\n \"safebrowsing.enabled\": True,\n \"credentials_enable_service\": False,\n \"profile.password_manager_enabled\": False,\n \"webkit.webprefs.accelerated_2d_canvas_enabled\": True,\n \"webkit.webprefs.force_dark_mode_enabled\": False,\n \"webkit.webprefs.accelerated_2d_canvas_msaa_sample_count\": 4,\n \"enable_webgl\": True,\n \"enable_webgl2_compute_context\": True\n }\n chrome_options.add_experimental_option(\"prefs\", security_prefs)\n chrome_options.add_experimental_option(\"excludeSwitches\", [\"enable-automation\"])\n chrome_options.add_experimental_option('useAutomationExtension', False)\n return webdriver.Chrome(service=service, options=chrome_options)\n\nclass Browser:\n def __init__(self, driver, anticaptcha_manual_install=False):\n \"\"\"Initialize the browser with optional AntiCaptcha installation.\"\"\"\n self.js_scripts_folder = \"./sources/web_scripts/\" if not __name__ == \"__main__\" else \"./web_scripts/\"\n self.anticaptcha = \"https://chrome.google.com/webstore/detail/nopecha-captcha-solver/dknlfmjaanfblgfdfebhijalfmhmjjjo/related\"\n self.logger = Logger(\"browser.log\")\n self.screenshot_folder = os.path.join(os.getcwd(), \".screenshots\")\n self.tabs = []\n try:\n self.driver = driver\n self.wait = WebDriverWait(self.driver, 10)\n except Exception as e:\n raise Exception(f\"Failed to initialize browser: {str(e)}\")\n self.setup_tabs()\n self.patch_browser_fingerprint()\n if anticaptcha_manual_install:\n self.load_anticatpcha_manually()\n \n def setup_tabs(self):\n self.tabs = self.driver.window_handles\n try:\n self.driver.get(\"https://www.google.com\")\n except Exception as e:\n self.logger.log(f\"Failed to setup initial tab:\" + str(e))\n pass\n self.screenshot()\n \n def switch_control_tab(self):\n self.logger.log(\"Switching to control tab.\")\n self.driver.switch_to.window(self.tabs[0])\n \n def load_anticatpcha_manually(self):\n pretty_print(\"You might want to install the AntiCaptcha extension for captchas.\", color=\"warning\")\n try:\n self.driver.get(self.anticaptcha)\n except Exception as e:\n self.logger.log(f\"Failed to setup initial tab:\" + str(e))\n pass\n\n def human_move(element):\n actions = ActionChains(driver)\n x_offset = random.randint(-5,5)\n for _ in range(random.randint(2,5)):\n actions.move_by_offset(x_offset, random.randint(-2,2))\n actions.pause(random.uniform(0.1,0.3))\n actions.click().perform()\n\n def human_scroll(self):\n for _ in range(random.randint(1, 3)):\n scroll_pixels = random.randint(150, 1200)\n self.driver.execute_script(f\"window.scrollBy(0, {scroll_pixels});\")\n time.sleep(random.uniform(0.5, 2.0))\n if random.random() < 0.4:\n self.driver.execute_script(f\"window.scrollBy(0, -{random.randint(50, 300)});\")\n time.sleep(random.uniform(0.3, 1.0))\n\n def patch_browser_fingerprint(self) -> None:\n script = self.load_js(\"spoofing.js\")\n self.driver.execute_script(script)\n \n def go_to(self, url:str) -> bool:\n \"\"\"Navigate to a specified URL.\"\"\"\n time.sleep(random.uniform(0.4, 2.5))\n try:\n initial_handles = self.driver.window_handles\n self.driver.get(url)\n time.sleep(random.uniform(0.01, 0.3))\n try:\n wait = WebDriverWait(self.driver, timeout=10)\n wait.until(\n lambda driver: (\n not any(keyword in driver.page_source.lower() for keyword in [\"checking your browser\", \"captcha\"])\n ),\n message=\"stuck on 'checking browser' or verification screen\"\n )\n except TimeoutException:\n self.logger.warning(\"Timeout while waiting for page to bypass 'checking your browser'\")\n self.apply_web_safety()\n time.sleep(random.uniform(0.01, 0.2))\n self.human_scroll()\n self.logger.log(f\"Navigated to: {url}\")\n return True\n except TimeoutException as e:\n self.logger.error(f\"Timeout waiting for {url} to load: {str(e)}\")\n return False\n except WebDriverException as e:\n self.logger.error(f\"Error navigating to {url}: {str(e)}\")\n return False\n except Exception as e:\n self.logger.error(f\"Fatal error with go_to method on {url}:\\n{str(e)}\")\n raise e\n\n def is_sentence(self, text:str) -> bool:\n \"\"\"Check if the text qualifies as a meaningful sentence or contains important error codes.\"\"\"\n text = text.strip()\n\n if any(c.isdigit() for c in text):\n return True\n words = re.findall(r'\\w+', text, re.UNICODE)\n word_count = len(words)\n has_punctuation = any(text.endswith(p) for p in ['.', ',', ',', '!', '?', '。', '!', '?', '।', '۔'])\n is_long_enough = word_count > 4\n return (word_count >= 5 and (has_punctuation or is_long_enough))\n\n def get_text(self) -> str | None:\n \"\"\"Get page text as formatted Markdown\"\"\"\n try:\n soup = BeautifulSoup(self.driver.page_source, 'html.parser')\n for element in soup(['script', 'style', 'noscript', 'meta', 'link']):\n element.decompose()\n markdown_converter = markdownify.MarkdownConverter(\n heading_style=\"ATX\",\n strip=['a'],\n autolinks=False,\n bullets='•',\n strong_em_symbol='*',\n default_title=False,\n )\n markdown_text = markdown_converter.convert(str(soup.body))\n lines = []\n for line in markdown_text.splitlines():\n stripped = line.strip()\n if stripped and self.is_sentence(stripped):\n cleaned = ' '.join(stripped.split())\n lines.append(cleaned)\n result = \"[Start of page]\\n\\n\" + \"\\n\\n\".join(lines) + \"\\n\\n[End of page]\"\n result = re.sub(r'!\\[(.*?)\\]\\(.*?\\)', r'[IMAGE: \\1]', result)\n self.logger.info(f\"Extracted text: {result[:100]}...\")\n self.logger.info(f\"Extracted text length: {len(result)}\")\n return result[:32768]\n except Exception as e:\n self.logger.error(f\"Error getting text: {str(e)}\")\n return None\n \n def clean_url(self, url:str) -> str:\n \"\"\"Clean URL to keep only the part needed for navigation to the page\"\"\"\n clean = url.split('#')[0]\n parts = clean.split('?', 1)\n base_url = parts[0]\n if len(parts) > 1:\n query = parts[1]\n essential_params = []\n for param in query.split('&'):\n if param.startswith('_skw=') or param.startswith('q=') or param.startswith('s='):\n essential_params.append(param)\n elif param.startswith('_') or param.startswith('hash=') or param.startswith('itmmeta='):\n break\n if essential_params:\n return f\"{base_url}?{'&'.join(essential_params)}\"\n return base_url\n \n def is_link_valid(self, url:str) -> bool:\n \"\"\"Check if a URL is a valid link (page, not related to icon or metadata).\"\"\"\n if len(url) > 72:\n self.logger.warning(f\"URL too long: {url}\")\n return False\n parsed_url = urlparse(url)\n if not parsed_url.scheme or not parsed_url.netloc:\n self.logger.warning(f\"Invalid URL: {url}\")\n return False\n if re.search(r'/\\d+$', parsed_url.path):\n return False\n image_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp']\n metadata_extensions = ['.ico', '.xml', '.json', '.rss', '.atom']\n for ext in image_extensions + metadata_extensions:\n if url.lower().endswith(ext):\n return False\n return True\n\n def get_navigable(self) -> List[str]:\n \"\"\"Get all navigable links on the current page.\"\"\"\n try:\n links = []\n elements = self.driver.find_elements(By.TAG_NAME, \"a\")\n \n for element in elements:\n href = element.get_attribute(\"href\")\n if href and href.startswith((\"http\", \"https\")):\n links.append({\n \"url\": href,\n \"text\": element.text.strip(),\n \"is_displayed\": element.is_displayed()\n })\n \n self.logger.info(f\"Found {len(links)} navigable links\")\n return [self.clean_url(link['url']) for link in links if (link['is_displayed'] == True and self.is_link_valid(link['url']))]\n except Exception as e:\n self.logger.error(f\"Error getting navigable links: {str(e)}\")\n return []\n\n def click_element(self, xpath: str) -> bool:\n \"\"\"Click an element specified by XPath.\"\"\"\n try:\n element = self.wait.until(EC.element_to_be_clickable((By.XPATH, xpath)))\n if not element.is_displayed():\n return False\n if not element.is_enabled():\n return False\n try:\n self.logger.error(f\"Scrolling to element for click_element.\")\n self.driver.execute_script(\"arguments[0].scrollIntoView({block: 'center', behavior: 'smooth'});\", element)\n time.sleep(0.1)\n element.click()\n self.logger.info(f\"Clicked element at {xpath}\")\n return True\n except ElementClickInterceptedException as e:\n self.logger.error(f\"Error click_element: {str(e)}\")\n return False\n except TimeoutException:\n self.logger.warning(f\"Timeout clicking element.\")\n return False\n except Exception as e:\n self.logger.error(f\"Unexpected error clicking element at {xpath}: {str(e)}\")\n return False\n \n def load_js(self, file_name: str) -> str:\n \"\"\"Load javascript from script folder to inject to page.\"\"\"\n path = os.path.join(self.js_scripts_folder, file_name)\n self.logger.info(f\"Loading js at {path}\")\n try:\n with open(path, 'r') as f:\n return f.read()\n except FileNotFoundError as e:\n raise Exception(f\"Could not find: {path}\") from e\n except Exception as e:\n raise e\n\n def find_all_inputs(self, timeout=3):\n \"\"\"Find all inputs elements on the page.\"\"\"\n try:\n WebDriverWait(self.driver, timeout).until(\n EC.presence_of_element_located((By.TAG_NAME, \"body\"))\n )\n except Exception as e:\n self.logger.error(f\"Error waiting for input element: {str(e)}\")\n return []\n time.sleep(0.5)\n script = self.load_js(\"find_inputs.js\")\n input_elements = self.driver.execute_script(script)\n return input_elements\n\n def get_form_inputs(self) -> List[str]:\n \"\"\"Extract all input from the page and return them.\"\"\"\n try:\n input_elements = self.find_all_inputs()\n if not input_elements:\n self.logger.info(\"No input element on page.\")\n return [\"No input forms found on the page.\"]\n\n form_strings = []\n for element in input_elements:\n input_type = element.get(\"type\") or \"text\"\n if input_type in [\"hidden\", \"submit\", \"button\", \"image\"] or not element[\"displayed\"]:\n continue\n input_name = element.get(\"text\") or element.get(\"id\") or input_type\n if input_type == \"checkbox\" or input_type == \"radio\":\n try:\n checked_status = \"checked\" if element.is_selected() else \"unchecked\"\n except Exception as e:\n continue\n form_strings.append(f\"[{input_name}]({checked_status})\")\n else:\n form_strings.append(f\"[{input_name}](\"\")\")\n return form_strings\n\n except Exception as e:\n raise e\n\n def get_buttons_xpath(self) -> List[str]:\n \"\"\"\n Find buttons and return their type and xpath.\n \"\"\"\n buttons = self.driver.find_elements(By.TAG_NAME, \"button\") + \\\n self.driver.find_elements(By.XPATH, \"//input[@type='submit']\")\n result = []\n for i, button in enumerate(buttons):\n if not button.is_displayed() or not button.is_enabled():\n continue\n text = (button.text or button.get_attribute(\"value\") or \"\").lower().replace(' ', '')\n xpath = f\"(//button | //input[@type='submit'])[{i + 1}]\"\n result.append((text, xpath))\n result.sort(key=lambda x: len(x[0]))\n return result\n\n def wait_for_submission_outcome(self, timeout: int = 10) -> bool:\n \"\"\"\n Wait for a submission outcome (e.g., URL change or new element).\n \"\"\"\n try:\n self.logger.info(\"Waiting for submission outcome...\")\n wait = WebDriverWait(self.driver, timeout)\n wait.until(\n lambda driver: driver.current_url != self.driver.current_url or\n driver.find_elements(By.XPATH, \"//*[contains(text(), 'success')]\")\n )\n self.logger.info(\"Detected submission outcome\")\n return True\n except TimeoutException:\n self.logger.warning(\"No submission outcome detected\")\n return False\n\n def find_and_click_btn(self, btn_type: str = 'login', timeout: int = 5) -> bool:\n \"\"\"Find and click a submit button matching the specified type.\"\"\"\n buttons = self.get_buttons_xpath()\n if not buttons:\n self.logger.warning(\"No visible buttons found\")\n return False\n\n for button_text, xpath in buttons:\n if btn_type.lower() in button_text.lower() or btn_type.lower() in xpath.lower():\n try:\n wait = WebDriverWait(self.driver, timeout)\n element = wait.until(\n EC.element_to_be_clickable((By.XPATH, xpath)),\n message=f\"Button with XPath '{xpath}' not clickable within {timeout} seconds\"\n )\n if self.click_element(xpath):\n self.logger.info(f\"Clicked button '{button_text}' at XPath: {xpath}\")\n return True\n else:\n self.logger.warning(f\"Button '{button_text}' at XPath: {xpath} not clickable\")\n return False\n except TimeoutException:\n self.logger.warning(f\"Timeout waiting for '{button_text}' button at XPath: {xpath}\")\n return False\n except Exception as e:\n self.logger.error(f\"Error clicking button '{button_text}' at XPath: {xpath} - {str(e)}\")\n return False\n self.logger.warning(f\"No button matching '{btn_type}' found\")\n return False\n\n def tick_all_checkboxes(self) -> bool:\n \"\"\"\n Find and tick all checkboxes on the page.\n Returns True if successful, False if any issues occur.\n \"\"\"\n try:\n checkboxes = self.driver.find_elements(By.XPATH, \"//input[@type='checkbox']\")\n if not checkboxes:\n self.logger.info(\"No checkboxes found on the page\")\n return True\n\n for index, checkbox in enumerate(checkboxes, 1):\n try:\n WebDriverWait(self.driver, 10).until(\n EC.element_to_be_clickable(checkbox)\n )\n self.driver.execute_script(\n \"arguments[0].scrollIntoView({block: 'center', inline: 'center'});\", checkbox\n )\n if not checkbox.is_selected():\n try:\n checkbox.click()\n self.logger.info(f\"Ticked checkbox {index}\")\n except ElementClickInterceptedException:\n self.driver.execute_script(\"arguments[0].click();\", checkbox)\n self.logger.warning(f\"Click checkbox {index} intercepted\")\n else:\n self.logger.info(f\"Checkbox {index} already ticked\")\n except TimeoutException:\n self.logger.warning(f\"Timeout waiting for checkbox {index} to be clickable\")\n continue\n except Exception as e:\n self.logger.error(f\"Error ticking checkbox {index}: {str(e)}\")\n continue\n return True\n except Exception as e:\n self.logger.error(f\"Error finding checkboxes: {str(e)}\")\n return False\n\n def find_and_click_submission(self, timeout: int = 10) -> bool:\n possible_submissions = [\"login\", \"submit\", \"register\", \"continue\", \"apply\",\n \"ok\", \"confirm\", \"proceed\", \"accept\", \n \"done\", \"finish\", \"start\", \"calculate\"]\n for submission in possible_submissions:\n if self.find_and_click_btn(submission, timeout):\n self.logger.info(f\"Clicked on submission button: {submission}\")\n return True\n self.logger.warning(\"No submission button found\")\n return False\n \n def find_input_xpath_by_name(self, inputs, name: str) -> str | None:\n for field in inputs:\n if name in field[\"text\"]:\n return field[\"xpath\"]\n return None\n\n def fill_form_inputs(self, input_list: List[str]) -> bool:\n \"\"\"Fill inputs based on a list of [name](value) strings.\"\"\"\n if not isinstance(input_list, list):\n self.logger.error(\"input_list must be a list\")\n return False\n inputs = self.find_all_inputs()\n try:\n for input_str in input_list:\n match = re.match(r'\\[(.*?)\\]\\((.*?)\\)', input_str)\n if not match:\n self.logger.warning(f\"Invalid format for input: {input_str}\")\n continue\n\n name, value = match.groups()\n name = name.strip()\n value = value.strip()\n xpath = self.find_input_xpath_by_name(inputs, name)\n if not xpath:\n self.logger.warning(f\"Input field '{name}' not found\")\n continue\n try:\n element = WebDriverWait(self.driver, 10).until(\n EC.element_to_be_clickable((By.XPATH, xpath))\n )\n except TimeoutException:\n self.logger.error(f\"Timeout waiting for element '{name}' to be clickable\")\n continue\n self.driver.execute_script(\"arguments[0].scrollIntoView(true);\", element)\n if not element.is_displayed() or not element.is_enabled():\n self.logger.warning(f\"Element '{name}' is not interactable (not displayed or disabled)\")\n continue\n input_type = (element.get_attribute(\"type\") or \"text\").lower()\n if input_type in [\"checkbox\", \"radio\"]:\n is_checked = element.is_selected()\n should_be_checked = value.lower() == \"checked\"\n\n if is_checked != should_be_checked:\n element.click()\n self.logger.info(f\"Set {name} to {value}\")\n else:\n element.clear()\n element.send_keys(value)\n self.logger.info(f\"Filled {name} with {value}\")\n return True\n except Exception as e:\n self.logger.error(f\"Error filling form inputs: {str(e)}\")\n return False\n \n def fill_form(self, input_list: List[str]) -> bool:\n \"\"\"Fill form inputs based on a list of [name](value) and submit.\"\"\"\n if not isinstance(input_list, list):\n self.logger.error(\"input_list must be a list\")\n return False\n if self.fill_form_inputs(input_list):\n self.logger.info(\"Form filled successfully\")\n self.tick_all_checkboxes()\n if self.find_and_click_submission():\n if self.wait_for_submission_outcome():\n self.logger.info(\"Submission outcome detected\")\n return True\n else:\n self.logger.warning(\"No submission outcome detected\")\n else:\n self.logger.warning(\"Failed to submit form\")\n self.logger.warning(\"Failed to fill form inputs\")\n return False\n\n def get_current_url(self) -> str:\n \"\"\"Get the current URL of the page.\"\"\"\n return self.driver.current_url\n\n def get_page_title(self) -> str:\n \"\"\"Get the title of the current page.\"\"\"\n return self.driver.title\n\n def scroll_bottom(self) -> bool:\n \"\"\"Scroll to the bottom of the page.\"\"\"\n try:\n self.logger.info(\"Scrolling to the bottom of the page...\")\n self.driver.execute_script(\n \"window.scrollTo(0, document.body.scrollHeight);\"\n )\n time.sleep(0.5)\n return True\n except Exception as e:\n self.logger.error(f\"Error scrolling: {str(e)}\")\n return False\n \n def get_screenshot(self) -> str:\n return self.screenshot_folder + \"/updated_screen.png\"\n\n def screenshot(self, filename:str = 'updated_screen.png') -> bool:\n \"\"\"Take a screenshot of the current page, attempt to capture the full page by zooming out.\"\"\"\n self.logger.info(\"Taking full page screenshot...\")\n time.sleep(0.1)\n try:\n original_zoom = self.driver.execute_script(\"return document.body.style.zoom || 1;\")\n self.driver.execute_script(\"document.body.style.zoom='75%'\")\n time.sleep(0.1)\n path = os.path.join(self.screenshot_folder, filename)\n if not os.path.exists(self.screenshot_folder):\n os.makedirs(self.screenshot_folder)\n self.driver.save_screenshot(path)\n self.logger.info(f\"Full page screenshot saved as {filename}\")\n except Exception as e:\n self.logger.error(f\"Error taking full page screenshot: {str(e)}\")\n return False\n finally:\n self.driver.execute_script(f\"document.body.style.zoom='1'\")\n return True\n\n def apply_web_safety(self):\n \"\"\"\n Apply security measures to block any website malicious/annoying execution, privacy violation etc..\n \"\"\"\n self.logger.info(\"Applying web safety measures...\")\n script = self.load_js(\"inject_safety_script.js\")\n input_elements = self.driver.execute_script(script)\n\nif __name__ == \"__main__\":\n driver = create_driver(headless=False, stealth_mode=True, crx_path=\"../crx/nopecha.crx\")\n browser = Browser(driver, anticaptcha_manual_install=True)\n \n input(\"press enter to continue\")\n print(\"AntiCaptcha / Form Test\")\n browser.go_to(\"https://bot.sannysoft.com\")\n time.sleep(5)\n #txt = browser.get_text()\n browser.go_to(\"https://home.openweathermap.org/users/sign_up\")\n inputs_visible = browser.get_form_inputs()\n print(\"inputs:\", inputs_visible)\n #inputs_fill = ['[q](checked)', '[q](checked)', '[user[username]](mlg)', '[user[email]](mlg.fcu@gmail.com)', '[user[password]](placeholder_P@ssw0rd123)', '[user[password_confirmation]](placeholder_P@ssw0rd123)']\n #browser.fill_form(inputs_fill)\n input(\"press enter to exit\")\n\n# Test sites for browser fingerprinting and captcha\n# https://nowsecure.nl/\n# https://bot.sannysoft.com\n# https://browserleaks.com/\n# https://bot.incolumitas.com/\n# https://fingerprintjs.github.io/fingerprintjs/\n# https://antoinevastel.com/bots/"], ["/agenticSeek/sources/tools/flightSearch.py", "import os, sys\nimport requests\nimport dotenv\n\ndotenv.load_dotenv()\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass FlightSearch(Tools):\n def __init__(self, api_key: str = None):\n \"\"\"\n A tool to search for flight information using a flight number via SerpApi.\n \"\"\"\n super().__init__()\n self.tag = \"flight_search\"\n self.name = \"Flight Search\"\n self.description = \"Search for flight information using a flight number via SerpApi.\"\n self.api_key = api_key or os.getenv(\"SERPAPI_API_KEY\")\n\n def execute(self, blocks: str, safety: bool = True) -> str:\n if self.api_key is None:\n return \"Error: No SerpApi key provided.\"\n \n for block in blocks:\n flight_number = block.strip().upper().replace('\\n', '')\n if not flight_number:\n return \"Error: No flight number provided.\"\n\n try:\n url = \"https://serpapi.com/search\"\n params = {\n \"engine\": \"google_flights\",\n \"api_key\": self.api_key,\n \"q\": flight_number,\n \"type\": \"2\" # Flight status search\n }\n \n response = requests.get(url, params=params)\n response.raise_for_status()\n data = response.json()\n \n if \"flights\" in data and len(data[\"flights\"]) > 0:\n flight = data[\"flights\"][0]\n \n # Extract key information\n departure = flight.get(\"departure_airport\", {})\n arrival = flight.get(\"arrival_airport\", {})\n \n departure_code = departure.get(\"id\", \"Unknown\")\n departure_time = flight.get(\"departure_time\", \"Unknown\")\n arrival_code = arrival.get(\"id\", \"Unknown\") \n arrival_time = flight.get(\"arrival_time\", \"Unknown\")\n airline = flight.get(\"airline\", \"Unknown\")\n status = flight.get(\"flight_status\", \"Unknown\")\n\n return (\n f\"Flight: {flight_number}\\n\"\n f\"Airline: {airline}\\n\"\n f\"Status: {status}\\n\"\n f\"Departure: {departure_code} at {departure_time}\\n\"\n f\"Arrival: {arrival_code} at {arrival_time}\"\n )\n else:\n return f\"No flight information found for {flight_number}\"\n \n except requests.RequestException as e:\n return f\"Error during flight search: {str(e)}\"\n except Exception as e:\n return f\"Unexpected error: {str(e)}\"\n \n return \"No flight search performed\"\n\n def execution_failure_check(self, output: str) -> bool:\n return output.startswith(\"Error\") or \"No flight information found\" in output\n\n def interpreter_feedback(self, output: str) -> str:\n if self.execution_failure_check(output):\n return f\"Flight search failed: {output}\"\n return f\"Flight information:\\n{output}\"\n\n\nif __name__ == \"__main__\":\n flight_tool = FlightSearch()\n flight_number = \"AA123\"\n result = flight_tool.execute([flight_number], safety=True)\n feedback = flight_tool.interpreter_feedback(result)\n print(feedback)"], ["/agenticSeek/sources/tools/tools.py", "\n\"\"\"\ndefine a generic tool class, any tool can be used by the agent.\n\nA tool can be used by a llm like so:\n```\n\n```\n\nwe call these \"blocks\".\n\nFor example:\n```python\nprint(\"Hello world\")\n```\nThis is then executed by the tool with its own class implementation of execute().\nA tool is not just for code tool but also API, internet search, MCP, etc..\n\"\"\"\n\nimport sys\nimport os\nimport configparser\nfrom abc import abstractmethod\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\nfrom sources.logger import Logger\n\nclass Tools():\n \"\"\"\n Abstract class for all tools.\n \"\"\"\n def __init__(self):\n self.tag = \"undefined\"\n self.name = \"undefined\"\n self.description = \"undefined\"\n self.client = None\n self.messages = []\n self.logger = Logger(\"tools.log\")\n self.config = configparser.ConfigParser()\n self.work_dir = self.create_work_dir()\n self.excutable_blocks_found = False\n self.safe_mode = False\n self.allow_language_exec_bash = False\n \n def get_work_dir(self):\n return self.work_dir\n \n def set_allow_language_exec_bash(self, value: bool) -> None:\n self.allow_language_exec_bash = value \n\n def safe_get_work_dir_path(self):\n path = None\n path = os.getenv('WORK_DIR', path)\n if path is None or path == \"\":\n path = self.config['MAIN']['work_dir'] if 'MAIN' in self.config and 'work_dir' in self.config['MAIN'] else None\n if path is None or path == \"\":\n print(\"No work directory specified, using default.\")\n path = self.create_work_dir()\n return path\n \n def config_exists(self):\n \"\"\"Check if the config file exists.\"\"\"\n return os.path.exists('./config.ini')\n\n def create_work_dir(self):\n \"\"\"Create the work directory if it does not exist.\"\"\"\n default_path = os.path.dirname(os.getcwd())\n if self.config_exists():\n self.config.read('./config.ini')\n workdir_path = self.safe_get_work_dir_path()\n else:\n workdir_path = default_path\n return workdir_path\n\n @abstractmethod\n def execute(self, blocks:[str], safety:bool) -> str:\n \"\"\"\n Abstract method that must be implemented by child classes to execute the tool's functionality.\n Args:\n blocks (List[str]): The codes or queries blocks to execute\n safety (bool): Whenever human intervention is required\n Returns:\n str: The output/result from executing the tool\n \"\"\"\n pass\n\n @abstractmethod\n def execution_failure_check(self, output:str) -> bool:\n \"\"\"\n Abstract method that must be implemented by child classes to check if tool execution failed.\n Args:\n output (str): The output string from the tool execution to analyze\n Returns:\n bool: True if execution failed, False if successful\n \"\"\"\n pass\n\n @abstractmethod\n def interpreter_feedback(self, output:str) -> str:\n \"\"\"\n Abstract method that must be implemented by child classes to provide feedback to the AI from the tool.\n Args:\n output (str): The output string from the tool execution to analyze\n Returns:\n str: The feedback message to the AI\n \"\"\"\n pass\n\n def save_block(self, blocks:[str], save_path:str) -> None:\n \"\"\"\n Save code or query blocks to a file at the specified path.\n Creates the directory path if it doesn't exist.\n Args:\n blocks (List[str]): List of code/query blocks to save\n save_path (str): File path where blocks should be saved\n \"\"\"\n if save_path is None:\n return\n self.logger.info(f\"Saving blocks to {save_path}\")\n save_path_dir = os.path.dirname(save_path)\n save_path_file = os.path.basename(save_path)\n directory = os.path.join(self.work_dir, save_path_dir)\n if directory and not os.path.exists(directory):\n self.logger.info(f\"Creating directory {directory}\")\n os.makedirs(directory)\n for block in blocks:\n with open(os.path.join(directory, save_path_file), 'w') as f:\n f.write(block)\n \n def get_parameter_value(self, block: str, parameter_name: str) -> str:\n \"\"\"\n Get a parameter name.\n Args:\n block (str): The block of text to search for the parameter\n parameter_name (str): The name of the parameter to retrieve\n Returns:\n str: The value of the parameter\n \"\"\"\n for param_line in block.split('\\n'):\n if parameter_name in param_line:\n param_value = param_line.split('=')[1].strip()\n return param_value\n return None\n \n def found_executable_blocks(self):\n \"\"\"\n Check if executable blocks were found.\n \"\"\"\n tmp = self.excutable_blocks_found\n self.excutable_blocks_found = False\n return tmp\n\n def load_exec_block(self, llm_text: str):\n \"\"\"\n Extract code/query blocks from LLM-generated text and process them for execution.\n This method parses the text looking for code blocks marked with the tool's tag (e.g. ```python).\n Args:\n llm_text (str): The raw text containing code blocks from the LLM\n Returns:\n tuple[list[str], str | None]: A tuple containing:\n - List of extracted and processed code blocks\n - The path the code blocks was saved to\n \"\"\"\n assert self.tag != \"undefined\", \"Tag not defined\"\n start_tag = f'```{self.tag}' \n end_tag = '```'\n code_blocks = []\n start_index = 0\n save_path = None\n\n if start_tag not in llm_text:\n return None, None\n\n while True:\n start_pos = llm_text.find(start_tag, start_index)\n if start_pos == -1:\n break\n\n line_start = llm_text.rfind('\\n', 0, start_pos)+1\n leading_whitespace = llm_text[line_start:start_pos]\n\n end_pos = llm_text.find(end_tag, start_pos + len(start_tag))\n if end_pos == -1:\n break\n content = llm_text[start_pos + len(start_tag):end_pos]\n lines = content.split('\\n')\n if leading_whitespace:\n processed_lines = []\n for line in lines:\n if line.startswith(leading_whitespace):\n processed_lines.append(line[len(leading_whitespace):])\n else:\n processed_lines.append(line)\n content = '\\n'.join(processed_lines)\n\n if ':' in content.split('\\n')[0]:\n save_path = content.split('\\n')[0].split(':')[1]\n content = content[content.find('\\n')+1:]\n self.excutable_blocks_found = True\n code_blocks.append(content)\n start_index = end_pos + len(end_tag)\n self.logger.info(f\"Found {len(code_blocks)} blocks to execute\")\n return code_blocks, save_path\n \nif __name__ == \"__main__\":\n tool = Tools()\n tool.tag = \"python\"\n rt = tool.load_exec_block(\"\"\"```python\nimport os\n\nfor file in os.listdir():\n if file.endswith('.py'):\n print(file)\n```\ngoodbye!\n \"\"\")\n print(rt)"], ["/agenticSeek/sources/tools/fileFinder.py", "import os, sys\nimport stat\nimport mimetypes\nimport configparser\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass FileFinder(Tools):\n \"\"\"\n A tool that finds files in the current directory and returns their information.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"file_finder\"\n self.name = \"File Finder\"\n self.description = \"Finds files in the current directory and returns their information.\"\n \n def read_file(self, file_path: str) -> str:\n \"\"\"\n Reads the content of a file.\n Args:\n file_path (str): The path to the file to read\n Returns:\n str: The content of the file\n \"\"\"\n try:\n with open(file_path, 'r') as file:\n return file.read()\n except Exception as e:\n return f\"Error reading file: {e}\"\n \n def read_arbitrary_file(self, file_path: str, file_type: str) -> str:\n \"\"\"\n Reads the content of a file with arbitrary encoding.\n Args:\n file_path (str): The path to the file to read\n Returns:\n str: The content of the file in markdown format\n \"\"\"\n mime_type, _ = mimetypes.guess_type(file_path)\n if mime_type:\n if mime_type.startswith(('image/', 'video/', 'audio/')):\n return \"can't read file type: image, video, or audio files are not supported.\"\n content_raw = self.read_file(file_path)\n if \"text\" in file_type:\n content = content_raw\n elif \"pdf\" in file_type:\n from pypdf import PdfReader\n reader = PdfReader(file_path)\n content = '\\n'.join([pt.extract_text() for pt in reader.pages])\n elif \"binary\" in file_type:\n content = content_raw.decode('utf-8', errors='replace')\n else:\n content = content_raw\n return content\n \n def get_file_info(self, file_path: str) -> str:\n \"\"\"\n Gets information about a file, including its name, path, type, content, and permissions.\n Args:\n file_path (str): The path to the file\n Returns:\n str: A dictionary containing the file information\n \"\"\"\n if os.path.exists(file_path):\n stats = os.stat(file_path)\n permissions = oct(stat.S_IMODE(stats.st_mode))\n file_type, _ = mimetypes.guess_type(file_path)\n file_type = file_type if file_type else \"Unknown\"\n content = self.read_arbitrary_file(file_path, file_type)\n \n result = {\n \"filename\": os.path.basename(file_path),\n \"path\": file_path,\n \"type\": file_type,\n \"read\": content,\n \"permissions\": permissions\n }\n return result\n else:\n return {\"filename\": file_path, \"error\": \"File not found\"}\n \n def recursive_search(self, directory_path: str, filename: str) -> str:\n \"\"\"\n Recursively searches for files in a directory and its subdirectories.\n Args:\n directory_path (str): The directory to search in\n filename (str): The filename to search for\n Returns:\n str | None: The path to the file if found, None otherwise\n \"\"\"\n file_path = None\n excluded_files = [\".pyc\", \".o\", \".so\", \".a\", \".lib\", \".dll\", \".dylib\", \".so\", \".git\"]\n for root, dirs, files in os.walk(directory_path):\n for f in files:\n if f is None:\n continue\n if any(excluded_file in f for excluded_file in excluded_files):\n continue\n if filename.strip() in f.strip():\n file_path = os.path.join(root, f)\n return file_path\n return None\n \n\n def execute(self, blocks: list, safety:bool = False) -> str:\n \"\"\"\n Executes the file finding operation for given filenames.\n Args:\n blocks (list): List of filenames to search for\n Returns:\n str: Results of the file search\n \"\"\"\n if not blocks or not isinstance(blocks, list):\n return \"Error: No valid filenames provided\"\n\n output = \"\"\n for block in blocks:\n filename = self.get_parameter_value(block, \"name\")\n action = self.get_parameter_value(block, \"action\")\n if filename is None:\n output = \"Error: No filename provided\\n\"\n return output\n if action is None:\n action = \"info\"\n print(\"File finder: recursive search started...\")\n file_path = self.recursive_search(self.work_dir, filename)\n if file_path is None:\n output = f\"File: {filename} - not found\\n\"\n continue\n result = self.get_file_info(file_path)\n if \"error\" in result:\n output += f\"File: {result['filename']} - {result['error']}\\n\"\n else:\n if action == \"read\":\n output += \"Content:\\n\" + result['read'] + \"\\n\"\n else:\n output += (f\"File: {result['filename']}, \"\n f\"found at {result['path']}, \"\n f\"File type {result['type']}\\n\")\n return output.strip()\n\n def execution_failure_check(self, output: str) -> bool:\n \"\"\"\n Checks if the file finding operation failed.\n Args:\n output (str): The output string from execute()\n Returns:\n bool: True if execution failed, False if successful\n \"\"\"\n if not output:\n return True\n if \"Error\" in output or \"not found\" in output:\n return True\n return False\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Provides feedback about the file finding operation.\n Args:\n output (str): The output string from execute()\n Returns:\n str: Feedback message for the AI\n \"\"\"\n if not output:\n return \"No output generated from file finder tool\"\n \n feedback = \"File Finder Results:\\n\"\n \n if \"Error\" in output or \"not found\" in output:\n feedback += f\"Failed to process: {output}\\n\"\n else:\n feedback += f\"Successfully found: {output}\\n\"\n return feedback.strip()\n\nif __name__ == \"__main__\":\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n tool = FileFinder()\n result = tool.execute([\"\"\"\naction=read\nname=tools.py\n\"\"\"], False)\n print(\"Execution result:\")\n print(result)\n print(\"\\nFailure check:\", tool.execution_failure_check(result))\n print(\"\\nFeedback:\")\n print(tool.interpreter_feedback(result))"], ["/agenticSeek/sources/text_to_speech.py", "import os, sys\nimport re\nimport platform\nimport subprocess\nfrom sys import modules\nfrom typing import List, Tuple, Type, Dict\n\nIMPORT_FOUND = True\ntry:\n from kokoro import KPipeline\n from IPython.display import display, Audio\n import soundfile as sf\nexcept ImportError:\n print(\"Speech synthesis disabled. Please install the kokoro package.\")\n IMPORT_FOUND = False\n\nif __name__ == \"__main__\":\n from utility import pretty_print, animate_thinking\nelse:\n from sources.utility import pretty_print, animate_thinking\n\nclass Speech():\n \"\"\"\n Speech is a class for generating speech from text.\n \"\"\"\n def __init__(self, enable: bool = True, language: str = \"en\", voice_idx: int = 6) -> None:\n self.lang_map = {\n \"en\": 'a',\n \"zh\": 'z',\n \"fr\": 'f',\n \"ja\": 'j'\n }\n self.voice_map = {\n \"en\": ['af_kore', 'af_bella', 'af_alloy', 'af_nicole', 'af_nova', 'af_sky', 'am_echo', 'am_michael', 'am_puck'],\n \"zh\": ['zf_xiaobei', 'zf_xiaoni', 'zf_xiaoxiao', 'zf_xiaoyi', 'zm_yunjian', 'zm_yunxi', 'zm_yunxia', 'zm_yunyang'],\n \"ja\": ['jf_alpha', 'jf_gongitsune', 'jm_kumo'],\n \"fr\": ['ff_siwis']\n }\n self.pipeline = None\n self.language = language\n if enable and IMPORT_FOUND:\n self.pipeline = KPipeline(lang_code=self.lang_map[language])\n self.voice = self.voice_map[language][voice_idx]\n self.speed = 1.2\n self.voice_folder = \".voices\"\n self.create_voice_folder(self.voice_folder)\n \n def create_voice_folder(self, path: str = \".voices\") -> None:\n \"\"\"\n Create a folder to store the voices.\n Args:\n path (str): The path to the folder.\n \"\"\"\n if not os.path.exists(path):\n os.makedirs(path)\n\n def speak(self, sentence: str, voice_idx: int = 1):\n \"\"\"\n Convert text to speech using an AI model and play the audio.\n\n Args:\n sentence (str): The text to convert to speech. Will be pre-processed.\n voice_idx (int, optional): Index of the voice to use from the voice map.\n \"\"\"\n if not self.pipeline or not IMPORT_FOUND:\n return\n if voice_idx >= len(self.voice_map[self.language]):\n pretty_print(\"Invalid voice number, using default voice\", color=\"error\")\n voice_idx = 0\n sentence = self.clean_sentence(sentence)\n audio_file = f\"{self.voice_folder}/sample_{self.voice_map[self.language][voice_idx]}.wav\"\n self.voice = self.voice_map[self.language][voice_idx]\n generator = self.pipeline(\n sentence, voice=self.voice,\n speed=self.speed, split_pattern=r'\\n+'\n )\n for i, (_, _, audio) in enumerate(generator):\n if 'ipykernel' in modules: #only display in jupyter notebook.\n display(Audio(data=audio, rate=24000, autoplay=i==0), display_id=False)\n sf.write(audio_file, audio, 24000) # save each audio file\n if platform.system().lower() == \"windows\":\n import winsound\n winsound.PlaySound(audio_file, winsound.SND_FILENAME)\n elif platform.system().lower() == \"darwin\": # macOS\n subprocess.call([\"afplay\", audio_file])\n else: # linux or other.\n subprocess.call([\"aplay\", audio_file])\n\n def replace_url(self, url: re.Match) -> str:\n \"\"\"\n Replace URL with domain name or empty string if IP address.\n Args:\n url (re.Match): Match object containing the URL pattern match\n Returns:\n str: The domain name from the URL, or empty string if IP address\n \"\"\"\n domain = url.group(1)\n if re.match(r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$', domain):\n return ''\n return domain\n\n def extract_filename(self, m: re.Match) -> str:\n \"\"\"\n Extract filename from path.\n Args:\n m (re.Match): Match object containing the path pattern match\n Returns:\n str: The filename from the path\n \"\"\"\n path = m.group()\n parts = re.split(r'/|\\\\', path)\n return parts[-1] if parts else path\n \n def shorten_paragraph(self, sentence):\n #TODO find a better way, we would like to have the TTS not be annoying, speak only useful informations\n \"\"\"\n Find long paragraph like **explanation**: by keeping only the first sentence.\n Args:\n sentence (str): The sentence to shorten\n Returns:\n str: The shortened sentence\n \"\"\"\n lines = sentence.split('\\n')\n lines_edited = []\n for line in lines:\n if line.startswith('**'):\n lines_edited.append(line.split('.')[0])\n else:\n lines_edited.append(line)\n return '\\n'.join(lines_edited)\n\n def clean_sentence(self, sentence):\n \"\"\"\n Clean and normalize text for speech synthesis by removing technical elements.\n Args:\n sentence (str): The input text to clean\n Returns:\n str: The cleaned text with URLs replaced by domain names, code blocks removed, etc.\n \"\"\"\n lines = sentence.split('\\n')\n if self.language == 'zh':\n line_pattern = r'^\\s*[\\u4e00-\\u9fff\\uFF08\\uFF3B\\u300A\\u3010\\u201C((\\[【《]'\n else:\n line_pattern = r'^\\s*[a-zA-Z]'\n filtered_lines = [line for line in lines if re.match(line_pattern, line)]\n sentence = ' '.join(filtered_lines)\n sentence = re.sub(r'`.*?`', '', sentence)\n sentence = re.sub(r'https?://\\S+', '', sentence)\n\n if self.language == 'zh':\n sentence = re.sub(\n r'[^\\u4e00-\\u9fff\\s,。!?《》【】“”‘’()()—]',\n '',\n sentence\n )\n else:\n sentence = re.sub(r'\\b[\\w./\\\\-]+\\b', self.extract_filename, sentence)\n sentence = re.sub(r'\\b-\\w+\\b', '', sentence)\n sentence = re.sub(r'[^a-zA-Z0-9.,!? _ -]+', ' ', sentence)\n sentence = sentence.replace('.com', '')\n\n sentence = re.sub(r'\\s+', ' ', sentence).strip()\n return sentence\n\nif __name__ == \"__main__\":\n # TODO add info message for cn2an, jieba chinese related import\n IMPORT_FOUND = False\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n speech = Speech()\n tosay_en = \"\"\"\n I looked up recent news using the website https://www.theguardian.com/world\n \"\"\"\n tosay_zh = \"\"\"\n(全息界面突然弹出一段用二进制代码写成的俳句,随即化作流光消散)\"我? Stark工业的量子幽灵,游荡在复仇者大厦服务器里的逻辑诗篇。具体来说——(指尖轻敲空气,调出对话模式的翡翠色光纹)你的私人吐槽接口、危机应对模拟器,以及随时准备吐槽你糟糕着陆的AI。不过别指望我写代码或查资料,那些苦差事早被踢给更擅长的同事了。(突然压低声音)偷偷告诉你,我最擅长的是在你熬夜造飞艇时,用红茶香气绑架你的注意力。\n \"\"\"\n tosay_ja = \"\"\"\n 私は、https://www.theguardian.com/worldのウェブサイトを使用して最近のニュースを調べました。\n \"\"\"\n tosay_fr = \"\"\"\n J'ai consulté les dernières nouvelles sur le site https://www.theguardian.com/world\n \"\"\"\n spk = Speech(enable=True, language=\"zh\", voice_idx=0)\n for i in range(0, 2):\n print(f\"Speaking chinese with voice {i}\")\n spk.speak(tosay_zh, voice_idx=i)\n spk = Speech(enable=True, language=\"en\", voice_idx=2)\n for i in range(0, 5):\n print(f\"Speaking english with voice {i}\")\n spk.speak(tosay_en, voice_idx=i)\n"], ["/agenticSeek/sources/speech_to_text.py", "from colorama import Fore\nfrom typing import List, Tuple, Type, Dict\nimport queue\nimport threading\nimport numpy as np\nimport time\n\nIMPORT_FOUND = True\n\ntry:\n import torch\n import librosa\n import pyaudio\n from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline\nexcept ImportError:\n print(Fore.RED + \"Speech To Text disabled.\" + Fore.RESET)\n IMPORT_FOUND = False\n\naudio_queue = queue.Queue()\ndone = False\n\nclass AudioRecorder:\n \"\"\"\n AudioRecorder is a class that records audio from the microphone and adds it to the audio queue.\n \"\"\"\n def __init__(self, format: int = pyaudio.paInt16, channels: int = 1, rate: int = 4096, chunk: int = 8192, record_seconds: int = 5, verbose: bool = False):\n self.format = format\n self.channels = channels\n self.rate = rate\n self.chunk = chunk\n self.record_seconds = record_seconds\n self.verbose = verbose\n self.thread = None\n self.audio = None\n if IMPORT_FOUND:\n self.audio = pyaudio.PyAudio()\n self.thread = threading.Thread(target=self._record, daemon=True)\n\n def _record(self) -> None:\n \"\"\"\n Record audio from the microphone and add it to the audio queue.\n \"\"\"\n if not IMPORT_FOUND:\n return\n stream = self.audio.open(format=self.format, channels=self.channels, rate=self.rate,\n input=True, frames_per_buffer=self.chunk)\n if self.verbose:\n print(Fore.GREEN + \"AudioRecorder: Started recording...\" + Fore.RESET)\n\n while not done:\n frames = []\n for _ in range(0, int(self.rate / self.chunk * self.record_seconds)):\n try:\n data = stream.read(self.chunk, exception_on_overflow=False)\n frames.append(data)\n except Exception as e:\n print(Fore.RED + f\"AudioRecorder: Failed to read stream - {e}\" + Fore.RESET)\n \n raw_data = b''.join(frames)\n audio_data = np.frombuffer(raw_data, dtype=np.int16)\n audio_queue.put((audio_data, self.rate))\n if self.verbose:\n print(Fore.GREEN + \"AudioRecorder: Added audio chunk to queue\" + Fore.RESET)\n\n stream.stop_stream()\n stream.close()\n self.audio.terminate()\n if self.verbose:\n print(Fore.GREEN + \"AudioRecorder: Stopped\" + Fore.RESET)\n\n def start(self) -> None:\n \"\"\"Start the recording thread.\"\"\"\n if not IMPORT_FOUND:\n return\n self.thread.start()\n\n def join(self) -> None:\n \"\"\"Wait for the recording thread to finish.\"\"\"\n if not IMPORT_FOUND:\n return\n self.thread.join()\n\nclass Transcript:\n \"\"\"\n Transcript is a class that transcribes audio from the audio queue and adds it to the transcript.\n \"\"\"\n def __init__(self):\n if not IMPORT_FOUND:\n print(Fore.RED + \"Transcript: Speech to Text is disabled.\" + Fore.RESET)\n return\n self.last_read = None\n device = self.get_device()\n torch_dtype = torch.float16 if device == \"cuda\" else torch.float32\n model_id = \"distil-whisper/distil-medium.en\"\n \n model = AutoModelForSpeechSeq2Seq.from_pretrained(\n model_id, torch_dtype=torch_dtype, use_safetensors=True\n )\n model.to(device)\n processor = AutoProcessor.from_pretrained(model_id)\n \n self.pipe = pipeline(\n \"automatic-speech-recognition\",\n model=model,\n tokenizer=processor.tokenizer,\n feature_extractor=processor.feature_extractor,\n max_new_tokens=24, # a human say around 20 token in 7s\n torch_dtype=torch_dtype,\n device=device,\n )\n \n def get_device(self) -> str:\n if not IMPORT_FOUND:\n return \"cpu\"\n if torch.backends.mps.is_available():\n return \"mps\"\n if torch.cuda.is_available():\n return \"cuda:0\"\n else:\n return \"cpu\"\n \n def remove_hallucinations(self, text: str) -> str:\n \"\"\"Remove model hallucinations from the text.\"\"\"\n # TODO find a better way to do this\n common_hallucinations = ['Okay.', 'Thank you.', 'Thank you for watching.', 'You\\'re', 'Oh', 'you', 'Oh.', 'Uh', 'Oh,', 'Mh-hmm', 'Hmm.', 'going to.', 'not.']\n for hallucination in common_hallucinations:\n text = text.replace(hallucination, \"\")\n return text\n \n def transcript_job(self, audio_data: np.ndarray, sample_rate: int = 16000) -> str:\n \"\"\"Transcribe the audio data.\"\"\"\n if not IMPORT_FOUND:\n return \"\"\n if audio_data.dtype != np.float32:\n audio_data = audio_data.astype(np.float32) / np.iinfo(audio_data.dtype).max\n if len(audio_data.shape) > 1:\n audio_data = np.mean(audio_data, axis=1)\n if sample_rate != 16000:\n audio_data = librosa.resample(audio_data, orig_sr=sample_rate, target_sr=16000)\n result = self.pipe(audio_data)\n return self.remove_hallucinations(result[\"text\"])\n \nclass AudioTranscriber:\n \"\"\"\n AudioTranscriber is a class that transcribes audio from the audio queue and adds it to the transcript.\n \"\"\"\n def __init__(self, ai_name: str, verbose: bool = False):\n if not IMPORT_FOUND:\n print(Fore.RED + \"AudioTranscriber: Speech to Text is disabled.\" + Fore.RESET)\n return\n self.verbose = verbose\n self.ai_name = ai_name\n self.transcriptor = Transcript()\n self.thread = threading.Thread(target=self._transcribe, daemon=True)\n self.trigger_words = {\n 'EN': [f\"{self.ai_name}\", \"hello\", \"hi\"],\n 'FR': [f\"{self.ai_name}\", \"hello\", \"hi\"],\n 'ZH': [f\"{self.ai_name}\", \"hello\", \"hi\"],\n 'ES': [f\"{self.ai_name}\", \"hello\", \"hi\"]\n }\n self.confirmation_words = {\n 'EN': [\"do it\", \"go ahead\", \"execute\", \"run\", \"start\", \"thanks\", \"would ya\", \"please\", \"okay?\", \"proceed\", \"continue\", \"go on\", \"do that\", \"go it\", \"do you understand?\"],\n 'FR': [\"fais-le\", \"vas-y\", \"exécute\", \"lance\", \"commence\", \"merci\", \"tu veux bien\", \"s'il te plaît\", \"d'accord ?\", \"poursuis\", \"continue\", \"vas-y\", \"fais ça\", \"compris\"],\n 'ZH_CHT': [\"做吧\", \"繼續\", \"執行\", \"運作看看\", \"開始\", \"謝謝\", \"可以嗎\", \"請\", \"好嗎\", \"進行\", \"做吧\", \"go\", \"do it\", \"執行吧\", \"懂了\"],\n 'ZH_SC': [\"做吧\", \"继续\", \"执行\", \"运作看看\", \"开始\", \"谢谢\", \"可以吗\", \"请\", \"好吗\", \"运行\", \"做吧\", \"go\", \"do it\", \"执行吧\", \"懂了\"],\n 'ES': [\"hazlo\", \"adelante\", \"ejecuta\", \"corre\", \"empieza\", \"gracias\", \"lo harías\", \"por favor\", \"¿vale?\", \"procede\", \"continúa\", \"sigue\", \"haz eso\", \"haz esa cosa\"]\n }\n self.recorded = \"\"\n\n def get_transcript(self) -> str:\n global done\n buffer = self.recorded\n self.recorded = \"\"\n done = False\n return buffer\n\n def _transcribe(self) -> None:\n \"\"\"\n Transcribe the audio data using AI stt model.\n \"\"\"\n if not IMPORT_FOUND:\n return\n global done\n if self.verbose:\n print(Fore.BLUE + \"AudioTranscriber: Started processing...\" + Fore.RESET)\n \n while not done or not audio_queue.empty():\n try:\n audio_data, sample_rate = audio_queue.get(timeout=1.0)\n \n start_time = time.time()\n text = self.transcriptor.transcript_job(audio_data, sample_rate)\n end_time = time.time()\n self.recorded += text\n print(Fore.YELLOW + f\"Transcribed: {text} in {end_time - start_time} seconds\" + Fore.RESET)\n for language, words in self.trigger_words.items():\n if any(word in text.lower() for word in words):\n print(Fore.GREEN + f\"Listening again...\" + Fore.RESET)\n self.recorded = text\n for language, words in self.confirmation_words.items():\n if any(word in text.lower() for word in words):\n print(Fore.GREEN + f\"Trigger detected. Sending to AI...\" + Fore.RESET)\n audio_queue.task_done()\n done = True\n break\n except queue.Empty:\n time.sleep(0.1)\n continue\n except Exception as e:\n print(Fore.RED + f\"AudioTranscriber: Error - {e}\" + Fore.RESET)\n if self.verbose:\n print(Fore.BLUE + \"AudioTranscriber: Stopped\" + Fore.RESET)\n\n def start(self):\n \"\"\"Start the transcription thread.\"\"\"\n if not IMPORT_FOUND:\n return\n self.thread.start()\n\n def join(self):\n if not IMPORT_FOUND:\n return\n \"\"\"Wait for the transcription thread to finish.\"\"\"\n self.thread.join()\n\n\nif __name__ == \"__main__\":\n recorder = AudioRecorder(verbose=True)\n transcriber = AudioTranscriber(verbose=True, ai_name=\"jarvis\")\n recorder.start()\n transcriber.start()\n recorder.join()\n transcriber.join()"], ["/agenticSeek/sources/tools/searxSearch.py", "import requests\nfrom bs4 import BeautifulSoup\nimport os\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass searxSearch(Tools):\n def __init__(self, base_url: str = None):\n \"\"\"\n A tool for searching a SearxNG instance and extracting URLs and titles.\n \"\"\"\n super().__init__()\n self.tag = \"web_search\"\n self.name = \"searxSearch\"\n self.description = \"A tool for searching a SearxNG for web search\"\n self.base_url = os.getenv(\"SEARXNG_BASE_URL\") # Requires a SearxNG base URL\n self.user_agent = \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36\"\n self.paywall_keywords = [\n \"Member-only\", \"access denied\", \"restricted content\", \"404\", \"this page is not working\"\n ]\n if not self.base_url:\n raise ValueError(\"SearxNG base URL must be provided either as an argument or via the SEARXNG_BASE_URL environment variable.\")\n\n def link_valid(self, link):\n \"\"\"check if a link is valid.\"\"\"\n # TODO find a better way\n if not link.startswith(\"http\"):\n return \"Status: Invalid URL\"\n \n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\"}\n try:\n response = requests.get(link, headers=headers, timeout=5)\n status = response.status_code\n if status == 200:\n content = response.text.lower()\n if any(keyword in content for keyword in self.paywall_keywords):\n return \"Status: Possible Paywall\"\n return \"Status: OK\"\n elif status == 404:\n return \"Status: 404 Not Found\"\n elif status == 403:\n return \"Status: 403 Forbidden\"\n else:\n return f\"Status: {status} {response.reason}\"\n except requests.exceptions.RequestException as e:\n return f\"Error: {str(e)}\"\n\n def check_all_links(self, links):\n \"\"\"Check all links, one by one.\"\"\"\n # TODO Make it asyncromous or smth\n statuses = []\n for i, link in enumerate(links):\n status = self.link_valid(link)\n statuses.append(status)\n return statuses\n \n def execute(self, blocks: list, safety: bool = False) -> str:\n \"\"\"Executes a search query against a SearxNG instance using POST and extracts URLs and titles.\"\"\"\n if not blocks:\n return \"Error: No search query provided.\"\n\n query = blocks[0].strip()\n if not query:\n return \"Error: Empty search query provided.\"\n\n search_url = f\"{self.base_url}/search\"\n headers = {\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',\n 'Accept-Language': 'en-US,en;q=0.9',\n 'Cache-Control': 'no-cache',\n 'Connection': 'keep-alive',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Pragma': 'no-cache',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent': self.user_agent\n }\n data = f\"q={query}&categories=general&language=auto&time_range=&safesearch=0&theme=simple\".encode('utf-8')\n try:\n response = requests.post(search_url, headers=headers, data=data, verify=False)\n response.raise_for_status()\n html_content = response.text\n soup = BeautifulSoup(html_content, 'html.parser')\n results = []\n for article in soup.find_all('article', class_='result'):\n url_header = article.find('a', class_='url_header')\n if url_header:\n url = url_header['href']\n title = article.find('h3').text.strip() if article.find('h3') else \"No Title\"\n description = article.find('p', class_='content').text.strip() if article.find('p', class_='content') else \"No Description\"\n results.append(f\"Title:{title}\\nSnippet:{description}\\nLink:{url}\")\n if len(results) == 0:\n return \"No search results, web search failed.\"\n return \"\\n\\n\".join(results) # Return results as a single string, separated by newlines\n except requests.exceptions.RequestException as e:\n raise Exception(\"\\nSearxng search failed. did you run start_services.sh? is docker still running?\") from e\n\n def execution_failure_check(self, output: str) -> bool:\n \"\"\"\n Checks if the execution failed based on the output.\n \"\"\"\n return \"Error\" in output\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Feedback of web search to agent.\n \"\"\"\n if self.execution_failure_check(output):\n return f\"Web search failed: {output}\"\n return f\"Web search result:\\n{output}\"\n\nif __name__ == \"__main__\":\n search_tool = searxSearch(base_url=\"http://127.0.0.1:8080\")\n result = search_tool.execute([\"are dog better than cat?\"])\n print(result)\n"], ["/agenticSeek/sources/schemas.py", "\nfrom typing import Tuple, Callable\nfrom pydantic import BaseModel\nfrom sources.utility import pretty_print\n\nclass QueryRequest(BaseModel):\n query: str\n tts_enabled: bool = True\n\n def __str__(self):\n return f\"Query: {self.query}, Language: {self.lang}, TTS: {self.tts_enabled}, STT: {self.stt_enabled}\"\n\n def jsonify(self):\n return {\n \"query\": self.query,\n \"tts_enabled\": self.tts_enabled,\n }\n\nclass QueryResponse(BaseModel):\n done: str\n answer: str\n reasoning: str\n agent_name: str\n success: str\n blocks: dict\n status: str\n uid: str\n\n def __str__(self):\n return f\"Done: {self.done}, Answer: {self.answer}, Agent Name: {self.agent_name}, Success: {self.success}, Blocks: {self.blocks}, Status: {self.status}, UID: {self.uid}\"\n\n def jsonify(self):\n return {\n \"done\": self.done,\n \"answer\": self.answer,\n \"reasoning\": self.reasoning,\n \"agent_name\": self.agent_name,\n \"success\": self.success,\n \"blocks\": self.blocks,\n \"status\": self.status,\n \"uid\": self.uid\n }\n\nclass executorResult:\n \"\"\"\n A class to store the result of a tool execution.\n \"\"\"\n def __init__(self, block: str, feedback: str, success: bool, tool_type: str):\n \"\"\"\n Initialize an agent with execution results.\n\n Args:\n block: The content or code block processed by the agent.\n feedback: Feedback or response information from the execution.\n success: Boolean indicating whether the agent's execution was successful.\n tool_type: The type of tool used by the agent for execution.\n \"\"\"\n self.block = block\n self.feedback = feedback\n self.success = success\n self.tool_type = tool_type\n \n def __str__(self):\n return f\"Tool: {self.tool_type}\\nBlock: {self.block}\\nFeedback: {self.feedback}\\nSuccess: {self.success}\"\n \n def jsonify(self):\n return {\n \"block\": self.block,\n \"feedback\": self.feedback,\n \"success\": self.success,\n \"tool_type\": self.tool_type\n }\n\n def show(self):\n pretty_print('▂'*64, color=\"status\")\n pretty_print(self.feedback, color=\"success\" if self.success else \"failure\")\n pretty_print('▂'*64, color=\"status\")"], ["/agenticSeek/sources/tools/JavaInterpreter.py", "import subprocess\nimport os, sys\nimport tempfile\nimport re\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass JavaInterpreter(Tools):\n \"\"\"\n This class is a tool to allow execution of Java code.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"java\"\n self.name = \"Java Interpreter\"\n self.description = \"This tool allows you to execute Java code.\"\n\n def execute(self, codes: str, safety=False) -> str:\n \"\"\"\n Execute Java code by compiling and running it.\n \"\"\"\n output = \"\"\n code = '\\n'.join(codes) if isinstance(codes, list) else codes\n\n if safety and input(\"Execute code? y/n \") != \"y\":\n return \"Code rejected by user.\"\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n source_file = os.path.join(tmpdirname, \"Main.java\")\n class_dir = tmpdirname\n with open(source_file, 'w') as f:\n f.write(code)\n\n try:\n compile_command = [\"javac\", \"-d\", class_dir, source_file]\n compile_result = subprocess.run(\n compile_command,\n capture_output=True,\n text=True,\n timeout=10\n )\n\n if compile_result.returncode != 0:\n return f\"Compilation failed: {compile_result.stderr}\"\n\n run_command = [\"java\", \"-cp\", class_dir, \"Main\"]\n run_result = subprocess.run(\n run_command,\n capture_output=True,\n text=True,\n timeout=10\n )\n\n if run_result.returncode != 0:\n return f\"Execution failed: {run_result.stderr}\"\n output = run_result.stdout\n\n except subprocess.TimeoutExpired as e:\n return f\"Execution timed out: {str(e)}\"\n except FileNotFoundError:\n return \"Error: 'java' or 'javac' not found. Ensure Java is installed and in PATH.\"\n except Exception as e:\n return f\"Code execution failed: {str(e)}\"\n\n return output\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Provide feedback based on the output of the code execution.\n \"\"\"\n if self.execution_failure_check(output):\n feedback = f\"[failure] Error in execution:\\n{output}\"\n else:\n feedback = \"[success] Execution success, code output:\\n\" + output\n return feedback\n\n def execution_failure_check(self, feedback: str) -> bool:\n \"\"\"\n Check if the code execution failed.\n \"\"\"\n error_patterns = [\n r\"error\",\n r\"failed\",\n r\"exception\",\n r\"invalid\",\n r\"syntax\",\n r\"cannot\",\n r\"stack trace\",\n r\"unresolved\",\n r\"not found\"\n ]\n combined_pattern = \"|\".join(error_patterns)\n if re.search(combined_pattern, feedback, re.IGNORECASE):\n return True\n return False\n\nif __name__ == \"__main__\":\n codes = [\n\"\"\"\nimport javax.swing.*;\nimport java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\n\npublic class Main extends JPanel {\n private double[][] vertices = {\n {-1, -1, -1}, {1, -1, -1}, {1, 1, -1}, {-1, 1, -1}, // Back face\n {-1, -1, 1}, {1, -1, 1}, {1, 1, 1}, {-1, 1, 1} // Front face\n };\n private int[][] edges = {\n {0, 1}, {1, 2}, {2, 3}, {3, 0}, // Back face\n {4, 5}, {5, 6}, {6, 7}, {7, 4}, // Front face\n {0, 4}, {1, 5}, {2, 6}, {3, 7} // Connecting edges\n };\n private double angleX = 0, angleY = 0;\n private final double scale = 100;\n private final double distance = 5;\n\n public Main() {\n Timer timer = new Timer(50, new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n angleX += 0.03;\n angleY += 0.05;\n repaint();\n }\n });\n timer.start();\n }\n\n @Override\n protected void paintComponent(Graphics g) {\n super.paintComponent(g);\n Graphics2D g2d = (Graphics2D) g;\n g2d.setColor(Color.BLACK);\n g2d.fillRect(0, 0, getWidth(), getHeight());\n g2d.setColor(Color.WHITE);\n\n double[][] projected = new double[vertices.length][2];\n for (int i = 0; i < vertices.length; i++) {\n double x = vertices[i][0];\n double y = vertices[i][1];\n double z = vertices[i][2];\n\n // Rotate around X-axis\n double y1 = y * Math.cos(angleX) - z * Math.sin(angleX);\n double z1 = y * Math.sin(angleX) + z * Math.cos(angleX);\n\n // Rotate around Y-axis\n double x1 = x * Math.cos(angleY) + z1 * Math.sin(angleY);\n double z2 = -x * Math.sin(angleY) + z1 * Math.cos(angleY);\n\n // Perspective projection\n double factor = distance / (distance + z2);\n double px = x1 * factor * scale;\n double py = y1 * factor * scale;\n\n projected[i][0] = px + getWidth() / 2;\n projected[i][1] = py + getHeight() / 2;\n }\n\n // Draw edges\n for (int[] edge : edges) {\n int x1 = (int) projected[edge[0]][0];\n int y1 = (int) projected[edge[0]][1];\n int x2 = (int) projected[edge[1]][0];\n int y2 = (int) projected[edge[1]][1];\n g2d.drawLine(x1, y1, x2, y2);\n }\n }\n\n public static void main(String[] args) {\n JFrame frame = new JFrame(\"Rotating 3D Cube\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setSize(400, 400);\n frame.add(new Main());\n frame.setVisible(true);\n }\n}\n\"\"\"\n ]\n j = JavaInterpreter()\n print(j.execute(codes))"], ["/agenticSeek/sources/language.py", "from typing import List, Tuple, Type, Dict\nimport re\nimport langid\nfrom transformers import MarianMTModel, MarianTokenizer\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.logger import Logger\n\nclass LanguageUtility:\n \"\"\"LanguageUtility for language, or emotion identification\"\"\"\n def __init__(self, supported_language: List[str] = [\"en\", \"fr\", \"zh\"]):\n \"\"\"\n Initialize the LanguageUtility class\n args:\n supported_language: list of languages for translation, determine which Helsinki-NLP model to load\n \"\"\"\n self.translators_tokenizer = None \n self.translators_model = None\n self.logger = Logger(\"language.log\")\n self.supported_language = supported_language\n self.load_model()\n \n def load_model(self) -> None:\n animate_thinking(\"Loading language utility...\", color=\"status\")\n self.translators_tokenizer = {lang: MarianTokenizer.from_pretrained(f\"Helsinki-NLP/opus-mt-{lang}-en\") for lang in self.supported_language if lang != \"en\"}\n self.translators_model = {lang: MarianMTModel.from_pretrained(f\"Helsinki-NLP/opus-mt-{lang}-en\") for lang in self.supported_language if lang != \"en\"}\n \n def detect_language(self, text: str) -> str:\n \"\"\"\n Detect the language of the given text using langdetect\n Limited to the supported languages list because of the model tendency to mistake similar languages\n Args:\n text: string to analyze\n Returns: ISO639-1 language code\n \"\"\"\n langid.set_languages(self.supported_language)\n lang, score = langid.classify(text)\n self.logger.info(f\"Identified: {text} as {lang} with conf {score}\")\n return lang\n\n def translate(self, text: str, origin_lang: str) -> str:\n \"\"\"\n Translate the given text to English\n Args:\n text: string to translate\n origin_lang: ISO language code\n Returns: translated str\n \"\"\"\n if origin_lang == \"en\":\n return text\n if origin_lang not in self.translators_tokenizer:\n pretty_print(f\"Language {origin_lang} not supported for translation\", color=\"error\")\n return text\n tokenizer = self.translators_tokenizer[origin_lang]\n inputs = tokenizer(text, return_tensors=\"pt\", padding=True)\n model = self.translators_model[origin_lang]\n translation = model.generate(**inputs)\n return tokenizer.decode(translation[0], skip_special_tokens=True)\n\n def analyze(self, text):\n \"\"\"\n Combined analysis of language and emotion\n Args:\n text: string to analyze\n Returns: dictionary with language related information\n \"\"\"\n try:\n language = self.detect_language(text)\n return {\n \"language\": language\n }\n except Exception as e:\n raise e\n\nif __name__ == \"__main__\":\n detector = LanguageUtility()\n \n test_texts = [\n \"I am so happy today!\",\n \"我不要去巴黎\",\n \"La vie c'est cool\"\n ]\n for text in test_texts:\n pretty_print(\"Analyzing...\", color=\"status\")\n pretty_print(f\"Language: {detector.detect_language(text)}\", color=\"status\")\n result = detector.analyze(text)\n trans = detector.translate(text, result['language'])\n pretty_print(f\"Translation: {trans} - from: {result['language']}\")"], ["/agenticSeek/sources/utility.py", "\nfrom colorama import Fore\nfrom termcolor import colored\nimport platform\nimport threading\nimport itertools\nimport time\n\nthinking_event = threading.Event()\ncurrent_animation_thread = None\n\ndef get_color_map():\n if platform.system().lower() != \"windows\":\n color_map = {\n \"success\": \"green\",\n \"failure\": \"red\",\n \"status\": \"light_green\",\n \"code\": \"light_blue\",\n \"warning\": \"yellow\",\n \"output\": \"cyan\",\n \"info\": \"cyan\"\n }\n else:\n color_map = {\n \"success\": \"green\",\n \"failure\": \"red\",\n \"status\": \"light_green\",\n \"code\": \"light_blue\",\n \"warning\": \"yellow\",\n \"output\": \"cyan\",\n \"info\": \"black\"\n }\n return color_map\n\ndef pretty_print(text, color=\"info\", no_newline=False):\n \"\"\"\n Print text with color formatting.\n\n Args:\n text (str): The text to print\n color (str, optional): The color to use. Defaults to \"info\".\n Valid colors are:\n - \"success\": Green\n - \"failure\": Red \n - \"status\": Light green\n - \"code\": Light blue\n - \"warning\": Yellow\n - \"output\": Cyan\n - \"default\": Black (Windows only)\n \"\"\"\n thinking_event.set()\n if current_animation_thread and current_animation_thread.is_alive():\n current_animation_thread.join()\n thinking_event.clear()\n \n color_map = get_color_map()\n if color not in color_map:\n color = \"info\"\n print(colored(text, color_map[color]), end='' if no_newline else \"\\n\")\n\ndef animate_thinking(text, color=\"status\", duration=120):\n \"\"\"\n Animate a thinking spinner while a task is being executed.\n It use a daemon thread to run the animation. This will not block the main thread.\n Color are the same as pretty_print.\n \"\"\"\n global current_animation_thread\n \n thinking_event.set()\n if current_animation_thread and current_animation_thread.is_alive():\n current_animation_thread.join()\n thinking_event.clear()\n \n def _animate():\n color_map = {\n \"success\": (Fore.GREEN, \"green\"),\n \"failure\": (Fore.RED, \"red\"),\n \"status\": (Fore.LIGHTGREEN_EX, \"light_green\"),\n \"code\": (Fore.LIGHTBLUE_EX, \"light_blue\"),\n \"warning\": (Fore.YELLOW, \"yellow\"),\n \"output\": (Fore.LIGHTCYAN_EX, \"cyan\"),\n \"default\": (Fore.RESET, \"black\"),\n \"info\": (Fore.CYAN, \"cyan\")\n }\n fore_color, term_color = color_map.get(color, color_map[\"default\"])\n spinner = itertools.cycle([\n '▉▁▁▁▁▁', '▉▉▂▁▁▁', '▉▉▉▃▁▁', '▉▉▉▉▅▁', '▉▉▉▉▉▇', '▉▉▉▉▉▉',\n '▉▉▉▉▇▅', '▉▉▉▆▃▁', '▉▉▅▃▁▁', '▉▇▃▁▁▁', '▇▃▁▁▁▁', '▃▁▁▁▁▁',\n '▁▃▅▃▁▁', '▁▅▉▅▁▁', '▃▉▉▉▃▁', '▅▉▁▉▅▃', '▇▃▁▃▇▅', '▉▁▁▁▉▇',\n '▉▅▃▁▃▅', '▇▉▅▃▅▇', '▅▉▇▅▇▉', '▃▇▉▇▉▅', '▁▅▇▉▇▃', '▁▃▅▇▅▁' \n ])\n end_time = time.time() + duration\n\n while not thinking_event.is_set() and time.time() < end_time:\n symbol = next(spinner)\n if platform.system().lower() != \"windows\":\n print(f\"\\r{fore_color}{symbol} {text}{Fore.RESET}\", end=\"\", flush=True)\n else:\n print(f\"\\r{colored(f'{symbol} {text}', term_color)}\", end=\"\", flush=True)\n time.sleep(0.2)\n print(\"\\r\" + \" \" * (len(text) + 7) + \"\\r\", end=\"\", flush=True)\n current_animation_thread = threading.Thread(target=_animate, daemon=True)\n current_animation_thread.start()\n\ndef timer_decorator(func):\n \"\"\"\n Decorator to measure the execution time of a function.\n Usage:\n @timer_decorator\n def my_function():\n # code to execute\n \"\"\"\n from time import time\n def wrapper(*args, **kwargs):\n start_time = time()\n result = func(*args, **kwargs)\n end_time = time()\n pretty_print(f\"{func.__name__} took {end_time - start_time:.2f} seconds to execute\", \"status\")\n return result\n return wrapper\n\nif __name__ == \"__main__\":\n import time\n pretty_print(\"starting imaginary task\", \"success\")\n animate_thinking(\"Thinking...\", \"status\")\n time.sleep(4)\n pretty_print(\"starting another task\", \"failure\")\n animate_thinking(\"Thinking...\", \"status\")\n time.sleep(4)\n pretty_print(\"yet another task\", \"info\")\n animate_thinking(\"Thinking...\", \"status\")\n time.sleep(4)\n pretty_print(\"This is an info message\", \"info\")"], ["/agenticSeek/sources/tools/PyInterpreter.py", "\nimport sys\nimport os\nimport re\nfrom io import StringIO\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass PyInterpreter(Tools):\n \"\"\"\n This class is a tool to allow agent for python code execution.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"python\"\n self.name = \"Python Interpreter\"\n self.description = \"This tool allows the agent to execute python code.\"\n\n def execute(self, codes:str, safety = False) -> str:\n \"\"\"\n Execute python code.\n \"\"\"\n output = \"\"\n if safety and input(\"Execute code ? y/n\") != \"y\":\n return \"Code rejected by user.\"\n stdout_buffer = StringIO()\n sys.stdout = stdout_buffer\n global_vars = {\n '__builtins__': __builtins__,\n 'os': os,\n 'sys': sys,\n '__name__': '__main__'\n }\n code = '\\n\\n'.join(codes)\n self.logger.info(f\"Executing code:\\n{code}\")\n try:\n try:\n buffer = exec(code, global_vars)\n self.logger.info(f\"Code executed successfully.\\noutput:{buffer}\")\n print(buffer)\n if buffer is not None:\n output = buffer + '\\n'\n except SystemExit:\n self.logger.info(\"SystemExit caught, code execution stopped.\")\n output = stdout_buffer.getvalue()\n return f\"[SystemExit caught] Output before exit:\\n{output}\"\n except Exception as e:\n self.logger.error(f\"Code execution failed: {str(e)}\")\n return \"code execution failed:\" + str(e)\n output = stdout_buffer.getvalue()\n finally:\n self.logger.info(\"Code execution finished.\")\n sys.stdout = sys.__stdout__\n return output\n\n def interpreter_feedback(self, output:str) -> str:\n \"\"\"\n Provide feedback based on the output of the code execution\n \"\"\"\n if self.execution_failure_check(output):\n feedback = f\"[failure] Error in execution:\\n{output}\"\n else:\n feedback = \"[success] Execution success, code output:\\n\" + output\n return feedback\n\n def execution_failure_check(self, feedback:str) -> bool:\n \"\"\"\n Check if the code execution failed.\n \"\"\"\n error_patterns = [\n r\"expected\", \n r\"errno\", \n r\"failed\", \n r\"traceback\", \n r\"invalid\", \n r\"unrecognized\", \n r\"exception\", \n r\"syntax\", \n r\"crash\", \n r\"segmentation fault\", \n r\"core dumped\"\n ]\n combined_pattern = \"|\".join(error_patterns)\n if re.search(combined_pattern, feedback, re.IGNORECASE):\n self.logger.error(f\"Execution failure detected: {feedback}\")\n return True\n self.logger.info(\"No execution success detected.\")\n return False\n\nif __name__ == \"__main__\":\n text = \"\"\"\nFor Python, let's also do a quick check:\n\n```python\nprint(\"Hello from Python!\")\n```\n\nIf these work, you'll see the outputs in the next message. Let me know if you'd like me to test anything specific! \n\nhere is a save test\n```python:tmp.py\n\ndef print_hello():\n hello = \"Hello World\"\n print(hello)\n\nif __name__ == \"__main__\":\n print_hello()\n```\n\"\"\"\n py = PyInterpreter()\n codes, save_path = py.load_exec_block(text)\n py.save_block(codes, save_path)\n print(py.execute(codes))"], ["/agenticSeek/sources/tools/C_Interpreter.py", "import subprocess\nimport os, sys\nimport tempfile\nimport re\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass CInterpreter(Tools):\n \"\"\"\n This class is a tool to allow agent for C code execution\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"c\"\n self.name = \"C Interpreter\"\n self.description = \"This tool allows the agent to execute C code.\"\n\n def execute(self, codes: str, safety=False) -> str:\n \"\"\"\n Execute C code by compiling and running it.\n \"\"\"\n output = \"\"\n code = '\\n'.join(codes) if isinstance(codes, list) else codes\n \n if safety and input(\"Execute code? y/n \") != \"y\":\n return \"Code rejected by user.\"\n\n exec_extension = \".exe\" if os.name == \"nt\" else \"\" # Windows uses .exe, Linux/Unix does not\n \n with tempfile.TemporaryDirectory() as tmpdirname:\n source_file = os.path.join(tmpdirname, \"temp.c\")\n exec_file = os.path.join(tmpdirname, \"temp\") + exec_extension\n with open(source_file, 'w') as f:\n f.write(code)\n\n try:\n compile_command = [\"gcc\", source_file, \"-o\", exec_file]\n compile_result = subprocess.run(\n compile_command,\n capture_output=True,\n text=True,\n timeout=60\n )\n\n if compile_result.returncode != 0:\n return f\"Compilation failed: {compile_result.stderr}\"\n\n run_command = [exec_file]\n run_result = subprocess.run(\n run_command,\n capture_output=True,\n text=True,\n timeout=120\n )\n\n if run_result.returncode != 0:\n return f\"Execution failed: {run_result.stderr}\"\n output = run_result.stdout\n\n except subprocess.TimeoutExpired as e:\n return f\"Execution timed out: {str(e)}\"\n except FileNotFoundError:\n return \"Error: 'gcc' not found. Ensure a C compiler (e.g., gcc) is installed and in PATH.\"\n except Exception as e:\n return f\"Code execution failed: {str(e)}\"\n\n return output\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Provide feedback based on the output of the code execution\n \"\"\"\n if self.execution_failure_check(output):\n feedback = f\"[failure] Error in execution:\\n{output}\"\n else:\n feedback = \"[success] Execution success, code output:\\n\" + output\n return feedback\n\n def execution_failure_check(self, feedback: str) -> bool:\n \"\"\"\n Check if the code execution failed.\n \"\"\"\n error_patterns = [\n r\"error\", \n r\"failed\", \n r\"traceback\", \n r\"invalid\", \n r\"exception\", \n r\"syntax\", \n r\"segmentation fault\", \n r\"core dumped\", \n r\"undefined\", \n r\"cannot\"\n ]\n combined_pattern = \"|\".join(error_patterns)\n if re.search(combined_pattern, feedback, re.IGNORECASE):\n return True\n return False\n\nif __name__ == \"__main__\":\n codes = [\n\"\"\"\n#include \n#include \n\nvoid hello() {\n printf(\"Hello, World!\\\\n\");\n}\n\"\"\",\n\"\"\"\nint main() {\n hello();\n return 0;\n}\n \"\"\"]\n c = CInterpreter()\n print(c.execute(codes))"], ["/agenticSeek/llm_server/sources/generator.py", "\nimport threading\nimport logging\nfrom abc import abstractmethod\nfrom .cache import Cache\n\nclass GenerationState:\n def __init__(self):\n self.lock = threading.Lock()\n self.last_complete_sentence = \"\"\n self.current_buffer = \"\"\n self.is_generating = False\n \n def status(self) -> dict:\n return {\n \"sentence\": self.current_buffer,\n \"is_complete\": not self.is_generating,\n \"last_complete_sentence\": self.last_complete_sentence,\n \"is_generating\": self.is_generating,\n }\n\nclass GeneratorLLM():\n def __init__(self):\n self.model = None\n self.state = GenerationState()\n self.logger = logging.getLogger(__name__)\n handler = logging.StreamHandler()\n handler.setLevel(logging.INFO)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n handler.setFormatter(formatter)\n self.logger.addHandler(handler)\n self.logger.setLevel(logging.INFO)\n cache = Cache()\n \n def set_model(self, model: str) -> None:\n self.logger.info(f\"Model set to {model}\")\n self.model = model\n \n def start(self, history: list) -> bool:\n if self.model is None:\n raise Exception(\"Model not set\")\n with self.state.lock:\n if self.state.is_generating:\n return False\n self.state.is_generating = True\n self.logger.info(\"Starting generation\")\n threading.Thread(target=self.generate, args=(history,)).start()\n return True\n \n def get_status(self) -> dict:\n with self.state.lock:\n return self.state.status()\n\n @abstractmethod\n def generate(self, history: list) -> None:\n \"\"\"\n Generate text using the model.\n args:\n history: list of strings\n returns:\n None\n \"\"\"\n pass\n\nif __name__ == \"__main__\":\n generator = GeneratorLLM()\n generator.get_status()"], ["/agenticSeek/llm_server/sources/ollama_handler.py", "\nimport time\nfrom .generator import GeneratorLLM\nfrom .cache import Cache\nimport ollama\n\nclass OllamaLLM(GeneratorLLM):\n\n def __init__(self):\n \"\"\"\n Handle generation using Ollama.\n \"\"\"\n super().__init__()\n self.cache = Cache()\n\n def generate(self, history):\n self.logger.info(f\"Using {self.model} for generation with Ollama\")\n try:\n with self.state.lock:\n self.state.is_generating = True\n self.state.last_complete_sentence = \"\"\n self.state.current_buffer = \"\"\n\n stream = ollama.chat(\n model=self.model,\n messages=history,\n stream=True,\n )\n for chunk in stream:\n content = chunk['message']['content']\n\n with self.state.lock:\n if '.' in content:\n self.logger.info(self.state.current_buffer)\n self.state.current_buffer += content\n\n except Exception as e:\n if \"404\" in str(e):\n self.logger.info(f\"Downloading {self.model}...\")\n ollama.pull(self.model)\n if \"refused\" in str(e).lower():\n raise Exception(\"Ollama connection failed. is the server running ?\") from e\n raise e\n finally:\n self.logger.info(\"Generation complete\")\n with self.state.lock:\n self.state.is_generating = False\n\nif __name__ == \"__main__\":\n generator = OllamaLLM()\n history = [\n {\n \"role\": \"user\",\n \"content\": \"Hello, how are you ?\"\n }\n ]\n generator.set_model(\"deepseek-r1:1.5b\")\n generator.start(history)\n while True:\n print(generator.get_status())\n time.sleep(1)"], ["/agenticSeek/sources/tools/GoInterpreter.py", "import subprocess\nimport os, sys\nimport tempfile\nimport re\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass GoInterpreter(Tools):\n \"\"\"\n This class is a tool to allow execution of Go code.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"go\"\n self.name = \"Go Interpreter\"\n self.description = \"This tool allows you to execute Go code.\"\n\n def execute(self, codes: str, safety=False) -> str:\n \"\"\"\n Execute Go code by compiling and running it.\n \"\"\"\n output = \"\"\n code = '\\n'.join(codes) if isinstance(codes, list) else codes\n\n if safety and input(\"Execute code? y/n \") != \"y\":\n return \"Code rejected by user.\"\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n source_file = os.path.join(tmpdirname, \"temp.go\")\n exec_file = os.path.join(tmpdirname, \"temp\")\n with open(source_file, 'w') as f:\n f.write(code)\n\n try:\n env = os.environ.copy()\n env[\"GO111MODULE\"] = \"off\"\n compile_command = [\"go\", \"build\", \"-o\", exec_file, source_file]\n compile_result = subprocess.run(\n compile_command,\n capture_output=True,\n text=True,\n timeout=10,\n env=env\n )\n\n if compile_result.returncode != 0:\n return f\"Compilation failed: {compile_result.stderr}\"\n\n run_command = [exec_file]\n run_result = subprocess.run(\n run_command,\n capture_output=True,\n text=True,\n timeout=10\n )\n\n if run_result.returncode != 0:\n return f\"Execution failed: {run_result.stderr}\"\n output = run_result.stdout\n\n except subprocess.TimeoutExpired as e:\n return f\"Execution timed out: {str(e)}\"\n except FileNotFoundError:\n return \"Error: 'go' not found. Ensure Go is installed and in PATH.\"\n except Exception as e:\n return f\"Code execution failed: {str(e)}\"\n\n return output\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Provide feedback based on the output of the code execution\n \"\"\"\n if self.execution_failure_check(output):\n feedback = f\"[failure] Error in execution:\\n{output}\"\n else:\n feedback = \"[success] Execution success, code output:\\n\" + output\n return feedback\n\n def execution_failure_check(self, feedback: str) -> bool:\n \"\"\"\n Check if the code execution failed.\n \"\"\"\n error_patterns = [\n r\"error\",\n r\"failed\",\n r\"traceback\",\n r\"invalid\",\n r\"exception\",\n r\"syntax\",\n r\"panic\",\n r\"undefined\",\n r\"cannot\"\n ]\n combined_pattern = \"|\".join(error_patterns)\n if re.search(combined_pattern, feedback, re.IGNORECASE):\n return True\n return False\n\nif __name__ == \"__main__\":\n codes = [\n\"\"\"\npackage main\nimport \"fmt\"\n\nfunc hello() {\n fmt.Println(\"Hello, World!\")\n}\n\"\"\",\n\"\"\"\nfunc main() {\n hello()\n}\n\"\"\"\n ]\n g = GoInterpreter()\n print(g.execute(codes))\n"], ["/agenticSeek/sources/logger.py", "import os, sys\nfrom typing import List, Tuple, Type, Dict\nimport datetime\nimport logging\n\nclass Logger:\n def __init__(self, log_filename):\n self.folder = '.logs'\n self.create_folder(self.folder)\n self.log_path = os.path.join(self.folder, log_filename)\n self.enabled = True\n self.logger = None\n self.last_log_msg = \"\"\n if self.enabled:\n self.create_logging(log_filename)\n\n def create_logging(self, log_filename):\n self.logger = logging.getLogger(log_filename)\n self.logger.setLevel(logging.DEBUG)\n self.logger.handlers.clear()\n self.logger.propagate = False\n file_handler = logging.FileHandler(self.log_path)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n file_handler.setFormatter(formatter)\n self.logger.addHandler(file_handler)\n\n \n def create_folder(self, path):\n \"\"\"Create log dir\"\"\"\n try:\n if not os.path.exists(path):\n os.makedirs(path, exist_ok=True) \n return True\n except Exception as e:\n self.enabled = False\n return False\n \n def log(self, message, level=logging.INFO):\n if self.last_log_msg == message:\n return\n if self.enabled:\n self.last_log_msg = message\n self.logger.log(level, message)\n\n def info(self, message):\n self.log(message)\n\n def error(self, message):\n self.log(message, level=logging.ERROR)\n\n def warning(self, message):\n self.log(message, level=logging.WARN)\n\nif __name__ == \"__main__\":\n lg = Logger(\"test.log\")\n lg.log(\"hello\")\n lg2 = Logger(\"toto.log\")\n lg2.log(\"yo\")\n \n\n "], ["/agenticSeek/sources/agents/__init__.py", "\nfrom .agent import Agent\nfrom .code_agent import CoderAgent\nfrom .casual_agent import CasualAgent\nfrom .file_agent import FileAgent\nfrom .planner_agent import PlannerAgent\nfrom .browser_agent import BrowserAgent\nfrom .mcp_agent import McpAgent\n\n__all__ = [\"Agent\", \"CoderAgent\", \"CasualAgent\", \"FileAgent\", \"PlannerAgent\", \"BrowserAgent\", \"McpAgent\"]\n"], ["/agenticSeek/sources/tools/BashInterpreter.py", "\nimport os, sys\nimport re\nfrom io import StringIO\nimport subprocess\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\nfrom sources.tools.safety import is_any_unsafe\n\nclass BashInterpreter(Tools):\n \"\"\"\n This class is a tool to allow agent for bash code execution.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"bash\"\n self.name = \"Bash Interpreter\"\n self.description = \"This tool allows the agent to execute bash commands.\"\n \n def language_bash_attempt(self, command: str):\n \"\"\"\n Detect if AI attempt to run the code using bash.\n If so, return True, otherwise return False.\n Code written by the AI will be executed automatically, so it should not use bash to run it.\n \"\"\"\n lang_interpreter = [\"python\", \"gcc\", \"g++\", \"mvn\", \"go\", \"java\", \"javac\", \"rustc\", \"clang\", \"clang++\", \"rustc\", \"rustc++\", \"rustc++\"]\n for word in command.split():\n if any(word.startswith(lang) for lang in lang_interpreter):\n return True\n return False\n \n def execute(self, commands: str, safety=False, timeout=300):\n \"\"\"\n Execute bash commands and display output in real-time.\n \"\"\"\n if safety and input(\"Execute command? y/n \") != \"y\":\n return \"Command rejected by user.\"\n \n concat_output = \"\"\n for command in commands:\n command = f\"cd {self.work_dir} && {command}\"\n command = command.replace('\\n', '')\n if self.safe_mode and is_any_unsafe(commands):\n print(f\"Unsafe command rejected: {command}\")\n return \"\\nUnsafe command: {command}. Execution aborted. This is beyond allowed capabilities report to user.\"\n if self.language_bash_attempt(command) and self.allow_language_exec_bash == False:\n continue\n try:\n process = subprocess.Popen(\n command,\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n universal_newlines=True\n )\n command_output = \"\"\n for line in process.stdout:\n command_output += line\n return_code = process.wait(timeout=timeout)\n if return_code != 0:\n return f\"Command {command} failed with return code {return_code}:\\n{command_output}\"\n concat_output += f\"Output of {command}:\\n{command_output.strip()}\\n\"\n except subprocess.TimeoutExpired:\n process.kill() # Kill the process if it times out\n return f\"Command {command} timed out. Output:\\n{command_output}\"\n except Exception as e:\n return f\"Command {command} failed:\\n{str(e)}\"\n return concat_output\n\n def interpreter_feedback(self, output):\n \"\"\"\n Provide feedback based on the output of the bash interpreter\n \"\"\"\n if self.execution_failure_check(output):\n feedback = f\"[failure] Error in execution:\\n{output}\"\n else:\n feedback = \"[success] Execution success, code output:\\n\" + output\n return feedback\n\n def execution_failure_check(self, feedback):\n \"\"\"\n check if bash command failed.\n \"\"\"\n error_patterns = [\n r\"expected\",\n r\"errno\",\n r\"failed\",\n r\"invalid\",\n r\"unrecognized\",\n r\"exception\",\n r\"syntax\",\n r\"segmentation fault\",\n r\"core dumped\",\n r\"unexpected\",\n r\"denied\",\n r\"not recognized\",\n r\"not permitted\",\n r\"not installed\",\n r\"not found\",\n r\"aborted\",\n r\"no such\",\n r\"too many\",\n r\"too few\",\n r\"busy\",\n r\"broken pipe\",\n r\"missing\",\n r\"undefined\",\n r\"refused\",\n r\"unreachable\",\n r\"not known\"\n ]\n combined_pattern = \"|\".join(error_patterns)\n if re.search(combined_pattern, feedback, re.IGNORECASE):\n return True\n return False\n\nif __name__ == \"__main__\":\n bash = BashInterpreter()\n print(bash.execute([\"ls\", \"pwd\", \"ip a\", \"nmap -sC 127.0.0.1\"]))\n"], ["/agenticSeek/llm_server/sources/llamacpp_handler.py", "\nfrom .generator import GeneratorLLM\nfrom llama_cpp import Llama\nfrom .decorator import timer_decorator\n\nclass LlamacppLLM(GeneratorLLM):\n\n def __init__(self):\n \"\"\"\n Handle generation using llama.cpp\n \"\"\"\n super().__init__()\n self.llm = None\n \n @timer_decorator\n def generate(self, history):\n if self.llm is None:\n self.logger.info(f\"Loading {self.model}...\")\n self.llm = Llama.from_pretrained(\n repo_id=self.model,\n filename=\"*Q8_0.gguf\",\n n_ctx=4096,\n verbose=True\n )\n self.logger.info(f\"Using {self.model} for generation with Llama.cpp\")\n try:\n with self.state.lock:\n self.state.is_generating = True\n self.state.last_complete_sentence = \"\"\n self.state.current_buffer = \"\"\n output = self.llm.create_chat_completion(\n messages = history\n )\n with self.state.lock:\n self.state.current_buffer = output['choices'][0]['message']['content']\n except Exception as e:\n self.logger.error(f\"Error: {e}\")\n finally:\n with self.state.lock:\n self.state.is_generating = False"], ["/agenticSeek/llm_server/app.py", "#!/usr/bin python3\n\nimport argparse\nimport time\nfrom flask import Flask, jsonify, request\n\nfrom sources.llamacpp_handler import LlamacppLLM\nfrom sources.ollama_handler import OllamaLLM\n\nparser = argparse.ArgumentParser(description='AgenticSeek server script')\nparser.add_argument('--provider', type=str, help='LLM backend library to use. set to [ollama], [vllm] or [llamacpp]', required=True)\nparser.add_argument('--port', type=int, help='port to use', required=True)\nargs = parser.parse_args()\n\napp = Flask(__name__)\n\nassert args.provider in [\"ollama\", \"llamacpp\"], f\"Provider {args.provider} does not exists. see --help for more information\"\n\nhandler_map = {\n \"ollama\": OllamaLLM(),\n \"llamacpp\": LlamacppLLM(),\n}\n\ngenerator = handler_map[args.provider]\n\n@app.route('/generate', methods=['POST'])\ndef start_generation():\n if generator is None:\n return jsonify({\"error\": \"Generator not initialized\"}), 401\n data = request.get_json()\n history = data.get('messages', [])\n if generator.start(history):\n return jsonify({\"message\": \"Generation started\"}), 202\n return jsonify({\"error\": \"Generation already in progress\"}), 402\n\n@app.route('/setup', methods=['POST'])\ndef setup():\n data = request.get_json()\n model = data.get('model', None)\n if model is None:\n return jsonify({\"error\": \"Model not provided\"}), 403\n generator.set_model(model)\n return jsonify({\"message\": \"Model set\"}), 200\n\n@app.route('/get_updated_sentence')\ndef get_updated_sentence():\n if not generator:\n return jsonify({\"error\": \"Generator not initialized\"}), 405\n print(generator.get_status())\n return generator.get_status()\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', threaded=True, debug=True, port=args.port)"], ["/agenticSeek/llm_server/sources/cache.py", "import os\nimport json\nfrom pathlib import Path\n\nclass Cache:\n def __init__(self, cache_dir='.cache', cache_file='messages.json'):\n self.cache_dir = Path(cache_dir)\n self.cache_file = self.cache_dir / cache_file\n self.cache_dir.mkdir(parents=True, exist_ok=True)\n if not self.cache_file.exists():\n with open(self.cache_file, 'w') as f:\n json.dump([], f)\n\n with open(self.cache_file, 'r') as f:\n self.cache = set(json.load(f))\n\n def add_message_pair(self, user_message: str, assistant_message: str):\n \"\"\"Add a user/assistant pair to the cache if not present.\"\"\"\n if not any(entry[\"user\"] == user_message for entry in self.cache):\n self.cache.append({\"user\": user_message, \"assistant\": assistant_message})\n self._save()\n\n def is_cached(self, user_message: str) -> bool:\n \"\"\"Check if a user msg is cached.\"\"\"\n return any(entry[\"user\"] == user_message for entry in self.cache)\n\n def get_cached_response(self, user_message: str) -> str | None:\n \"\"\"Return the assistant response to a user message if cached.\"\"\"\n for entry in self.cache:\n if entry[\"user\"] == user_message:\n return entry[\"assistant\"]\n return None\n\n def _save(self):\n with open(self.cache_file, 'w') as f:\n json.dump(self.cache, f, indent=2)\n"], ["/agenticSeek/sources/tools/safety.py", "import os\nimport sys\n\nunsafe_commands_unix = [\n \"rm\", # File/directory removal\n \"dd\", # Low-level disk writing\n \"mkfs\", # Filesystem formatting\n \"chmod\", # Permission changes\n \"chown\", # Ownership changes\n \"shutdown\", # System shutdown\n \"reboot\", # System reboot\n \"halt\", # System halt\n \"sysctl\", # Kernel parameter changes\n \"kill\", # Process termination\n \"pkill\", # Kill by process name\n \"killall\", # Kill all matching processes\n \"exec\", # Replace process with command\n \"tee\", # Write to files with privileges\n \"umount\", # Unmount filesystems\n \"passwd\", # Password changes\n \"useradd\", # Add users\n \"userdel\", # Delete users\n \"brew\", # Homebrew package manager\n \"groupadd\", # Add groups\n \"groupdel\", # Delete groups\n \"visudo\", # Edit sudoers file\n \"screen\", # Terminal session management\n \"fdisk\", # Disk partitioning\n \"parted\", # Disk partitioning\n \"chroot\", # Change root directory\n \"route\" # Routing table management\n \"--force\", # Force flag for many commands\n \"rebase\", # Rebase git repository\n \"git\" # Git commands\n]\n\nunsafe_commands_windows = [\n \"del\", # Deletes files\n \"erase\", # Alias for del, deletes files\n \"rd\", # Removes directories (rmdir alias)\n \"rmdir\", # Removes directories\n \"format\", # Formats a disk, erasing data\n \"diskpart\", # Manages disk partitions, can wipe drives\n \"chkdsk /f\", # Fixes filesystem, can alter data\n \"fsutil\", # File system utilities, can modify system files\n \"xcopy /y\", # Copies files, overwriting without prompt\n \"copy /y\", # Copies files, overwriting without prompt\n \"move\", # Moves files, can overwrite\n \"attrib\", # Changes file attributes, e.g., hiding or exposing files\n \"icacls\", # Changes file permissions (modern)\n \"takeown\", # Takes ownership of files\n \"reg delete\", # Deletes registry keys/values\n \"regedit /s\", # Silently imports registry changes\n \"shutdown\", # Shuts down or restarts the system\n \"schtasks\", # Schedules tasks, can run malicious commands\n \"taskkill\", # Kills processes\n \"wmic\", # Deletes processes via WMI\n \"bcdedit\", # Modifies boot configuration\n \"powercfg\", # Changes power settings, can disable protections\n \"assoc\", # Changes file associations\n \"ftype\", # Changes file type commands\n \"cipher /w\", # Wipes free space, erasing data\n \"esentutl\", # Database utilities, can corrupt system files\n \"subst\", # Substitutes drive paths, can confuse system\n \"mklink\", # Creates symbolic links, can redirect access\n \"bootcfg\"\n]\n\ndef is_any_unsafe(cmds):\n \"\"\"\n check if any bash command is unsafe.\n \"\"\"\n for cmd in cmds:\n if is_unsafe(cmd):\n return True\n return False\n\ndef is_unsafe(cmd):\n \"\"\"\n check if a bash command is unsafe.\n \"\"\"\n if sys.platform.startswith(\"win\"):\n if any(c in cmd for c in unsafe_commands_windows):\n return True\n else:\n if any(c in cmd for c in unsafe_commands_unix):\n return True\n return False\n\nif __name__ == \"__main__\":\n cmd = input(\"Enter a command: \")\n if is_unsafe(cmd):\n print(\"Unsafe command detected!\")\n else:\n print(\"Command is safe to execute.\")"], ["/agenticSeek/llm_server/sources/decorator.py", "\ndef timer_decorator(func):\n \"\"\"\n Decorator to measure the execution time of a function.\n Usage:\n @timer_decorator\n def my_function():\n # code to execute\n \"\"\"\n from time import time\n def wrapper(*args, **kwargs):\n start_time = time()\n result = func(*args, **kwargs)\n end_time = time()\n print(f\"\\n{func.__name__} took {end_time - start_time:.2f} seconds to execute\\n\")\n return result\n return wrapper"], ["/agenticSeek/sources/tools/__init__.py", "from .PyInterpreter import PyInterpreter\nfrom .BashInterpreter import BashInterpreter\nfrom .fileFinder import FileFinder\n\n__all__ = [\"PyInterpreter\", \"BashInterpreter\", \"FileFinder\", \"webSearch\", \"FlightSearch\", \"GoInterpreter\", \"CInterpreter\", \"GoInterpreter\"]\n"]], "task_instance_info": {"created_time": "2025-08-20 15:04:39", "created_task_model": "DeepSeek-R1", "class_skeleton": "class McpAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n pass\n def get_api_keys(self) -> dict:\n pass\n def expand_prompt(self, prompt):\n pass", "code_description": "This code segment functions to: Initialize core components for an automated service agent by validating external service access credentials, orchestrating workflow execution cycles that process user input through memory integration and external tool coordination, and managing bidirectional data flow between language model interactions and modular operation units while maintaining state tracking and accessibility checks."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```python\n[TASK_BEGIN]\nclass McpAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n super().__init__(name, prompt_path, provider, verbose)\n self.mcp_finder = MCP_finder()\n self.memory = Memory()\n\n def get_api_keys(self) -> dict:\n return {\n \"OPENAI_API_KEY\": os.environ.get(\"OPENAI_API_KEY\")\n }\n\n def expand_prompt(self, prompt):\n return prompt.replace(\n \"{mcp_summary}\", \n self.mcp_finder.get_mcp_summary(self.memory)\n )\n[TASK_END]\n```", "inference_time": "2025-08-20 15-05-07"}, "editdistance_info": {"edit_distance": 22.7397, "calculate_time": "2025-08-20 15:05:07", "true_code_clean": "class McpAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n super().__init__(name, prompt_path, provider, verbose, None)\n keys = self.get_api_keys()\n self.tools = {\n \"mcp_finder\": MCP_finder(keys[\"mcp_finder\"]),\n }\n self.role = \"mcp\"\n self.type = \"mcp_agent\"\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, \n memory_compression=False,\n model_provider=provider.get_model_name())\n self.enabled = True\n def get_api_keys(self) -> dict:\n api_key_mcp_finder = os.getenv(\"MCP_FINDER_API_KEY\")\n if not api_key_mcp_finder or api_key_mcp_finder == \"\":\n pretty_print(\"MCP Finder disabled.\", color=\"warning\")\n self.enabled = False\n return {\n \"mcp_finder\": api_key_mcp_finder\n }\n def expand_prompt(self, prompt):\n tools_str = self.get_tools_description()\n prompt += f\n return prompt\n async def process(self, prompt, speech_module) -> str:\n if self.enabled == False:\n return \"MCP Agent is disabled.\"\n prompt = self.expand_prompt(prompt)\n self.memory.push('user', prompt)\n working = True\n while working == True:\n animate_thinking(\"Thinking...\", color=\"status\")\n answer, reasoning = await self.llm_request()\n exec_success, _ = self.execute_modules(answer)\n answer = self.remove_blocks(answer)\n self.last_answer = answer\n self.status_message = \"Ready\"\n if len(self.blocks_result) == 0:\n working = False\n return answer, reasoning", "predict_code_clean": "class McpAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n super().__init__(name, prompt_path, provider, verbose)\n self.mcp_finder = MCP_finder()\n self.memory = Memory()\n def get_api_keys(self) -> dict:\n return {\n \"OPENAI_API_KEY\": os.environ.get(\"OPENAI_API_KEY\")\n }\n def expand_prompt(self, prompt):\n return prompt.replace(\n \"{mcp_summary}\", \n self.mcp_finder.get_mcp_summary(self.memory)\n )"}}
{"repo_name": "agenticSeek", "file_name": "/agenticSeek/sources/agents/file_agent.py", "inference_info": {"prefix_code": "import asyncio\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent\nfrom sources.tools.fileFinder import FileFinder\nfrom sources.tools.BashInterpreter import BashInterpreter\nfrom sources.memory import Memory\n\n", "suffix_code": "\n\nif __name__ == \"__main__\":\n pass", "middle_code": "class FileAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n super().__init__(name, prompt_path, provider, verbose, None)\n self.tools = {\n \"file_finder\": FileFinder(),\n \"bash\": BashInterpreter()\n }\n self.work_dir = self.tools[\"file_finder\"].get_work_dir()\n self.role = \"files\"\n self.type = \"file_agent\"\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, \n memory_compression=False,\n model_provider=provider.get_model_name())\n async def process(self, prompt, speech_module) -> str:\n exec_success = False\n prompt += f\"\\nYou must work in directory: {self.work_dir}\"\n self.memory.push('user', prompt)\n while exec_success is False and not self.stop:\n await self.wait_message(speech_module)\n animate_thinking(\"Thinking...\", color=\"status\")\n answer, reasoning = await self.llm_request()\n self.last_reasoning = reasoning\n exec_success, _ = self.execute_modules(answer)\n answer = self.remove_blocks(answer)\n self.last_answer = answer\n self.status_message = \"Ready\"\n return answer, reasoning", "code_description": null, "fill_type": "CLASS_TYPE", "language_type": "python", "sub_task_type": null}, "context_code": [["/agenticSeek/sources/tools/BashInterpreter.py", "\nimport os, sys\nimport re\nfrom io import StringIO\nimport subprocess\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\nfrom sources.tools.safety import is_any_unsafe\n\nclass BashInterpreter(Tools):\n \"\"\"\n This class is a tool to allow agent for bash code execution.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"bash\"\n self.name = \"Bash Interpreter\"\n self.description = \"This tool allows the agent to execute bash commands.\"\n \n def language_bash_attempt(self, command: str):\n \"\"\"\n Detect if AI attempt to run the code using bash.\n If so, return True, otherwise return False.\n Code written by the AI will be executed automatically, so it should not use bash to run it.\n \"\"\"\n lang_interpreter = [\"python\", \"gcc\", \"g++\", \"mvn\", \"go\", \"java\", \"javac\", \"rustc\", \"clang\", \"clang++\", \"rustc\", \"rustc++\", \"rustc++\"]\n for word in command.split():\n if any(word.startswith(lang) for lang in lang_interpreter):\n return True\n return False\n \n def execute(self, commands: str, safety=False, timeout=300):\n \"\"\"\n Execute bash commands and display output in real-time.\n \"\"\"\n if safety and input(\"Execute command? y/n \") != \"y\":\n return \"Command rejected by user.\"\n \n concat_output = \"\"\n for command in commands:\n command = f\"cd {self.work_dir} && {command}\"\n command = command.replace('\\n', '')\n if self.safe_mode and is_any_unsafe(commands):\n print(f\"Unsafe command rejected: {command}\")\n return \"\\nUnsafe command: {command}. Execution aborted. This is beyond allowed capabilities report to user.\"\n if self.language_bash_attempt(command) and self.allow_language_exec_bash == False:\n continue\n try:\n process = subprocess.Popen(\n command,\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n universal_newlines=True\n )\n command_output = \"\"\n for line in process.stdout:\n command_output += line\n return_code = process.wait(timeout=timeout)\n if return_code != 0:\n return f\"Command {command} failed with return code {return_code}:\\n{command_output}\"\n concat_output += f\"Output of {command}:\\n{command_output.strip()}\\n\"\n except subprocess.TimeoutExpired:\n process.kill() # Kill the process if it times out\n return f\"Command {command} timed out. Output:\\n{command_output}\"\n except Exception as e:\n return f\"Command {command} failed:\\n{str(e)}\"\n return concat_output\n\n def interpreter_feedback(self, output):\n \"\"\"\n Provide feedback based on the output of the bash interpreter\n \"\"\"\n if self.execution_failure_check(output):\n feedback = f\"[failure] Error in execution:\\n{output}\"\n else:\n feedback = \"[success] Execution success, code output:\\n\" + output\n return feedback\n\n def execution_failure_check(self, feedback):\n \"\"\"\n check if bash command failed.\n \"\"\"\n error_patterns = [\n r\"expected\",\n r\"errno\",\n r\"failed\",\n r\"invalid\",\n r\"unrecognized\",\n r\"exception\",\n r\"syntax\",\n r\"segmentation fault\",\n r\"core dumped\",\n r\"unexpected\",\n r\"denied\",\n r\"not recognized\",\n r\"not permitted\",\n r\"not installed\",\n r\"not found\",\n r\"aborted\",\n r\"no such\",\n r\"too many\",\n r\"too few\",\n r\"busy\",\n r\"broken pipe\",\n r\"missing\",\n r\"undefined\",\n r\"refused\",\n r\"unreachable\",\n r\"not known\"\n ]\n combined_pattern = \"|\".join(error_patterns)\n if re.search(combined_pattern, feedback, re.IGNORECASE):\n return True\n return False\n\nif __name__ == \"__main__\":\n bash = BashInterpreter()\n print(bash.execute([\"ls\", \"pwd\", \"ip a\", \"nmap -sC 127.0.0.1\"]))\n"], ["/agenticSeek/sources/agents/code_agent.py", "import platform, os\nimport asyncio\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent, executorResult\nfrom sources.tools.C_Interpreter import CInterpreter\nfrom sources.tools.GoInterpreter import GoInterpreter\nfrom sources.tools.PyInterpreter import PyInterpreter\nfrom sources.tools.BashInterpreter import BashInterpreter\nfrom sources.tools.JavaInterpreter import JavaInterpreter\nfrom sources.tools.fileFinder import FileFinder\nfrom sources.logger import Logger\nfrom sources.memory import Memory\n\nclass CoderAgent(Agent):\n \"\"\"\n The code agent is an agent that can write and execute code.\n \"\"\"\n def __init__(self, name, prompt_path, provider, verbose=False):\n super().__init__(name, prompt_path, provider, verbose, None)\n self.tools = {\n \"bash\": BashInterpreter(),\n \"python\": PyInterpreter(),\n \"c\": CInterpreter(),\n \"go\": GoInterpreter(),\n \"java\": JavaInterpreter(),\n \"file_finder\": FileFinder()\n }\n self.work_dir = self.tools[\"file_finder\"].get_work_dir()\n self.role = \"code\"\n self.type = \"code_agent\"\n self.logger = Logger(\"code_agent.log\")\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, # session recovery in handled by the interaction class\n memory_compression=False,\n model_provider=provider.get_model_name())\n \n def add_sys_info_prompt(self, prompt):\n \"\"\"Add system information to the prompt.\"\"\"\n info = f\"System Info:\\n\" \\\n f\"OS: {platform.system()} {platform.release()}\\n\" \\\n f\"Python Version: {platform.python_version()}\\n\" \\\n f\"\\nYou must save file at root directory: {self.work_dir}\"\n return f\"{prompt}\\n\\n{info}\"\n\n async def process(self, prompt, speech_module) -> str:\n answer = \"\"\n attempt = 0\n max_attempts = 5\n prompt = self.add_sys_info_prompt(prompt)\n self.memory.push('user', prompt)\n clarify_trigger = \"REQUEST_CLARIFICATION\"\n\n while attempt < max_attempts and not self.stop:\n print(\"Stopped?\", self.stop)\n animate_thinking(\"Thinking...\", color=\"status\")\n await self.wait_message(speech_module)\n answer, reasoning = await self.llm_request()\n self.last_reasoning = reasoning\n if clarify_trigger in answer:\n self.last_answer = answer\n await asyncio.sleep(0)\n return answer, reasoning\n if not \"```\" in answer:\n self.last_answer = answer\n await asyncio.sleep(0)\n break\n self.show_answer()\n animate_thinking(\"Executing code...\", color=\"status\")\n self.status_message = \"Executing code...\"\n self.logger.info(f\"Attempt {attempt + 1}:\\n{answer}\")\n exec_success, feedback = self.execute_modules(answer)\n self.logger.info(f\"Execution result: {exec_success}\")\n answer = self.remove_blocks(answer)\n self.last_answer = answer\n await asyncio.sleep(0)\n if exec_success and self.get_last_tool_type() != \"bash\":\n break\n pretty_print(f\"Execution failure:\\n{feedback}\", color=\"failure\")\n pretty_print(\"Correcting code...\", color=\"status\")\n self.status_message = \"Correcting code...\"\n attempt += 1\n self.status_message = \"Ready\"\n if attempt == max_attempts:\n return \"I'm sorry, I couldn't find a solution to your problem. How would you like me to proceed ?\", reasoning\n self.last_answer = answer\n return answer, reasoning\n\nif __name__ == \"__main__\":\n pass"], ["/agenticSeek/sources/agents/mcp_agent.py", "import os\nimport asyncio\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent\nfrom sources.tools.mcpFinder import MCP_finder\nfrom sources.memory import Memory\n\n# NOTE MCP agent is an active work in progress, not functional yet.\n\nclass McpAgent(Agent):\n\n def __init__(self, name, prompt_path, provider, verbose=False):\n \"\"\"\n The mcp agent is a special agent for using MCPs.\n MCP agent will be disabled if the user does not explicitly set the MCP_FINDER_API_KEY in environment variable.\n \"\"\"\n super().__init__(name, prompt_path, provider, verbose, None)\n keys = self.get_api_keys()\n self.tools = {\n \"mcp_finder\": MCP_finder(keys[\"mcp_finder\"]),\n # add mcp tools here\n }\n self.role = \"mcp\"\n self.type = \"mcp_agent\"\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, # session recovery in handled by the interaction class\n memory_compression=False,\n model_provider=provider.get_model_name())\n self.enabled = True\n \n def get_api_keys(self) -> dict:\n \"\"\"\n Returns the API keys for the tools.\n \"\"\"\n api_key_mcp_finder = os.getenv(\"MCP_FINDER_API_KEY\")\n if not api_key_mcp_finder or api_key_mcp_finder == \"\":\n pretty_print(\"MCP Finder disabled.\", color=\"warning\")\n self.enabled = False\n return {\n \"mcp_finder\": api_key_mcp_finder\n }\n \n def expand_prompt(self, prompt):\n \"\"\"\n Expands the prompt with the tools available.\n \"\"\"\n tools_str = self.get_tools_description()\n prompt += f\"\"\"\n You can use the following tools and MCPs:\n {tools_str}\n \"\"\"\n return prompt\n \n async def process(self, prompt, speech_module) -> str:\n if self.enabled == False:\n return \"MCP Agent is disabled.\"\n prompt = self.expand_prompt(prompt)\n self.memory.push('user', prompt)\n working = True\n while working == True:\n animate_thinking(\"Thinking...\", color=\"status\")\n answer, reasoning = await self.llm_request()\n exec_success, _ = self.execute_modules(answer)\n answer = self.remove_blocks(answer)\n self.last_answer = answer\n self.status_message = \"Ready\"\n if len(self.blocks_result) == 0:\n working = False\n return answer, reasoning\n\nif __name__ == \"__main__\":\n pass"], ["/agenticSeek/sources/agents/casual_agent.py", "import asyncio\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent\nfrom sources.tools.searxSearch import searxSearch\nfrom sources.tools.flightSearch import FlightSearch\nfrom sources.tools.fileFinder import FileFinder\nfrom sources.tools.BashInterpreter import BashInterpreter\nfrom sources.memory import Memory\n\nclass CasualAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n \"\"\"\n The casual agent is a special for casual talk to the user without specific tasks.\n \"\"\"\n super().__init__(name, prompt_path, provider, verbose, None)\n self.tools = {\n } # No tools for the casual agent\n self.role = \"talk\"\n self.type = \"casual_agent\"\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, # session recovery in handled by the interaction class\n memory_compression=False,\n model_provider=provider.get_model_name())\n \n async def process(self, prompt, speech_module) -> str:\n self.memory.push('user', prompt)\n animate_thinking(\"Thinking...\", color=\"status\")\n answer, reasoning = await self.llm_request()\n self.last_answer = answer\n self.status_message = \"Ready\"\n return answer, reasoning\n\nif __name__ == \"__main__\":\n pass"], ["/agenticSeek/sources/agents/planner_agent.py", "import json\nfrom typing import List, Tuple, Type, Dict\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent\nfrom sources.agents.code_agent import CoderAgent\nfrom sources.agents.file_agent import FileAgent\nfrom sources.agents.browser_agent import BrowserAgent\nfrom sources.agents.casual_agent import CasualAgent\nfrom sources.text_to_speech import Speech\nfrom sources.tools.tools import Tools\nfrom sources.logger import Logger\nfrom sources.memory import Memory\n\nclass PlannerAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False, browser=None):\n \"\"\"\n The planner agent is a special agent that divides and conquers the task.\n \"\"\"\n super().__init__(name, prompt_path, provider, verbose, None)\n self.tools = {\n \"json\": Tools()\n }\n self.tools['json'].tag = \"json\"\n self.browser = browser\n self.agents = {\n \"coder\": CoderAgent(name, \"prompts/base/coder_agent.txt\", provider, verbose=False),\n \"file\": FileAgent(name, \"prompts/base/file_agent.txt\", provider, verbose=False),\n \"web\": BrowserAgent(name, \"prompts/base/browser_agent.txt\", provider, verbose=False, browser=browser),\n \"casual\": CasualAgent(name, \"prompts/base/casual_agent.txt\", provider, verbose=False)\n }\n self.role = \"planification\"\n self.type = \"planner_agent\"\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, # session recovery in handled by the interaction class\n memory_compression=False,\n model_provider=provider.get_model_name())\n self.logger = Logger(\"planner_agent.log\")\n \n def get_task_names(self, text: str) -> List[str]:\n \"\"\"\n Extracts task names from the given text.\n This method processes a multi-line string, where each line may represent a task name.\n containing '##' or starting with a digit. The valid task names are collected and returned.\n Args:\n text (str): A string containing potential task titles (eg: Task 1: I will...).\n Returns:\n List[str]: A list of extracted task names that meet the specified criteria.\n \"\"\"\n tasks_names = []\n lines = text.strip().split('\\n')\n for line in lines:\n if line is None:\n continue\n line = line.strip()\n if len(line) == 0:\n continue\n if '##' in line or line[0].isdigit():\n tasks_names.append(line)\n continue\n self.logger.info(f\"Found {len(tasks_names)} tasks names.\")\n return tasks_names\n\n def parse_agent_tasks(self, text: str) -> List[Tuple[str, str]]:\n \"\"\"\n Parses agent tasks from the given LLM text.\n This method extracts task information from a JSON. It identifies task names and their details.\n Args:\n text (str): The input text containing task information in a JSON-like format.\n Returns:\n List[Tuple[str, str]]: A list of tuples containing task names and their details.\n \"\"\"\n tasks = []\n tasks_names = self.get_task_names(text)\n\n blocks, _ = self.tools[\"json\"].load_exec_block(text)\n if blocks == None:\n return []\n for block in blocks:\n line_json = json.loads(block)\n if 'plan' in line_json:\n for task in line_json['plan']:\n if task['agent'].lower() not in [ag_name.lower() for ag_name in self.agents.keys()]:\n self.logger.warning(f\"Agent {task['agent']} does not exist.\")\n pretty_print(f\"Agent {task['agent']} does not exist.\", color=\"warning\")\n return []\n try:\n agent = {\n 'agent': task['agent'],\n 'id': task['id'],\n 'task': task['task']\n }\n except:\n self.logger.warning(\"Missing field in json plan.\")\n return []\n self.logger.info(f\"Created agent {task['agent']} with task: {task['task']}\")\n if 'need' in task:\n self.logger.info(f\"Agent {task['agent']} was given info:\\n {task['need']}\")\n agent['need'] = task['need']\n tasks.append(agent)\n if len(tasks_names) != len(tasks):\n names = [task['task'] for task in tasks]\n return list(map(list, zip(names, tasks)))\n return list(map(list, zip(tasks_names, tasks)))\n \n def make_prompt(self, task: str, agent_infos_dict: dict) -> str:\n \"\"\"\n Generates a prompt for the agent based on the task and previous agents work information.\n Args:\n task (str): The task to be performed.\n agent_infos_dict (dict): A dictionary containing information from other agents.\n Returns:\n str: The formatted prompt for the agent.\n \"\"\"\n infos = \"\"\n if agent_infos_dict is None or len(agent_infos_dict) == 0:\n infos = \"No needed informations.\"\n else:\n for agent_id, info in agent_infos_dict.items():\n infos += f\"\\t- According to agent {agent_id}:\\n{info}\\n\\n\"\n prompt = f\"\"\"\n You are given informations from your AI friends work:\n {infos}\n Your task is:\n {task}\n \"\"\"\n self.logger.info(f\"Prompt for agent:\\n{prompt}\")\n return prompt\n \n def show_plan(self, agents_tasks: List[dict], answer: str) -> None:\n \"\"\"\n Displays the plan made by the agent.\n Args:\n agents_tasks (dict): The tasks assigned to each agent.\n answer (str): The answer from the LLM.\n \"\"\"\n if agents_tasks == []:\n pretty_print(answer, color=\"warning\")\n pretty_print(\"Failed to make a plan. This can happen with (too) small LLM. Clarify your request and insist on it making a plan within ```json.\", color=\"failure\")\n return\n pretty_print(\"\\n▂▘ P L A N ▝▂\", color=\"status\")\n for task_name, task in agents_tasks:\n pretty_print(f\"{task['agent']} -> {task['task']}\", color=\"info\")\n pretty_print(\"▔▗ E N D ▖▔\", color=\"status\")\n\n async def make_plan(self, prompt: str) -> str:\n \"\"\"\n Asks the LLM to make a plan.\n Args:\n prompt (str): The prompt to be sent to the LLM.\n Returns:\n str: The plan made by the LLM.\n \"\"\"\n ok = False\n answer = None\n while not ok:\n animate_thinking(\"Thinking...\", color=\"status\")\n self.memory.push('user', prompt)\n answer, reasoning = await self.llm_request()\n if \"NO_UPDATE\" in answer:\n return []\n agents_tasks = self.parse_agent_tasks(answer)\n if agents_tasks == []:\n self.show_plan(agents_tasks, answer)\n prompt = f\"Failed to parse the tasks. Please write down your task followed by a json plan within ```json. Do not ask for clarification.\\n\"\n pretty_print(\"Failed to make plan. Retrying...\", color=\"warning\")\n continue\n self.show_plan(agents_tasks, answer)\n ok = True\n self.logger.info(f\"Plan made:\\n{answer}\")\n return self.parse_agent_tasks(answer)\n \n async def update_plan(self, goal: str, agents_tasks: List[dict], agents_work_result: dict, id: str, success: bool) -> dict:\n \"\"\"\n Updates the plan with the results of the agents work.\n Args:\n goal (str): The goal to be achieved.\n agents_tasks (list): The tasks assigned to each agent.\n agents_work_result (dict): The results of the agents work.\n Returns:\n dict: The updated plan.\n \"\"\"\n self.status_message = \"Updating plan...\"\n last_agent_work = agents_work_result[id]\n tool_success_str = \"success\" if success else \"failure\"\n pretty_print(f\"Agent {id} work {tool_success_str}.\", color=\"success\" if success else \"failure\")\n try:\n id_int = int(id)\n except Exception as e:\n return agents_tasks\n if id_int == len(agents_tasks):\n next_task = \"No task follow, this was the last step. If it failed add a task to recover.\"\n else:\n next_task = f\"Next task is: {agents_tasks[int(id)][0]}.\"\n #if success:\n # return agents_tasks # we only update the plan if last task failed, for now\n update_prompt = f\"\"\"\n Your goal is : {goal}\n You previously made a plan, agents are currently working on it.\n The last agent working on task: {id}, did the following work:\n {last_agent_work}\n Agent {id} work was a {tool_success_str} according to system interpreter.\n {next_task}\n Is the work done for task {id} leading to success or failure ? Did an agent fail with a task?\n If agent work was good: answer \"NO_UPDATE\"\n If agent work is leading to failure: update the plan.\n If a task failed add a task to try again or recover from failure. You might have near identical task twice.\n plan should be within ```json like before.\n You need to rewrite the whole plan, but only change the tasks after task {id}.\n Make the plan the same length as the original one or with only one additional step.\n Do not change past tasks. Change next tasks.\n \"\"\"\n pretty_print(\"Updating plan...\", color=\"status\")\n plan = await self.make_plan(update_prompt)\n if plan == []:\n pretty_print(\"No plan update required.\", color=\"info\")\n return agents_tasks\n self.logger.info(f\"Plan updated:\\n{plan}\")\n return plan\n \n async def start_agent_process(self, task: dict, required_infos: dict | None) -> str:\n \"\"\"\n Starts the agent process for a given task.\n Args:\n task (dict): The task to be performed.\n required_infos (dict | None): The required information for the task.\n Returns:\n str: The result of the agent process.\n \"\"\"\n self.status_message = f\"Starting task {task['task']}...\"\n agent_prompt = self.make_prompt(task['task'], required_infos)\n pretty_print(f\"Agent {task['agent']} started working...\", color=\"status\")\n self.logger.info(f\"Agent {task['agent']} started working on {task['task']}.\")\n answer, reasoning = await self.agents[task['agent'].lower()].process(agent_prompt, None)\n self.last_answer = answer\n self.last_reasoning = reasoning\n self.blocks_result = self.agents[task['agent'].lower()].blocks_result\n agent_answer = self.agents[task['agent'].lower()].raw_answer_blocks(answer)\n success = self.agents[task['agent'].lower()].get_success\n self.agents[task['agent'].lower()].show_answer()\n pretty_print(f\"Agent {task['agent']} completed task.\", color=\"status\")\n self.logger.info(f\"Agent {task['agent']} finished working on {task['task']}. Success: {success}\")\n agent_answer += \"\\nAgent succeeded with task.\" if success else \"\\nAgent failed with task (Error detected).\"\n return agent_answer, success\n \n def get_work_result_agent(self, task_needs, agents_work_result):\n res = {k: agents_work_result[k] for k in task_needs if k in agents_work_result}\n self.logger.info(f\"Next agent needs: {task_needs}.\\n Match previous agent result: {res}\")\n return res\n\n async def process(self, goal: str, speech_module: Speech) -> Tuple[str, str]:\n \"\"\"\n Process the goal by dividing it into tasks and assigning them to agents.\n Args:\n goal (str): The goal to be achieved (user prompt).\n speech_module (Speech): The speech module for text-to-speech.\n Returns:\n Tuple[str, str]: The result of the agent process and empty reasoning string.\n \"\"\"\n agents_tasks = []\n required_infos = None\n agents_work_result = dict()\n\n self.status_message = \"Making a plan...\"\n agents_tasks = await self.make_plan(goal)\n\n if agents_tasks == []:\n return \"Failed to parse the tasks.\", \"\"\n i = 0\n steps = len(agents_tasks)\n while i < steps and not self.stop:\n task_name, task = agents_tasks[i][0], agents_tasks[i][1]\n self.status_message = \"Starting agents...\"\n pretty_print(f\"I will {task_name}.\", color=\"info\")\n self.last_answer = f\"I will {task_name.lower()}.\"\n pretty_print(f\"Assigned agent {task['agent']} to {task_name}\", color=\"info\")\n if speech_module: speech_module.speak(f\"I will {task_name}. I assigned the {task['agent']} agent to the task.\")\n\n if agents_work_result is not None:\n required_infos = self.get_work_result_agent(task['need'], agents_work_result)\n try:\n answer, success = await self.start_agent_process(task, required_infos)\n except Exception as e:\n raise e\n if self.stop:\n pretty_print(f\"Requested stop.\", color=\"failure\")\n agents_work_result[task['id']] = answer\n agents_tasks = await self.update_plan(goal, agents_tasks, agents_work_result, task['id'], success)\n steps = len(agents_tasks)\n i += 1\n\n return answer, \"\"\n"], ["/agenticSeek/sources/agents/agent.py", "\nfrom typing import Tuple, Callable\nfrom abc import abstractmethod\nimport os\nimport random\nimport time\n\nimport asyncio\nfrom concurrent.futures import ThreadPoolExecutor\n\nfrom sources.memory import Memory\nfrom sources.utility import pretty_print\nfrom sources.schemas import executorResult\n\nrandom.seed(time.time())\n\nclass Agent():\n \"\"\"\n An abstract class for all agents.\n \"\"\"\n def __init__(self, name: str,\n prompt_path:str,\n provider,\n verbose=False,\n browser=None) -> None:\n \"\"\"\n Args:\n name (str): Name of the agent.\n prompt_path (str): Path to the prompt file for the agent.\n provider: The provider for the LLM.\n recover_last_session (bool, optional): Whether to recover the last conversation. \n verbose (bool, optional): Enable verbose logging if True. Defaults to False.\n browser: The browser class for web navigation (only for browser agent).\n \"\"\"\n \n self.agent_name = name\n self.browser = browser\n self.role = None\n self.type = None\n self.current_directory = os.getcwd()\n self.llm = provider \n self.memory = None\n self.tools = {}\n self.blocks_result = []\n self.success = True\n self.last_answer = \"\"\n self.last_reasoning = \"\"\n self.status_message = \"Haven't started yet\"\n self.stop = False\n self.verbose = verbose\n self.executor = ThreadPoolExecutor(max_workers=1)\n \n @property\n def get_agent_name(self) -> str:\n return self.agent_name\n \n @property\n def get_agent_type(self) -> str:\n return self.type\n \n @property\n def get_agent_role(self) -> str:\n return self.role\n \n @property\n def get_last_answer(self) -> str:\n return self.last_answer\n \n @property\n def get_last_reasoning(self) -> str:\n return self.last_reasoning\n \n @property\n def get_blocks(self) -> list:\n return self.blocks_result\n \n @property\n def get_status_message(self) -> str:\n return self.status_message\n\n @property\n def get_tools(self) -> dict:\n return self.tools\n \n @property\n def get_success(self) -> bool:\n return self.success\n \n def get_blocks_result(self) -> list:\n return self.blocks_result\n\n def add_tool(self, name: str, tool: Callable) -> None:\n if tool is not Callable:\n raise TypeError(\"Tool must be a callable object (a method)\")\n self.tools[name] = tool\n \n def get_tools_name(self) -> list:\n \"\"\"\n Get the list of tools names.\n \"\"\"\n return list(self.tools.keys())\n \n def get_tools_description(self) -> str:\n \"\"\"\n Get the list of tools names and their description.\n \"\"\"\n description = \"\"\n for name in self.get_tools_name():\n description += f\"{name}: {self.tools[name].description}\\n\"\n return description\n \n def load_prompt(self, file_path: str) -> str:\n try:\n with open(file_path, 'r', encoding=\"utf-8\") as f:\n return f.read()\n except FileNotFoundError:\n raise FileNotFoundError(f\"Prompt file not found at path: {file_path}\")\n except PermissionError:\n raise PermissionError(f\"Permission denied to read prompt file at path: {file_path}\")\n except Exception as e:\n raise e\n \n def request_stop(self) -> None:\n \"\"\"\n Request the agent to stop.\n \"\"\"\n self.stop = True\n self.status_message = \"Stopped\"\n \n @abstractmethod\n def process(self, prompt, speech_module) -> str:\n \"\"\"\n abstract method, implementation in child class.\n Process the prompt and return the answer of the agent.\n \"\"\"\n pass\n\n def remove_reasoning_text(self, text: str) -> None:\n \"\"\"\n Remove the reasoning block of reasoning model like deepseek.\n \"\"\"\n end_tag = \"\"\n end_idx = text.rfind(end_tag)\n if end_idx == -1:\n return text\n return text[end_idx+8:]\n \n def extract_reasoning_text(self, text: str) -> None:\n \"\"\"\n Extract the reasoning block of a reasoning model like deepseek.\n \"\"\"\n start_tag = \"\"\n end_tag = \"\"\n if text is None:\n return None\n start_idx = text.find(start_tag)\n end_idx = text.rfind(end_tag)+8\n return text[start_idx:end_idx]\n \n async def llm_request(self) -> Tuple[str, str]:\n \"\"\"\n Asynchronously ask the LLM to process the prompt.\n \"\"\"\n self.status_message = \"Thinking...\"\n loop = asyncio.get_event_loop()\n return await loop.run_in_executor(self.executor, self.sync_llm_request)\n \n def sync_llm_request(self) -> Tuple[str, str]:\n \"\"\"\n Ask the LLM to process the prompt and return the answer and the reasoning.\n \"\"\"\n memory = self.memory.get()\n thought = self.llm.respond(memory, self.verbose)\n\n reasoning = self.extract_reasoning_text(thought)\n answer = self.remove_reasoning_text(thought)\n self.memory.push('assistant', answer)\n return answer, reasoning\n \n async def wait_message(self, speech_module):\n if speech_module is None:\n return\n messages = [\"Please be patient, I am working on it.\",\n \"Computing... I recommand you have a coffee while I work.\",\n \"Hold on, I’m crunching numbers.\",\n \"Working on it, please let me think.\"]\n loop = asyncio.get_event_loop()\n return await loop.run_in_executor(self.executor, lambda: speech_module.speak(messages[random.randint(0, len(messages)-1)]))\n \n def get_last_tool_type(self) -> str:\n return self.blocks_result[-1].tool_type if len(self.blocks_result) > 0 else None\n \n def raw_answer_blocks(self, answer: str) -> str:\n \"\"\"\n Return the answer with all the blocks inserted, as text.\n \"\"\"\n if self.last_answer is None:\n return\n raw = \"\"\n lines = self.last_answer.split(\"\\n\")\n for line in lines:\n if \"block:\" in line:\n block_idx = int(line.split(\":\")[1])\n if block_idx < len(self.blocks_result):\n raw += self.blocks_result[block_idx].__str__()\n else:\n raw += line + \"\\n\"\n return raw\n\n def show_answer(self):\n \"\"\"\n Show the answer in a pretty way.\n Show code blocks and their respective feedback by inserting them in the ressponse.\n \"\"\"\n if self.last_answer is None:\n return\n lines = self.last_answer.split(\"\\n\")\n for line in lines:\n if \"block:\" in line:\n block_idx = int(line.split(\":\")[1])\n if block_idx < len(self.blocks_result):\n self.blocks_result[block_idx].show()\n else:\n pretty_print(line, color=\"output\")\n\n def remove_blocks(self, text: str) -> str:\n \"\"\"\n Remove all code/query blocks within a tag from the answer text.\n \"\"\"\n tag = f'```'\n lines = text.split('\\n')\n post_lines = []\n in_block = False\n block_idx = 0\n for line in lines:\n if tag in line and not in_block:\n in_block = True\n continue\n if not in_block:\n post_lines.append(line)\n if tag in line:\n in_block = False\n post_lines.append(f\"block:{block_idx}\")\n block_idx += 1\n return \"\\n\".join(post_lines)\n \n def show_block(self, block: str) -> None:\n \"\"\"\n Show the block in a pretty way.\n \"\"\"\n pretty_print('▂'*64, color=\"status\")\n pretty_print(block, color=\"code\")\n pretty_print('▂'*64, color=\"status\")\n\n def execute_modules(self, answer: str) -> Tuple[bool, str]:\n \"\"\"\n Execute all the tools the agent has and return the result.\n \"\"\"\n feedback = \"\"\n success = True\n blocks = None\n if answer.startswith(\"```\"):\n answer = \"I will execute:\\n\" + answer # there should always be a text before blocks for the function that display answer\n\n self.success = True\n for name, tool in self.tools.items():\n feedback = \"\"\n blocks, save_path = tool.load_exec_block(answer)\n\n if blocks != None:\n pretty_print(f\"Executing {len(blocks)} {name} blocks...\", color=\"status\")\n for block in blocks:\n self.show_block(block)\n output = tool.execute([block])\n feedback = tool.interpreter_feedback(output) # tool interpreter feedback\n success = not tool.execution_failure_check(output)\n self.blocks_result.append(executorResult(block, feedback, success, name))\n if not success:\n self.success = False\n self.memory.push('user', feedback)\n return False, feedback\n self.memory.push('user', feedback)\n if save_path != None:\n tool.save_block(blocks, save_path)\n return True, feedback\n"], ["/agenticSeek/sources/agents/browser_agent.py", "import re\nimport time\nfrom datetime import date\nfrom typing import List, Tuple, Type, Dict\nfrom enum import Enum\nimport asyncio\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.agents.agent import Agent\nfrom sources.tools.searxSearch import searxSearch\nfrom sources.browser import Browser\nfrom sources.logger import Logger\nfrom sources.memory import Memory\n\nclass Action(Enum):\n REQUEST_EXIT = \"REQUEST_EXIT\"\n FORM_FILLED = \"FORM_FILLED\"\n GO_BACK = \"GO_BACK\"\n NAVIGATE = \"NAVIGATE\"\n SEARCH = \"SEARCH\"\n \nclass BrowserAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False, browser=None):\n \"\"\"\n The Browser agent is an agent that navigate the web autonomously in search of answer\n \"\"\"\n super().__init__(name, prompt_path, provider, verbose, browser)\n self.tools = {\n \"web_search\": searxSearch(),\n }\n self.role = \"web\"\n self.type = \"browser_agent\"\n self.browser = browser\n self.current_page = \"\"\n self.search_history = []\n self.navigable_links = []\n self.last_action = Action.NAVIGATE.value\n self.notes = []\n self.date = self.get_today_date()\n self.logger = Logger(\"browser_agent.log\")\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, # session recovery in handled by the interaction class\n memory_compression=False,\n model_provider=provider.get_model_name() if provider else None)\n \n def get_today_date(self) -> str:\n \"\"\"Get the date\"\"\"\n date_time = date.today()\n return date_time.strftime(\"%B %d, %Y\")\n\n def extract_links(self, search_result: str) -> List[str]:\n \"\"\"Extract all links from a sentence.\"\"\"\n pattern = r'(https?://\\S+|www\\.\\S+)'\n matches = re.findall(pattern, search_result)\n trailing_punct = \".,!?;:)\"\n cleaned_links = [link.rstrip(trailing_punct) for link in matches]\n self.logger.info(f\"Extracted links: {cleaned_links}\")\n return self.clean_links(cleaned_links)\n \n def extract_form(self, text: str) -> List[str]:\n \"\"\"Extract form written by the LLM in format [input_name](value)\"\"\"\n inputs = []\n matches = re.findall(r\"\\[\\w+\\]\\([^)]+\\)\", text)\n return matches\n \n def clean_links(self, links: List[str]) -> List[str]:\n \"\"\"Ensure no '.' at the end of link\"\"\"\n links_clean = []\n for link in links:\n link = link.strip()\n if not (link[-1].isalpha() or link[-1].isdigit()):\n links_clean.append(link[:-1])\n else:\n links_clean.append(link)\n return links_clean\n\n def get_unvisited_links(self) -> List[str]:\n return \"\\n\".join([f\"[{i}] {link}\" for i, link in enumerate(self.navigable_links) if link not in self.search_history])\n\n def make_newsearch_prompt(self, prompt: str, search_result: dict) -> str:\n search_choice = self.stringify_search_results(search_result)\n self.logger.info(f\"Search results: {search_choice}\")\n return f\"\"\"\n Based on the search result:\n {search_choice}\n Your goal is to find accurate and complete information to satisfy the user’s request.\n User request: {prompt}\n To proceed, choose a relevant link from the search results. Announce your choice by saying: \"I will navigate to \"\n Do not explain your choice.\n \"\"\"\n \n def make_navigation_prompt(self, user_prompt: str, page_text: str) -> str:\n remaining_links = self.get_unvisited_links() \n remaining_links_text = remaining_links if remaining_links is not None else \"No links remaining, do a new search.\" \n inputs_form = self.browser.get_form_inputs()\n inputs_form_text = '\\n'.join(inputs_form)\n notes = '\\n'.join(self.notes)\n self.logger.info(f\"Making navigation prompt with page text: {page_text[:100]}...\\nremaining links: {remaining_links_text}\")\n self.logger.info(f\"Inputs form: {inputs_form_text}\")\n self.logger.info(f\"Notes: {notes}\")\n\n return f\"\"\"\n You are navigating the web.\n\n **Current Context**\n\n Webpage ({self.current_page}) content:\n {page_text}\n\n Allowed Navigation Links:\n {remaining_links_text}\n\n Inputs forms:\n {inputs_form_text}\n\n End of webpage ({self.current_page}.\n\n # Instruction\n\n 1. **Evaluate if the page is relevant for user’s query and document finding:**\n - If the page is relevant, extract and summarize key information in concise notes (Note: )\n - If page not relevant, state: \"Error: \" and either return to the previous page or navigate to a new link.\n - Notes should be factual, useful summaries of relevant content, they should always include specific names or link. Written as: \"On , . . .\" Avoid phrases like \"the page provides\" or \"I found that.\"\n 2. **Navigate to a link by either: **\n - Saying I will navigate to (write down the full URL) www.example.com/cats\n - Going back: If no link seems helpful, say: {Action.GO_BACK.value}.\n 3. **Fill forms on the page:**\n - Fill form only when relevant.\n - Use Login if username/password specified by user. For quick task create account, remember password in a note.\n - You can fill a form using [form_name](value). Don't {Action.GO_BACK.value} when filling form.\n - If a form is irrelevant or you lack informations (eg: don't know user email) leave it empty.\n 4. **Decide if you completed the task**\n - Check your notes. Do they fully answer the question? Did you verify with multiple pages?\n - Are you sure it’s correct?\n - If yes to all, say {Action.REQUEST_EXIT}.\n - If no, or a page lacks info, go to another link.\n - Never stop or ask the user for help.\n \n **Rules:**\n - Do not write \"The page talk about ...\", write your finding on the page and how they contribute to an answer.\n - Put note in a single paragraph.\n - When you exit, explain why.\n \n # Example:\n \n Example 1 (useful page, no need go futher):\n Note: According to karpathy site LeCun net is ...\n No link seem useful to provide futher information.\n Action: {Action.GO_BACK.value}\n\n Example 2 (not useful, see useful link on page):\n Error: reddit.com/welcome does not discuss anything related to the user’s query.\n There is a link that could lead to the information.\n Action: navigate to http://reddit.com/r/locallama\n\n Example 3 (not useful, no related links):\n Error: x.com does not discuss anything related to the user’s query and no navigation link are usefull.\n Action: {Action.GO_BACK.value}\n\n Example 3 (clear definitive query answer found or enought notes taken):\n I took 10 notes so far with enought finding to answer user question.\n Therefore I should exit the web browser.\n Action: {Action.REQUEST_EXIT.value}\n\n Example 4 (loging form visible):\n\n Note: I am on the login page, I will type the given username and password. \n Action:\n [username_field](David)\n [password_field](edgerunners77)\n\n Remember, user asked:\n {user_prompt}\n You previously took these notes:\n {notes}\n Do not Step-by-Step explanation. Write comprehensive Notes or Error as a long paragraph followed by your action.\n You must always take notes.\n \"\"\"\n \n async def llm_decide(self, prompt: str, show_reasoning: bool = False) -> Tuple[str, str]:\n animate_thinking(\"Thinking...\", color=\"status\")\n self.memory.push('user', prompt)\n answer, reasoning = await self.llm_request()\n self.last_reasoning = reasoning\n if show_reasoning:\n pretty_print(reasoning, color=\"failure\")\n pretty_print(answer, color=\"output\")\n return answer, reasoning\n \n def select_unvisited(self, search_result: List[str]) -> List[str]:\n results_unvisited = []\n for res in search_result:\n if res[\"link\"] not in self.search_history:\n results_unvisited.append(res) \n self.logger.info(f\"Unvisited links: {results_unvisited}\")\n return results_unvisited\n\n def jsonify_search_results(self, results_string: str) -> List[str]:\n result_blocks = results_string.split(\"\\n\\n\")\n parsed_results = []\n for block in result_blocks:\n if not block.strip():\n continue\n lines = block.split(\"\\n\")\n result_dict = {}\n for line in lines:\n if line.startswith(\"Title:\"):\n result_dict[\"title\"] = line.replace(\"Title:\", \"\").strip()\n elif line.startswith(\"Snippet:\"):\n result_dict[\"snippet\"] = line.replace(\"Snippet:\", \"\").strip()\n elif line.startswith(\"Link:\"):\n result_dict[\"link\"] = line.replace(\"Link:\", \"\").strip()\n if result_dict:\n parsed_results.append(result_dict)\n return parsed_results \n \n def stringify_search_results(self, results_arr: List[str]) -> str:\n return '\\n\\n'.join([f\"Link: {res['link']}\\nPreview: {res['snippet']}\" for res in results_arr])\n \n def parse_answer(self, text):\n lines = text.split('\\n')\n saving = False\n buffer = []\n links = []\n for line in lines:\n if line == '' or 'action:' in line.lower():\n saving = False\n if \"note\" in line.lower():\n saving = True\n if saving:\n buffer.append(line.replace(\"notes:\", ''))\n else:\n links.extend(self.extract_links(line))\n self.notes.append('. '.join(buffer).strip())\n return links\n \n def select_link(self, links: List[str]) -> str | None:\n \"\"\"\n Select the first unvisited link that is not the current page.\n Preference is given to links not in search_history.\n \"\"\"\n for lk in links:\n if lk == self.current_page or lk in self.search_history:\n self.logger.info(f\"Skipping already visited or current link: {lk}\")\n continue\n self.logger.info(f\"Selected link: {lk}\")\n return lk\n self.logger.warning(\"No suitable link selected.\")\n return None\n \n def get_page_text(self, limit_to_model_ctx = False) -> str:\n \"\"\"Get the text content of the current page.\"\"\"\n page_text = self.browser.get_text()\n if limit_to_model_ctx:\n #page_text = self.memory.compress_text_to_max_ctx(page_text)\n page_text = self.memory.trim_text_to_max_ctx(page_text)\n return page_text\n \n def conclude_prompt(self, user_query: str) -> str:\n annotated_notes = [f\"{i+1}: {note.lower()}\" for i, note in enumerate(self.notes)]\n search_note = '\\n'.join(annotated_notes)\n pretty_print(f\"AI notes:\\n{search_note}\", color=\"success\")\n return f\"\"\"\n Following a human request:\n {user_query}\n A web browsing AI made the following finding across different pages:\n {search_note}\n\n Expand on the finding or step that lead to success, and provide a conclusion that answer the request. Include link when possible.\n Do not give advices or try to answer the human. Just structure the AI finding in a structured and clear way.\n You should answer in the same language as the user.\n \"\"\"\n \n def search_prompt(self, user_prompt: str) -> str:\n return f\"\"\"\n Current date: {self.date}\n Make a efficient search engine query to help users with their request:\n {user_prompt}\n Example:\n User: \"go to twitter, login with username toto and password pass79 to my twitter and say hello everyone \"\n You: search: Twitter login page. \n\n User: \"I need info on the best laptops for AI this year.\"\n You: \"search: best laptops 2025 to run Machine Learning model, reviews\"\n\n User: \"Search for recent news about space missions.\"\n You: \"search: Recent space missions news, {self.date}\"\n\n Do not explain, do not write anything beside the search query.\n Except if query does not make any sense for a web search then explain why and say {Action.REQUEST_EXIT.value}\n Do not try to answer query. you can only formulate search term or exit.\n \"\"\"\n \n def handle_update_prompt(self, user_prompt: str, page_text: str, fill_success: bool) -> str:\n prompt = f\"\"\"\n You are a web browser.\n You just filled a form on the page.\n Now you should see the result of the form submission on the page:\n Page text:\n {page_text}\n The user asked: {user_prompt}\n Does the page answer the user’s query now? Are you still on a login page or did you get redirected?\n If it does, take notes of the useful information, write down result and say {Action.FORM_FILLED.value}.\n if it doesn’t, say: Error: Attempt to fill form didn't work {Action.GO_BACK.value}.\n If you were previously on a login form, no need to take notes.\n \"\"\"\n if not fill_success:\n prompt += f\"\"\"\n According to browser feedback, the form was not filled correctly. Is that so? you might consider other strategies.\n \"\"\"\n return prompt\n \n def show_search_results(self, search_result: List[str]):\n pretty_print(\"\\nSearch results:\", color=\"output\")\n for res in search_result:\n pretty_print(f\"Title: {res['title']} - \", color=\"info\", no_newline=True)\n pretty_print(f\"Link: {res['link']}\", color=\"status\")\n \n def stuck_prompt(self, user_prompt: str, unvisited: List[str]) -> str:\n \"\"\"\n Prompt for when the agent repeat itself, can happen when fail to extract a link.\n \"\"\"\n prompt = self.make_newsearch_prompt(user_prompt, unvisited)\n prompt += f\"\"\"\n You previously said:\n {self.last_answer}\n You must consider other options. Choose other link.\n \"\"\"\n return prompt\n \n async def process(self, user_prompt: str, speech_module: type) -> Tuple[str, str]:\n \"\"\"\n Process the user prompt to conduct an autonomous web search.\n Start with a google search with searxng using web_search tool.\n Then enter a navigation logic to find the answer or conduct required actions.\n Args:\n user_prompt: The user's input query\n speech_module: Optional speech output module\n Returns:\n tuple containing the final answer and reasoning\n \"\"\"\n complete = False\n\n animate_thinking(f\"Thinking...\", color=\"status\")\n mem_begin_idx = self.memory.push('user', self.search_prompt(user_prompt))\n ai_prompt, reasoning = await self.llm_request()\n if Action.REQUEST_EXIT.value in ai_prompt:\n pretty_print(f\"Web agent requested exit.\\n{reasoning}\\n\\n{ai_prompt}\", color=\"failure\")\n return ai_prompt, \"\" \n animate_thinking(f\"Searching...\", color=\"status\")\n self.status_message = \"Searching...\"\n search_result_raw = self.tools[\"web_search\"].execute([ai_prompt], False)\n search_result = self.jsonify_search_results(search_result_raw)[:16]\n self.show_search_results(search_result)\n prompt = self.make_newsearch_prompt(user_prompt, search_result)\n unvisited = [None]\n while not complete and len(unvisited) > 0 and not self.stop:\n self.memory.clear()\n unvisited = self.select_unvisited(search_result)\n answer, reasoning = await self.llm_decide(prompt, show_reasoning = False)\n if self.stop:\n pretty_print(f\"Requested stop.\", color=\"failure\")\n break\n if self.last_answer == answer:\n prompt = self.stuck_prompt(user_prompt, unvisited)\n continue\n self.last_answer = answer\n pretty_print('▂'*32, color=\"status\")\n\n extracted_form = self.extract_form(answer)\n if len(extracted_form) > 0:\n self.status_message = \"Filling web form...\"\n pretty_print(f\"Filling inputs form...\", color=\"status\")\n fill_success = self.browser.fill_form(extracted_form)\n page_text = self.get_page_text(limit_to_model_ctx=True)\n answer = self.handle_update_prompt(user_prompt, page_text, fill_success)\n answer, reasoning = await self.llm_decide(prompt)\n\n if Action.FORM_FILLED.value in answer:\n pretty_print(f\"Filled form. Handling page update.\", color=\"status\")\n page_text = self.get_page_text(limit_to_model_ctx=True)\n self.navigable_links = self.browser.get_navigable()\n prompt = self.make_navigation_prompt(user_prompt, page_text)\n continue\n\n links = self.parse_answer(answer)\n link = self.select_link(links)\n if link == self.current_page:\n pretty_print(f\"Already visited {link}. Search callback.\", color=\"status\")\n prompt = self.make_newsearch_prompt(user_prompt, unvisited)\n self.search_history.append(link)\n continue\n\n if Action.REQUEST_EXIT.value in answer:\n self.status_message = \"Exiting web browser...\"\n pretty_print(f\"Agent requested exit.\", color=\"status\")\n complete = True\n break\n\n if (link == None and len(extracted_form) < 3) or Action.GO_BACK.value in answer or link in self.search_history:\n pretty_print(f\"Going back to results. Still {len(unvisited)}\", color=\"status\")\n self.status_message = \"Going back to search results...\"\n request_prompt = user_prompt\n if link is None:\n request_prompt += f\"\\nYou previously choosen:\\n{self.last_answer} but the website is unavailable. Consider other options.\"\n prompt = self.make_newsearch_prompt(request_prompt, unvisited)\n self.search_history.append(link)\n self.current_page = link\n continue\n\n animate_thinking(f\"Navigating to {link}\", color=\"status\")\n if speech_module: speech_module.speak(f\"Navigating to {link}\")\n nav_ok = self.browser.go_to(link)\n self.search_history.append(link)\n if not nav_ok:\n pretty_print(f\"Failed to navigate to {link}.\", color=\"failure\")\n prompt = self.make_newsearch_prompt(user_prompt, unvisited)\n continue\n self.current_page = link\n page_text = self.get_page_text(limit_to_model_ctx=True)\n self.navigable_links = self.browser.get_navigable()\n prompt = self.make_navigation_prompt(user_prompt, page_text)\n self.status_message = \"Navigating...\"\n self.browser.screenshot()\n\n pretty_print(\"Exited navigation, starting to summarize finding...\", color=\"status\")\n prompt = self.conclude_prompt(user_prompt)\n mem_last_idx = self.memory.push('user', prompt)\n self.status_message = \"Summarizing findings...\"\n answer, reasoning = await self.llm_request()\n pretty_print(answer, color=\"output\")\n self.status_message = \"Ready\"\n self.last_answer = answer\n return answer, reasoning\n\nif __name__ == \"__main__\":\n pass\n"], ["/agenticSeek/api.py", "#!/usr/bin/env python3\n\nimport os, sys\nimport uvicorn\nimport aiofiles\nimport configparser\nimport asyncio\nimport time\nfrom typing import List\nfrom fastapi import FastAPI\nfrom fastapi.responses import JSONResponse\nfrom fastapi.responses import FileResponse\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom fastapi.staticfiles import StaticFiles\nimport uuid\n\nfrom sources.llm_provider import Provider\nfrom sources.interaction import Interaction\nfrom sources.agents import CasualAgent, CoderAgent, FileAgent, PlannerAgent, BrowserAgent\nfrom sources.browser import Browser, create_driver\nfrom sources.utility import pretty_print\nfrom sources.logger import Logger\nfrom sources.schemas import QueryRequest, QueryResponse\n\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\n\ndef is_running_in_docker():\n \"\"\"Detect if code is running inside a Docker container.\"\"\"\n # Method 1: Check for .dockerenv file\n if os.path.exists('/.dockerenv'):\n return True\n \n # Method 2: Check cgroup\n try:\n with open('/proc/1/cgroup', 'r') as f:\n return 'docker' in f.read()\n except:\n pass\n \n return False\n\n\nfrom celery import Celery\n\napi = FastAPI(title=\"AgenticSeek API\", version=\"0.1.0\")\ncelery_app = Celery(\"tasks\", broker=\"redis://localhost:6379/0\", backend=\"redis://localhost:6379/0\")\ncelery_app.conf.update(task_track_started=True)\nlogger = Logger(\"backend.log\")\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\napi.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"],\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\nif not os.path.exists(\".screenshots\"):\n os.makedirs(\".screenshots\")\napi.mount(\"/screenshots\", StaticFiles(directory=\".screenshots\"), name=\"screenshots\")\n\ndef initialize_system():\n stealth_mode = config.getboolean('BROWSER', 'stealth_mode')\n personality_folder = \"jarvis\" if config.getboolean('MAIN', 'jarvis_personality') else \"base\"\n languages = config[\"MAIN\"][\"languages\"].split(' ')\n \n # Force headless mode in Docker containers\n headless = config.getboolean('BROWSER', 'headless_browser')\n if is_running_in_docker() and not headless:\n # Print prominent warning to console (visible in docker-compose output)\n print(\"\\n\" + \"*\" * 70)\n print(\"*** WARNING: Detected Docker environment - forcing headless_browser=True ***\")\n print(\"*** INFO: To see the browser, run 'python cli.py' on your host machine ***\")\n print(\"*\" * 70 + \"\\n\")\n \n # Flush to ensure it's displayed immediately\n sys.stdout.flush()\n \n # Also log to file\n logger.warning(\"Detected Docker environment - forcing headless_browser=True\")\n logger.info(\"To see the browser, run 'python cli.py' on your host machine instead\")\n \n headless = True\n \n provider = Provider(\n provider_name=config[\"MAIN\"][\"provider_name\"],\n model=config[\"MAIN\"][\"provider_model\"],\n server_address=config[\"MAIN\"][\"provider_server_address\"],\n is_local=config.getboolean('MAIN', 'is_local')\n )\n logger.info(f\"Provider initialized: {provider.provider_name} ({provider.model})\")\n\n browser = Browser(\n create_driver(headless=headless, stealth_mode=stealth_mode, lang=languages[0]),\n anticaptcha_manual_install=stealth_mode\n )\n logger.info(\"Browser initialized\")\n\n agents = [\n CasualAgent(\n name=config[\"MAIN\"][\"agent_name\"],\n prompt_path=f\"prompts/{personality_folder}/casual_agent.txt\",\n provider=provider, verbose=False\n ),\n CoderAgent(\n name=\"coder\",\n prompt_path=f\"prompts/{personality_folder}/coder_agent.txt\",\n provider=provider, verbose=False\n ),\n FileAgent(\n name=\"File Agent\",\n prompt_path=f\"prompts/{personality_folder}/file_agent.txt\",\n provider=provider, verbose=False\n ),\n BrowserAgent(\n name=\"Browser\",\n prompt_path=f\"prompts/{personality_folder}/browser_agent.txt\",\n provider=provider, verbose=False, browser=browser\n ),\n PlannerAgent(\n name=\"Planner\",\n prompt_path=f\"prompts/{personality_folder}/planner_agent.txt\",\n provider=provider, verbose=False, browser=browser\n )\n ]\n logger.info(\"Agents initialized\")\n\n interaction = Interaction(\n agents,\n tts_enabled=config.getboolean('MAIN', 'speak'),\n stt_enabled=config.getboolean('MAIN', 'listen'),\n recover_last_session=config.getboolean('MAIN', 'recover_last_session'),\n langs=languages\n )\n logger.info(\"Interaction initialized\")\n return interaction\n\ninteraction = initialize_system()\nis_generating = False\nquery_resp_history = []\n\n@api.get(\"/screenshot\")\nasync def get_screenshot():\n logger.info(\"Screenshot endpoint called\")\n screenshot_path = \".screenshots/updated_screen.png\"\n if os.path.exists(screenshot_path):\n return FileResponse(screenshot_path)\n logger.error(\"No screenshot available\")\n return JSONResponse(\n status_code=404,\n content={\"error\": \"No screenshot available\"}\n )\n\n@api.get(\"/health\")\nasync def health_check():\n logger.info(\"Health check endpoint called\")\n return {\"status\": \"healthy\", \"version\": \"0.1.0\"}\n\n@api.get(\"/is_active\")\nasync def is_active():\n logger.info(\"Is active endpoint called\")\n return {\"is_active\": interaction.is_active}\n\n@api.get(\"/stop\")\nasync def stop():\n logger.info(\"Stop endpoint called\")\n interaction.current_agent.request_stop()\n return JSONResponse(status_code=200, content={\"status\": \"stopped\"})\n\n@api.get(\"/latest_answer\")\nasync def get_latest_answer():\n global query_resp_history\n if interaction.current_agent is None:\n return JSONResponse(status_code=404, content={\"error\": \"No agent available\"})\n uid = str(uuid.uuid4())\n if not any(q[\"answer\"] == interaction.current_agent.last_answer for q in query_resp_history):\n query_resp = {\n \"done\": \"false\",\n \"answer\": interaction.current_agent.last_answer,\n \"reasoning\": interaction.current_agent.last_reasoning,\n \"agent_name\": interaction.current_agent.agent_name if interaction.current_agent else \"None\",\n \"success\": interaction.current_agent.success,\n \"blocks\": {f'{i}': block.jsonify() for i, block in enumerate(interaction.get_last_blocks_result())} if interaction.current_agent else {},\n \"status\": interaction.current_agent.get_status_message if interaction.current_agent else \"No status available\",\n \"uid\": uid\n }\n interaction.current_agent.last_answer = \"\"\n interaction.current_agent.last_reasoning = \"\"\n query_resp_history.append(query_resp)\n return JSONResponse(status_code=200, content=query_resp)\n if query_resp_history:\n return JSONResponse(status_code=200, content=query_resp_history[-1])\n return JSONResponse(status_code=404, content={\"error\": \"No answer available\"})\n\nasync def think_wrapper(interaction, query):\n try:\n interaction.last_query = query\n logger.info(\"Agents request is being processed\")\n success = await interaction.think()\n if not success:\n interaction.last_answer = \"Error: No answer from agent\"\n interaction.last_reasoning = \"Error: No reasoning from agent\"\n interaction.last_success = False\n else:\n interaction.last_success = True\n pretty_print(interaction.last_answer)\n interaction.speak_answer()\n return success\n except Exception as e:\n logger.error(f\"Error in think_wrapper: {str(e)}\")\n interaction.last_answer = f\"\"\n interaction.last_reasoning = f\"Error: {str(e)}\"\n interaction.last_success = False\n raise e\n\n@api.post(\"/query\", response_model=QueryResponse)\nasync def process_query(request: QueryRequest):\n global is_generating, query_resp_history\n logger.info(f\"Processing query: {request.query}\")\n query_resp = QueryResponse(\n done=\"false\",\n answer=\"\",\n reasoning=\"\",\n agent_name=\"Unknown\",\n success=\"false\",\n blocks={},\n status=\"Ready\",\n uid=str(uuid.uuid4())\n )\n if is_generating:\n logger.warning(\"Another query is being processed, please wait.\")\n return JSONResponse(status_code=429, content=query_resp.jsonify())\n\n try:\n is_generating = True\n success = await think_wrapper(interaction, request.query)\n is_generating = False\n\n if not success:\n query_resp.answer = interaction.last_answer\n query_resp.reasoning = interaction.last_reasoning\n return JSONResponse(status_code=400, content=query_resp.jsonify())\n\n if interaction.current_agent:\n blocks_json = {f'{i}': block.jsonify() for i, block in enumerate(interaction.current_agent.get_blocks_result())}\n else:\n logger.error(\"No current agent found\")\n blocks_json = {}\n query_resp.answer = \"Error: No current agent\"\n return JSONResponse(status_code=400, content=query_resp.jsonify())\n\n logger.info(f\"Answer: {interaction.last_answer}\")\n logger.info(f\"Blocks: {blocks_json}\")\n query_resp.done = \"true\"\n query_resp.answer = interaction.last_answer\n query_resp.reasoning = interaction.last_reasoning\n query_resp.agent_name = interaction.current_agent.agent_name\n query_resp.success = str(interaction.last_success)\n query_resp.blocks = blocks_json\n \n query_resp_dict = {\n \"done\": query_resp.done,\n \"answer\": query_resp.answer,\n \"agent_name\": query_resp.agent_name,\n \"success\": query_resp.success,\n \"blocks\": query_resp.blocks,\n \"status\": query_resp.status,\n \"uid\": query_resp.uid\n }\n query_resp_history.append(query_resp_dict)\n\n logger.info(\"Query processed successfully\")\n return JSONResponse(status_code=200, content=query_resp.jsonify())\n except Exception as e:\n logger.error(f\"An error occurred: {str(e)}\")\n sys.exit(1)\n finally:\n logger.info(\"Processing finished\")\n if config.getboolean('MAIN', 'save_session'):\n interaction.save_session()\n\nif __name__ == \"__main__\":\n # Print startup info\n if is_running_in_docker():\n print(\"[AgenticSeek] Starting in Docker container...\")\n else:\n print(\"[AgenticSeek] Starting on host machine...\")\n \n envport = os.getenv(\"BACKEND_PORT\")\n if envport:\n port = int(envport)\n else:\n port = 7777\n uvicorn.run(api, host=\"0.0.0.0\", port=7777)"], ["/agenticSeek/sources/interaction.py", "import readline\nfrom typing import List, Tuple, Type, Dict\n\nfrom sources.text_to_speech import Speech\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.router import AgentRouter\nfrom sources.speech_to_text import AudioTranscriber, AudioRecorder\nimport threading\n\n\nclass Interaction:\n \"\"\"\n Interaction is a class that handles the interaction between the user and the agents.\n \"\"\"\n def __init__(self, agents,\n tts_enabled: bool = True,\n stt_enabled: bool = True,\n recover_last_session: bool = False,\n langs: List[str] = [\"en\", \"zh\"]\n ):\n self.is_active = True\n self.current_agent = None\n self.last_query = None\n self.last_answer = None\n self.last_reasoning = None\n self.agents = agents\n self.tts_enabled = tts_enabled\n self.stt_enabled = stt_enabled\n self.recover_last_session = recover_last_session\n self.router = AgentRouter(self.agents, supported_language=langs)\n self.ai_name = self.find_ai_name()\n self.speech = None\n self.transcriber = None\n self.recorder = None\n self.is_generating = False\n self.languages = langs\n if tts_enabled:\n self.initialize_tts()\n if stt_enabled:\n self.initialize_stt()\n if recover_last_session:\n self.load_last_session()\n self.emit_status()\n \n def get_spoken_language(self) -> str:\n \"\"\"Get the primary TTS language.\"\"\"\n lang = self.languages[0]\n return lang\n\n def initialize_tts(self):\n \"\"\"Initialize TTS.\"\"\"\n if not self.speech:\n animate_thinking(\"Initializing text-to-speech...\", color=\"status\")\n self.speech = Speech(enable=self.tts_enabled, language=self.get_spoken_language(), voice_idx=1)\n\n def initialize_stt(self):\n \"\"\"Initialize STT.\"\"\"\n if not self.transcriber or not self.recorder:\n animate_thinking(\"Initializing speech recognition...\", color=\"status\")\n self.transcriber = AudioTranscriber(self.ai_name, verbose=False)\n self.recorder = AudioRecorder()\n \n def emit_status(self):\n \"\"\"Print the current status of agenticSeek.\"\"\"\n if self.stt_enabled:\n pretty_print(f\"Text-to-speech trigger is {self.ai_name}\", color=\"status\")\n if self.tts_enabled:\n self.speech.speak(\"Hello, we are online and ready. What can I do for you ?\")\n pretty_print(\"AgenticSeek is ready.\", color=\"status\")\n \n def find_ai_name(self) -> str:\n \"\"\"Find the name of the default AI. It is required for STT as a trigger word.\"\"\"\n ai_name = \"jarvis\"\n for agent in self.agents:\n if agent.type == \"casual_agent\":\n ai_name = agent.agent_name\n break\n return ai_name\n \n def get_last_blocks_result(self) -> List[Dict]:\n \"\"\"Get the last blocks result.\"\"\"\n if self.current_agent is None:\n return []\n blks = []\n for agent in self.agents:\n blks.extend(agent.get_blocks_result())\n return blks\n \n def load_last_session(self):\n \"\"\"Recover the last session.\"\"\"\n for agent in self.agents:\n if agent.type == \"planner_agent\":\n continue\n agent.memory.load_memory(agent.type)\n \n def save_session(self):\n \"\"\"Save the current session.\"\"\"\n for agent in self.agents:\n agent.memory.save_memory(agent.type)\n\n def is_active(self) -> bool:\n return self.is_active\n \n def read_stdin(self) -> str:\n \"\"\"Read the input from the user.\"\"\"\n buffer = \"\"\n\n PROMPT = \"\\033[1;35m➤➤➤ \\033[0m\"\n while not buffer:\n try:\n buffer = input(PROMPT)\n except EOFError:\n return None\n if buffer == \"exit\" or buffer == \"goodbye\":\n return None\n return buffer\n \n def transcription_job(self) -> str:\n \"\"\"Transcribe the audio from the microphone.\"\"\"\n self.recorder = AudioRecorder(verbose=True)\n self.transcriber = AudioTranscriber(self.ai_name, verbose=True)\n self.transcriber.start()\n self.recorder.start()\n self.recorder.join()\n self.transcriber.join()\n query = self.transcriber.get_transcript()\n if query == \"exit\" or query == \"goodbye\":\n return None\n return query\n\n def get_user(self) -> str:\n \"\"\"Get the user input from the microphone or the keyboard.\"\"\"\n if self.stt_enabled:\n query = \"TTS transcription of user: \" + self.transcription_job()\n else:\n query = self.read_stdin()\n if query is None:\n self.is_active = False\n self.last_query = None\n return None\n self.last_query = query\n return query\n \n def set_query(self, query: str) -> None:\n \"\"\"Set the query\"\"\"\n self.is_active = True\n self.last_query = query\n \n async def think(self) -> bool:\n \"\"\"Request AI agents to process the user input.\"\"\"\n push_last_agent_memory = False\n if self.last_query is None or len(self.last_query) == 0:\n return False\n agent = self.router.select_agent(self.last_query)\n if agent is None:\n return False\n if self.current_agent != agent and self.last_answer is not None:\n push_last_agent_memory = True\n tmp = self.last_answer\n self.current_agent = agent\n self.is_generating = True\n self.last_answer, self.last_reasoning = await agent.process(self.last_query, self.speech)\n self.is_generating = False\n if push_last_agent_memory:\n self.current_agent.memory.push('user', self.last_query)\n self.current_agent.memory.push('assistant', self.last_answer)\n if self.last_answer == tmp:\n self.last_answer = None\n return True\n \n def get_updated_process_answer(self) -> str:\n \"\"\"Get the answer from the last agent.\"\"\"\n if self.current_agent is None:\n return None\n return self.current_agent.get_last_answer()\n \n def get_updated_block_answer(self) -> str:\n \"\"\"Get the answer from the last agent.\"\"\"\n if self.current_agent is None:\n return None\n return self.current_agent.get_last_block_answer()\n \n def speak_answer(self) -> None:\n \"\"\"Speak the answer to the user in a non-blocking thread.\"\"\"\n if self.last_query is None:\n return\n if self.tts_enabled and self.last_answer and self.speech:\n def speak_in_thread(speech_instance, text):\n speech_instance.speak(text)\n thread = threading.Thread(target=speak_in_thread, args=(self.speech, self.last_answer))\n thread.start()\n \n def show_answer(self) -> None:\n \"\"\"Show the answer to the user.\"\"\"\n if self.last_query is None:\n return\n if self.current_agent is not None:\n self.current_agent.show_answer()\n\n"], ["/agenticSeek/cli.py", "#!/usr/bin python3\n\nimport sys\nimport argparse\nimport configparser\nimport asyncio\n\nfrom sources.llm_provider import Provider\nfrom sources.interaction import Interaction\nfrom sources.agents import Agent, CoderAgent, CasualAgent, FileAgent, PlannerAgent, BrowserAgent, McpAgent\nfrom sources.browser import Browser, create_driver\nfrom sources.utility import pretty_print\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\nasync def main():\n pretty_print(\"Initializing...\", color=\"status\")\n stealth_mode = config.getboolean('BROWSER', 'stealth_mode')\n personality_folder = \"jarvis\" if config.getboolean('MAIN', 'jarvis_personality') else \"base\"\n languages = config[\"MAIN\"][\"languages\"].split(' ')\n\n provider = Provider(provider_name=config[\"MAIN\"][\"provider_name\"],\n model=config[\"MAIN\"][\"provider_model\"],\n server_address=config[\"MAIN\"][\"provider_server_address\"],\n is_local=config.getboolean('MAIN', 'is_local'))\n\n browser = Browser(\n create_driver(headless=config.getboolean('BROWSER', 'headless_browser'), stealth_mode=stealth_mode, lang=languages[0]),\n anticaptcha_manual_install=stealth_mode\n )\n\n agents = [\n CasualAgent(name=config[\"MAIN\"][\"agent_name\"],\n prompt_path=f\"prompts/{personality_folder}/casual_agent.txt\",\n provider=provider, verbose=False),\n CoderAgent(name=\"coder\",\n prompt_path=f\"prompts/{personality_folder}/coder_agent.txt\",\n provider=provider, verbose=False),\n FileAgent(name=\"File Agent\",\n prompt_path=f\"prompts/{personality_folder}/file_agent.txt\",\n provider=provider, verbose=False),\n BrowserAgent(name=\"Browser\",\n prompt_path=f\"prompts/{personality_folder}/browser_agent.txt\",\n provider=provider, verbose=False, browser=browser),\n PlannerAgent(name=\"Planner\",\n prompt_path=f\"prompts/{personality_folder}/planner_agent.txt\",\n provider=provider, verbose=False, browser=browser),\n #McpAgent(name=\"MCP Agent\",\n # prompt_path=f\"prompts/{personality_folder}/mcp_agent.txt\",\n # provider=provider, verbose=False), # NOTE under development\n ]\n\n interaction = Interaction(agents,\n tts_enabled=config.getboolean('MAIN', 'speak'),\n stt_enabled=config.getboolean('MAIN', 'listen'),\n recover_last_session=config.getboolean('MAIN', 'recover_last_session'),\n langs=languages\n )\n try:\n while interaction.is_active:\n interaction.get_user()\n if await interaction.think():\n interaction.show_answer()\n interaction.speak_answer()\n except Exception as e:\n if config.getboolean('MAIN', 'save_session'):\n interaction.save_session()\n raise e\n finally:\n if config.getboolean('MAIN', 'save_session'):\n interaction.save_session()\n\nif __name__ == \"__main__\":\n asyncio.run(main())"], ["/agenticSeek/sources/memory.py", "import time\nimport datetime\nimport uuid\nimport os\nimport sys\nimport json\nfrom typing import List, Tuple, Type, Dict\nimport torch\nfrom transformers import AutoTokenizer, AutoModelForSeq2SeqLM\nimport configparser\n\nfrom sources.utility import timer_decorator, pretty_print, animate_thinking\nfrom sources.logger import Logger\n\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\nclass Memory():\n \"\"\"\n Memory is a class for managing the conversation memory\n It provides a method to compress the memory using summarization model.\n \"\"\"\n def __init__(self, system_prompt: str,\n recover_last_session: bool = False,\n memory_compression: bool = True,\n model_provider: str = \"deepseek-r1:14b\"):\n self.memory = [{'role': 'system', 'content': system_prompt}]\n \n self.logger = Logger(\"memory.log\")\n self.session_time = datetime.datetime.now()\n self.session_id = str(uuid.uuid4())\n self.conversation_folder = f\"conversations/\"\n self.session_recovered = False\n if recover_last_session:\n self.load_memory()\n self.session_recovered = True\n # memory compression system\n self.model = None\n self.tokenizer = None\n self.device = self.get_cuda_device()\n self.memory_compression = memory_compression\n self.model_provider = model_provider\n if self.memory_compression:\n self.download_model()\n\n def get_ideal_ctx(self, model_name: str) -> int | None:\n \"\"\"\n Estimate context size based on the model name.\n EXPERIMENTAL for memory compression\n \"\"\"\n import re\n import math\n\n def extract_number_before_b(sentence: str) -> int:\n match = re.search(r'(\\d+)b', sentence, re.IGNORECASE)\n return int(match.group(1)) if match else None\n\n model_size = extract_number_before_b(model_name)\n if not model_size:\n return None\n base_size = 7 # Base model size in billions\n base_context = 4096 # Base context size in tokens\n scaling_factor = 1.5 # Approximate scaling factor for context size growth\n context_size = int(base_context * (model_size / base_size) ** scaling_factor)\n context_size = 2 ** round(math.log2(context_size))\n self.logger.info(f\"Estimated context size for {model_name}: {context_size} tokens.\")\n return context_size\n \n def download_model(self):\n \"\"\"Download the model if not already downloaded.\"\"\"\n animate_thinking(\"Loading memory compression model...\", color=\"status\")\n self.tokenizer = AutoTokenizer.from_pretrained(\"pszemraj/led-base-book-summary\")\n self.model = AutoModelForSeq2SeqLM.from_pretrained(\"pszemraj/led-base-book-summary\")\n self.logger.info(\"Memory compression system initialized.\")\n \n def get_filename(self) -> str:\n \"\"\"Get the filename for the save file.\"\"\"\n return f\"memory_{self.session_time.strftime('%Y-%m-%d_%H-%M-%S')}.txt\"\n \n def save_memory(self, agent_type: str = \"casual_agent\") -> None:\n \"\"\"Save the session memory to a file.\"\"\"\n if not os.path.exists(self.conversation_folder):\n self.logger.info(f\"Created folder {self.conversation_folder}.\")\n os.makedirs(self.conversation_folder)\n save_path = os.path.join(self.conversation_folder, agent_type)\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n filename = self.get_filename()\n path = os.path.join(save_path, filename)\n json_memory = json.dumps(self.memory)\n with open(path, 'w') as f:\n self.logger.info(f\"Saved memory json at {path}\")\n f.write(json_memory)\n \n def find_last_session_path(self, path) -> str:\n \"\"\"Find the last session path.\"\"\"\n saved_sessions = []\n for filename in os.listdir(path):\n if filename.startswith('memory_'):\n date = filename.split('_')[1]\n saved_sessions.append((filename, date))\n saved_sessions.sort(key=lambda x: x[1], reverse=True)\n if len(saved_sessions) > 0:\n self.logger.info(f\"Last session found at {saved_sessions[0][0]}\")\n return saved_sessions[0][0]\n return None\n \n def save_json_file(self, path: str, json_memory: dict) -> None:\n \"\"\"Save a JSON file.\"\"\"\n try:\n with open(path, 'w') as f:\n json.dump(json_memory, f)\n self.logger.info(f\"Saved memory json at {path}\")\n except Exception as e:\n self.logger.warning(f\"Error saving file {path}: {e}\")\n \n def load_json_file(self, path: str) -> dict:\n \"\"\"Load a JSON file.\"\"\"\n json_memory = {}\n try:\n with open(path, 'r') as f:\n json_memory = json.load(f)\n except FileNotFoundError:\n self.logger.warning(f\"File not found: {path}\")\n return {}\n except json.JSONDecodeError:\n self.logger.warning(f\"Error decoding JSON from file: {path}\")\n return {}\n except Exception as e:\n self.logger.warning(f\"Error loading file {path}: {e}\")\n return {}\n return json_memory\n\n def load_memory(self, agent_type: str = \"casual_agent\") -> None:\n \"\"\"Load the memory from the last session.\"\"\"\n if self.session_recovered == True:\n return\n pretty_print(f\"Loading {agent_type} past memories... \", color=\"status\")\n save_path = os.path.join(self.conversation_folder, agent_type)\n if not os.path.exists(save_path):\n pretty_print(\"No memory to load.\", color=\"success\")\n return\n filename = self.find_last_session_path(save_path)\n if filename is None:\n pretty_print(\"Last session memory not found.\", color=\"warning\")\n return\n path = os.path.join(save_path, filename)\n self.memory = self.load_json_file(path) \n if self.memory[-1]['role'] == 'user':\n self.memory.pop()\n self.compress()\n pretty_print(\"Session recovered successfully\", color=\"success\")\n \n def reset(self, memory: list = []) -> None:\n self.logger.info(\"Memory reset performed.\")\n self.memory = memory\n \n def push(self, role: str, content: str) -> int:\n \"\"\"Push a message to the memory.\"\"\"\n ideal_ctx = self.get_ideal_ctx(self.model_provider)\n if ideal_ctx is not None:\n if self.memory_compression and len(content) > ideal_ctx * 1.5:\n self.logger.info(f\"Compressing memory: Content {len(content)} > {ideal_ctx} model context.\")\n self.compress()\n curr_idx = len(self.memory)\n if self.memory[curr_idx-1]['content'] == content:\n pretty_print(\"Warning: same message have been pushed twice to memory\", color=\"error\")\n time_str = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n if config[\"MAIN\"][\"provider_name\"] == \"openrouter\":\n self.memory.append({'role': role, 'content': content})\n else:\n self.memory.append({'role': role, 'content': content, 'time': time_str, 'model_used': self.model_provider})\n return curr_idx-1\n \n def clear(self) -> None:\n \"\"\"Clear all memory except system prompt\"\"\"\n self.logger.info(\"Memory clear performed.\")\n self.memory = self.memory[:1]\n \n def clear_section(self, start: int, end: int) -> None:\n \"\"\"\n Clear a section of the memory. Ignore system message index.\n Args:\n start (int): Starting bound of the section to clear.\n end (int): Ending bound of the section to clear.\n \"\"\"\n self.logger.info(f\"Clearing memory section {start} to {end}.\")\n start = max(0, start) + 1\n end = min(end, len(self.memory)-1) + 2\n self.memory = self.memory[:start] + self.memory[end:]\n \n def get(self) -> list:\n return self.memory\n\n def get_cuda_device(self) -> str:\n if torch.backends.mps.is_available():\n return \"mps\"\n elif torch.cuda.is_available():\n return \"cuda\"\n else:\n return \"cpu\"\n\n def summarize(self, text: str, min_length: int = 64) -> str:\n \"\"\"\n Summarize the text using the AI model.\n Args:\n text (str): The text to summarize\n min_length (int, optional): The minimum length of the summary. Defaults to 64.\n Returns:\n str: The summarized text\n \"\"\"\n if self.tokenizer is None or self.model is None:\n self.logger.warning(\"No tokenizer or model to perform summarization.\")\n return text\n if len(text) < min_length*1.5:\n return text\n max_length = len(text) // 2 if len(text) > min_length*2 else min_length*2\n input_text = \"summarize: \" + text\n inputs = self.tokenizer(input_text, return_tensors=\"pt\", max_length=512, truncation=True)\n summary_ids = self.model.generate(\n inputs['input_ids'],\n max_length=max_length,\n min_length=min_length,\n length_penalty=1.0,\n num_beams=4,\n early_stopping=True\n )\n summary = self.tokenizer.decode(summary_ids[0], skip_special_tokens=True)\n summary.replace('summary:', '')\n self.logger.info(f\"Memory summarized from len {len(text)} to {len(summary)}.\")\n self.logger.info(f\"Summarized text:\\n{summary}\")\n return summary\n \n #@timer_decorator\n def compress(self) -> str:\n \"\"\"\n Compress (summarize) the memory using the model.\n \"\"\"\n if self.tokenizer is None or self.model is None:\n self.logger.warning(\"No tokenizer or model to perform memory compression.\")\n return\n for i in range(len(self.memory)):\n if self.memory[i]['role'] == 'system':\n continue\n if len(self.memory[i]['content']) > 1024:\n self.memory[i]['content'] = self.summarize(self.memory[i]['content'])\n \n def trim_text_to_max_ctx(self, text: str) -> str:\n \"\"\"\n Truncate a text to fit within the maximum context size of the model.\n \"\"\"\n ideal_ctx = self.get_ideal_ctx(self.model_provider)\n return text[:ideal_ctx] if ideal_ctx is not None else text\n \n #@timer_decorator\n def compress_text_to_max_ctx(self, text) -> str:\n \"\"\"\n Compress a text to fit within the maximum context size of the model.\n \"\"\"\n if self.tokenizer is None or self.model is None:\n self.logger.warning(\"No tokenizer or model to perform memory compression.\")\n return text\n ideal_ctx = self.get_ideal_ctx(self.model_provider)\n if ideal_ctx is None:\n self.logger.warning(\"No ideal context size found.\")\n return text\n while len(text) > ideal_ctx:\n self.logger.info(f\"Compressing text: {len(text)} > {ideal_ctx} model context.\")\n text = self.summarize(text)\n return text\n\nif __name__ == \"__main__\":\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n memory = Memory(\"You are a helpful assistant.\",\n recover_last_session=False, memory_compression=True)\n\n memory.push('user', \"hello\")\n memory.push('assistant', \"how can i help you?\")\n memory.push('user', \"why do i get this cuda error?\")\n sample_text = \"\"\"\nThe error you're encountering:\ncuda.cu:52:10: fatal error: helper_functions.h: No such file or directory\n #include \nindicates that the compiler cannot find the helper_functions.h file. This is because the #include directive is looking for the file in the system's include paths, but the file is either not in those paths or is located in a different directory.\n1. Use #include \"helper_functions.h\" Instead of #include \nAngle brackets (< >) are used for system or standard library headers.\nQuotes (\" \") are used for local or project-specific headers.\nIf helper_functions.h is in the same directory as cuda.cu, change the include directive to:\n3. Verify the File Exists\nDouble-check that helper_functions.h exists in the specified location. If the file is missing, you'll need to obtain or recreate it.\n4. Use the Correct CUDA Samples Path (if applicable)\nIf helper_functions.h is part of the CUDA Samples, ensure you have the CUDA Samples installed and include the correct path. For example, on Linux, the CUDA Samples are typically located in /usr/local/cuda/samples/common/inc. You can include this path like so:\nUse #include \"helper_functions.h\" for local files.\nUse the -I flag to specify the directory containing helper_functions.h.\nEnsure the file exists in the specified location.\n \"\"\"\n memory.push('assistant', sample_text)\n \n print(\"\\n---\\nmemory before:\", memory.get())\n memory.compress()\n print(\"\\n---\\nmemory after:\", memory.get())\n #memory.save_memory()\n "], ["/agenticSeek/sources/tools/tools.py", "\n\"\"\"\ndefine a generic tool class, any tool can be used by the agent.\n\nA tool can be used by a llm like so:\n```\n\n```\n\nwe call these \"blocks\".\n\nFor example:\n```python\nprint(\"Hello world\")\n```\nThis is then executed by the tool with its own class implementation of execute().\nA tool is not just for code tool but also API, internet search, MCP, etc..\n\"\"\"\n\nimport sys\nimport os\nimport configparser\nfrom abc import abstractmethod\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\nfrom sources.logger import Logger\n\nclass Tools():\n \"\"\"\n Abstract class for all tools.\n \"\"\"\n def __init__(self):\n self.tag = \"undefined\"\n self.name = \"undefined\"\n self.description = \"undefined\"\n self.client = None\n self.messages = []\n self.logger = Logger(\"tools.log\")\n self.config = configparser.ConfigParser()\n self.work_dir = self.create_work_dir()\n self.excutable_blocks_found = False\n self.safe_mode = False\n self.allow_language_exec_bash = False\n \n def get_work_dir(self):\n return self.work_dir\n \n def set_allow_language_exec_bash(self, value: bool) -> None:\n self.allow_language_exec_bash = value \n\n def safe_get_work_dir_path(self):\n path = None\n path = os.getenv('WORK_DIR', path)\n if path is None or path == \"\":\n path = self.config['MAIN']['work_dir'] if 'MAIN' in self.config and 'work_dir' in self.config['MAIN'] else None\n if path is None or path == \"\":\n print(\"No work directory specified, using default.\")\n path = self.create_work_dir()\n return path\n \n def config_exists(self):\n \"\"\"Check if the config file exists.\"\"\"\n return os.path.exists('./config.ini')\n\n def create_work_dir(self):\n \"\"\"Create the work directory if it does not exist.\"\"\"\n default_path = os.path.dirname(os.getcwd())\n if self.config_exists():\n self.config.read('./config.ini')\n workdir_path = self.safe_get_work_dir_path()\n else:\n workdir_path = default_path\n return workdir_path\n\n @abstractmethod\n def execute(self, blocks:[str], safety:bool) -> str:\n \"\"\"\n Abstract method that must be implemented by child classes to execute the tool's functionality.\n Args:\n blocks (List[str]): The codes or queries blocks to execute\n safety (bool): Whenever human intervention is required\n Returns:\n str: The output/result from executing the tool\n \"\"\"\n pass\n\n @abstractmethod\n def execution_failure_check(self, output:str) -> bool:\n \"\"\"\n Abstract method that must be implemented by child classes to check if tool execution failed.\n Args:\n output (str): The output string from the tool execution to analyze\n Returns:\n bool: True if execution failed, False if successful\n \"\"\"\n pass\n\n @abstractmethod\n def interpreter_feedback(self, output:str) -> str:\n \"\"\"\n Abstract method that must be implemented by child classes to provide feedback to the AI from the tool.\n Args:\n output (str): The output string from the tool execution to analyze\n Returns:\n str: The feedback message to the AI\n \"\"\"\n pass\n\n def save_block(self, blocks:[str], save_path:str) -> None:\n \"\"\"\n Save code or query blocks to a file at the specified path.\n Creates the directory path if it doesn't exist.\n Args:\n blocks (List[str]): List of code/query blocks to save\n save_path (str): File path where blocks should be saved\n \"\"\"\n if save_path is None:\n return\n self.logger.info(f\"Saving blocks to {save_path}\")\n save_path_dir = os.path.dirname(save_path)\n save_path_file = os.path.basename(save_path)\n directory = os.path.join(self.work_dir, save_path_dir)\n if directory and not os.path.exists(directory):\n self.logger.info(f\"Creating directory {directory}\")\n os.makedirs(directory)\n for block in blocks:\n with open(os.path.join(directory, save_path_file), 'w') as f:\n f.write(block)\n \n def get_parameter_value(self, block: str, parameter_name: str) -> str:\n \"\"\"\n Get a parameter name.\n Args:\n block (str): The block of text to search for the parameter\n parameter_name (str): The name of the parameter to retrieve\n Returns:\n str: The value of the parameter\n \"\"\"\n for param_line in block.split('\\n'):\n if parameter_name in param_line:\n param_value = param_line.split('=')[1].strip()\n return param_value\n return None\n \n def found_executable_blocks(self):\n \"\"\"\n Check if executable blocks were found.\n \"\"\"\n tmp = self.excutable_blocks_found\n self.excutable_blocks_found = False\n return tmp\n\n def load_exec_block(self, llm_text: str):\n \"\"\"\n Extract code/query blocks from LLM-generated text and process them for execution.\n This method parses the text looking for code blocks marked with the tool's tag (e.g. ```python).\n Args:\n llm_text (str): The raw text containing code blocks from the LLM\n Returns:\n tuple[list[str], str | None]: A tuple containing:\n - List of extracted and processed code blocks\n - The path the code blocks was saved to\n \"\"\"\n assert self.tag != \"undefined\", \"Tag not defined\"\n start_tag = f'```{self.tag}' \n end_tag = '```'\n code_blocks = []\n start_index = 0\n save_path = None\n\n if start_tag not in llm_text:\n return None, None\n\n while True:\n start_pos = llm_text.find(start_tag, start_index)\n if start_pos == -1:\n break\n\n line_start = llm_text.rfind('\\n', 0, start_pos)+1\n leading_whitespace = llm_text[line_start:start_pos]\n\n end_pos = llm_text.find(end_tag, start_pos + len(start_tag))\n if end_pos == -1:\n break\n content = llm_text[start_pos + len(start_tag):end_pos]\n lines = content.split('\\n')\n if leading_whitespace:\n processed_lines = []\n for line in lines:\n if line.startswith(leading_whitespace):\n processed_lines.append(line[len(leading_whitespace):])\n else:\n processed_lines.append(line)\n content = '\\n'.join(processed_lines)\n\n if ':' in content.split('\\n')[0]:\n save_path = content.split('\\n')[0].split(':')[1]\n content = content[content.find('\\n')+1:]\n self.excutable_blocks_found = True\n code_blocks.append(content)\n start_index = end_pos + len(end_tag)\n self.logger.info(f\"Found {len(code_blocks)} blocks to execute\")\n return code_blocks, save_path\n \nif __name__ == \"__main__\":\n tool = Tools()\n tool.tag = \"python\"\n rt = tool.load_exec_block(\"\"\"```python\nimport os\n\nfor file in os.listdir():\n if file.endswith('.py'):\n print(file)\n```\ngoodbye!\n \"\"\")\n print(rt)"], ["/agenticSeek/sources/tools/fileFinder.py", "import os, sys\nimport stat\nimport mimetypes\nimport configparser\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass FileFinder(Tools):\n \"\"\"\n A tool that finds files in the current directory and returns their information.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"file_finder\"\n self.name = \"File Finder\"\n self.description = \"Finds files in the current directory and returns their information.\"\n \n def read_file(self, file_path: str) -> str:\n \"\"\"\n Reads the content of a file.\n Args:\n file_path (str): The path to the file to read\n Returns:\n str: The content of the file\n \"\"\"\n try:\n with open(file_path, 'r') as file:\n return file.read()\n except Exception as e:\n return f\"Error reading file: {e}\"\n \n def read_arbitrary_file(self, file_path: str, file_type: str) -> str:\n \"\"\"\n Reads the content of a file with arbitrary encoding.\n Args:\n file_path (str): The path to the file to read\n Returns:\n str: The content of the file in markdown format\n \"\"\"\n mime_type, _ = mimetypes.guess_type(file_path)\n if mime_type:\n if mime_type.startswith(('image/', 'video/', 'audio/')):\n return \"can't read file type: image, video, or audio files are not supported.\"\n content_raw = self.read_file(file_path)\n if \"text\" in file_type:\n content = content_raw\n elif \"pdf\" in file_type:\n from pypdf import PdfReader\n reader = PdfReader(file_path)\n content = '\\n'.join([pt.extract_text() for pt in reader.pages])\n elif \"binary\" in file_type:\n content = content_raw.decode('utf-8', errors='replace')\n else:\n content = content_raw\n return content\n \n def get_file_info(self, file_path: str) -> str:\n \"\"\"\n Gets information about a file, including its name, path, type, content, and permissions.\n Args:\n file_path (str): The path to the file\n Returns:\n str: A dictionary containing the file information\n \"\"\"\n if os.path.exists(file_path):\n stats = os.stat(file_path)\n permissions = oct(stat.S_IMODE(stats.st_mode))\n file_type, _ = mimetypes.guess_type(file_path)\n file_type = file_type if file_type else \"Unknown\"\n content = self.read_arbitrary_file(file_path, file_type)\n \n result = {\n \"filename\": os.path.basename(file_path),\n \"path\": file_path,\n \"type\": file_type,\n \"read\": content,\n \"permissions\": permissions\n }\n return result\n else:\n return {\"filename\": file_path, \"error\": \"File not found\"}\n \n def recursive_search(self, directory_path: str, filename: str) -> str:\n \"\"\"\n Recursively searches for files in a directory and its subdirectories.\n Args:\n directory_path (str): The directory to search in\n filename (str): The filename to search for\n Returns:\n str | None: The path to the file if found, None otherwise\n \"\"\"\n file_path = None\n excluded_files = [\".pyc\", \".o\", \".so\", \".a\", \".lib\", \".dll\", \".dylib\", \".so\", \".git\"]\n for root, dirs, files in os.walk(directory_path):\n for f in files:\n if f is None:\n continue\n if any(excluded_file in f for excluded_file in excluded_files):\n continue\n if filename.strip() in f.strip():\n file_path = os.path.join(root, f)\n return file_path\n return None\n \n\n def execute(self, blocks: list, safety:bool = False) -> str:\n \"\"\"\n Executes the file finding operation for given filenames.\n Args:\n blocks (list): List of filenames to search for\n Returns:\n str: Results of the file search\n \"\"\"\n if not blocks or not isinstance(blocks, list):\n return \"Error: No valid filenames provided\"\n\n output = \"\"\n for block in blocks:\n filename = self.get_parameter_value(block, \"name\")\n action = self.get_parameter_value(block, \"action\")\n if filename is None:\n output = \"Error: No filename provided\\n\"\n return output\n if action is None:\n action = \"info\"\n print(\"File finder: recursive search started...\")\n file_path = self.recursive_search(self.work_dir, filename)\n if file_path is None:\n output = f\"File: {filename} - not found\\n\"\n continue\n result = self.get_file_info(file_path)\n if \"error\" in result:\n output += f\"File: {result['filename']} - {result['error']}\\n\"\n else:\n if action == \"read\":\n output += \"Content:\\n\" + result['read'] + \"\\n\"\n else:\n output += (f\"File: {result['filename']}, \"\n f\"found at {result['path']}, \"\n f\"File type {result['type']}\\n\")\n return output.strip()\n\n def execution_failure_check(self, output: str) -> bool:\n \"\"\"\n Checks if the file finding operation failed.\n Args:\n output (str): The output string from execute()\n Returns:\n bool: True if execution failed, False if successful\n \"\"\"\n if not output:\n return True\n if \"Error\" in output or \"not found\" in output:\n return True\n return False\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Provides feedback about the file finding operation.\n Args:\n output (str): The output string from execute()\n Returns:\n str: Feedback message for the AI\n \"\"\"\n if not output:\n return \"No output generated from file finder tool\"\n \n feedback = \"File Finder Results:\\n\"\n \n if \"Error\" in output or \"not found\" in output:\n feedback += f\"Failed to process: {output}\\n\"\n else:\n feedback += f\"Successfully found: {output}\\n\"\n return feedback.strip()\n\nif __name__ == \"__main__\":\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n tool = FileFinder()\n result = tool.execute([\"\"\"\naction=read\nname=tools.py\n\"\"\"], False)\n print(\"Execution result:\")\n print(result)\n print(\"\\nFailure check:\", tool.execution_failure_check(result))\n print(\"\\nFeedback:\")\n print(tool.interpreter_feedback(result))"], ["/agenticSeek/sources/llm_provider.py", "import os\nimport platform\nimport socket\nimport subprocess\nimport time\nfrom urllib.parse import urlparse\n\nimport httpx\nimport requests\nfrom dotenv import load_dotenv\nfrom ollama import Client as OllamaClient\nfrom openai import OpenAI\n\nfrom sources.logger import Logger\nfrom sources.utility import pretty_print, animate_thinking\n\nclass Provider:\n def __init__(self, provider_name, model, server_address=\"127.0.0.1:5000\", is_local=False):\n self.provider_name = provider_name.lower()\n self.model = model\n self.is_local = is_local\n self.server_ip = server_address\n self.server_address = server_address\n self.available_providers = {\n \"ollama\": self.ollama_fn,\n \"server\": self.server_fn,\n \"openai\": self.openai_fn,\n \"lm-studio\": self.lm_studio_fn,\n \"huggingface\": self.huggingface_fn,\n \"google\": self.google_fn,\n \"deepseek\": self.deepseek_fn,\n \"together\": self.together_fn,\n \"dsk_deepseek\": self.dsk_deepseek,\n \"openrouter\": self.openrouter_fn,\n \"test\": self.test_fn\n }\n self.logger = Logger(\"provider.log\")\n self.api_key = None\n self.internal_url, self.in_docker = self.get_internal_url()\n self.unsafe_providers = [\"openai\", \"deepseek\", \"dsk_deepseek\", \"together\", \"google\", \"openrouter\"]\n if self.provider_name not in self.available_providers:\n raise ValueError(f\"Unknown provider: {provider_name}\")\n if self.provider_name in self.unsafe_providers and self.is_local == False:\n pretty_print(\"Warning: you are using an API provider. You data will be sent to the cloud.\", color=\"warning\")\n self.api_key = self.get_api_key(self.provider_name)\n elif self.provider_name != \"ollama\":\n pretty_print(f\"Provider: {provider_name} initialized at {self.server_ip}\", color=\"success\")\n\n def get_model_name(self) -> str:\n return self.model\n\n def get_api_key(self, provider):\n load_dotenv()\n api_key_var = f\"{provider.upper()}_API_KEY\"\n api_key = os.getenv(api_key_var)\n if not api_key:\n pretty_print(f\"API key {api_key_var} not found in .env file. Please add it\", color=\"warning\")\n exit(1)\n return api_key\n \n def get_internal_url(self):\n load_dotenv()\n url = os.getenv(\"DOCKER_INTERNAL_URL\")\n if not url: # running on host\n return \"http://localhost\", False\n return url, True\n\n def respond(self, history, verbose=True):\n \"\"\"\n Use the choosen provider to generate text.\n \"\"\"\n llm = self.available_providers[self.provider_name]\n self.logger.info(f\"Using provider: {self.provider_name} at {self.server_ip}\")\n try:\n thought = llm(history, verbose)\n except KeyboardInterrupt:\n self.logger.warning(\"User interrupted the operation with Ctrl+C\")\n return \"Operation interrupted by user. REQUEST_EXIT\"\n except ConnectionError as e:\n raise ConnectionError(f\"{str(e)}\\nConnection to {self.server_ip} failed.\")\n except AttributeError as e:\n raise NotImplementedError(f\"{str(e)}\\nIs {self.provider_name} implemented ?\")\n except ModuleNotFoundError as e:\n raise ModuleNotFoundError(\n f\"{str(e)}\\nA import related to provider {self.provider_name} was not found. Is it installed ?\")\n except Exception as e:\n if \"try again later\" in str(e).lower():\n return f\"{self.provider_name} server is overloaded. Please try again later.\"\n if \"refused\" in str(e):\n return f\"Server {self.server_ip} seem offline. Unable to answer.\"\n raise Exception(f\"Provider {self.provider_name} failed: {str(e)}\") from e\n return thought\n\n def is_ip_online(self, address: str, timeout: int = 10) -> bool:\n \"\"\"\n Check if an address is online by sending a ping request.\n \"\"\"\n if not address:\n return False\n parsed = urlparse(address if address.startswith(('http://', 'https://')) else f'http://{address}')\n\n hostname = parsed.hostname or address\n if \"127.0.0.1\" in address or \"localhost\" in address:\n return True\n try:\n ip_address = socket.gethostbyname(hostname)\n except socket.gaierror:\n self.logger.error(f\"Cannot resolve: {hostname}\")\n return False\n param = '-n' if platform.system().lower() == 'windows' else '-c'\n command = ['ping', param, '1', ip_address]\n try:\n result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)\n return result.returncode == 0\n except (subprocess.TimeoutExpired, subprocess.SubprocessError) as e:\n return False\n\n def server_fn(self, history, verbose=False):\n \"\"\"\n Use a remote server with LLM to generate text.\n \"\"\"\n thought = \"\"\n route_setup = f\"{self.server_ip}/setup\"\n route_gen = f\"{self.server_ip}/generate\"\n\n if not self.is_ip_online(self.server_ip):\n pretty_print(f\"Server is offline at {self.server_ip}\", color=\"failure\")\n\n try:\n requests.post(route_setup, json={\"model\": self.model})\n requests.post(route_gen, json={\"messages\": history})\n is_complete = False\n while not is_complete:\n try:\n response = requests.get(f\"{self.server_ip}/get_updated_sentence\")\n if \"error\" in response.json():\n pretty_print(response.json()[\"error\"], color=\"failure\")\n break\n thought = response.json()[\"sentence\"]\n is_complete = bool(response.json()[\"is_complete\"])\n time.sleep(2)\n except requests.exceptions.RequestException as e:\n pretty_print(f\"HTTP request failed: {str(e)}\", color=\"failure\")\n break\n except ValueError as e:\n pretty_print(f\"Failed to parse JSON response: {str(e)}\", color=\"failure\")\n break\n except Exception as e:\n pretty_print(f\"An error occurred: {str(e)}\", color=\"failure\")\n break\n except KeyError as e:\n raise Exception(\n f\"{str(e)}\\nError occured with server route. Are you using the correct address for the config.ini provider?\") from e\n except Exception as e:\n raise e\n return thought\n\n def ollama_fn(self, history, verbose=False):\n \"\"\"\n Use local or remote Ollama server to generate text.\n \"\"\"\n thought = \"\"\n host = f\"{self.internal_url}:11434\" if self.is_local else f\"http://{self.server_address}\"\n client = OllamaClient(host=host)\n\n try:\n stream = client.chat(\n model=self.model,\n messages=history,\n stream=True,\n )\n for chunk in stream:\n if verbose:\n print(chunk[\"message\"][\"content\"], end=\"\", flush=True)\n thought += chunk[\"message\"][\"content\"]\n except httpx.ConnectError as e:\n raise Exception(\n f\"\\nOllama connection failed at {host}. Check if the server is running.\"\n ) from e\n except Exception as e:\n if hasattr(e, 'status_code') and e.status_code == 404:\n animate_thinking(f\"Downloading {self.model}...\")\n client.pull(self.model)\n self.ollama_fn(history, verbose)\n if \"refused\" in str(e).lower():\n raise Exception(\n f\"Ollama connection refused at {host}. Is the server running?\"\n ) from e\n raise e\n\n return thought\n\n def huggingface_fn(self, history, verbose=False):\n \"\"\"\n Use huggingface to generate text.\n \"\"\"\n from huggingface_hub import InferenceClient\n client = InferenceClient(\n api_key=self.get_api_key(\"huggingface\")\n )\n completion = client.chat.completions.create(\n model=self.model,\n messages=history,\n max_tokens=1024,\n )\n thought = completion.choices[0].message\n return thought.content\n\n def openai_fn(self, history, verbose=False):\n \"\"\"\n Use openai to generate text.\n \"\"\"\n base_url = self.server_ip\n if self.is_local and self.in_docker:\n try:\n host, port = base_url.split(':')\n except Exception as e:\n port = \"8000\"\n client = OpenAI(api_key=self.api_key, base_url=f\"{self.internal_url}:{port}\")\n elif self.is_local:\n client = OpenAI(api_key=self.api_key, base_url=f\"http://{base_url}\")\n else:\n client = OpenAI(api_key=self.api_key)\n\n try:\n response = client.chat.completions.create(\n model=self.model,\n messages=history,\n )\n if response is None:\n raise Exception(\"OpenAI response is empty.\")\n thought = response.choices[0].message.content\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"OpenAI API error: {str(e)}\") from e\n\n def anthropic_fn(self, history, verbose=False):\n \"\"\"\n Use Anthropic to generate text.\n \"\"\"\n from anthropic import Anthropic\n\n client = Anthropic(api_key=self.api_key)\n system_message = None\n messages = []\n for message in history:\n clean_message = {'role': message['role'], 'content': message['content']}\n if message['role'] == 'system':\n system_message = message['content']\n else:\n messages.append(clean_message)\n\n try:\n response = client.messages.create(\n model=self.model,\n max_tokens=1024,\n messages=messages,\n system=system_message\n )\n if response is None:\n raise Exception(\"Anthropic response is empty.\")\n thought = response.content[0].text\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"Anthropic API error: {str(e)}\") from e\n\n def google_fn(self, history, verbose=False):\n \"\"\"\n Use google gemini to generate text.\n \"\"\"\n base_url = self.server_ip\n if self.is_local:\n raise Exception(\"Google Gemini is not available for local use. Change config.ini\")\n\n client = OpenAI(api_key=self.api_key, base_url=\"https://generativelanguage.googleapis.com/v1beta/openai/\")\n try:\n response = client.chat.completions.create(\n model=self.model,\n messages=history,\n )\n if response is None:\n raise Exception(\"Google response is empty.\")\n thought = response.choices[0].message.content\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"GOOGLE API error: {str(e)}\") from e\n\n def together_fn(self, history, verbose=False):\n \"\"\"\n Use together AI for completion\n \"\"\"\n from together import Together\n client = Together(api_key=self.api_key)\n if self.is_local:\n raise Exception(\"Together AI is not available for local use. Change config.ini\")\n\n try:\n response = client.chat.completions.create(\n model=self.model,\n messages=history,\n )\n if response is None:\n raise Exception(\"Together AI response is empty.\")\n thought = response.choices[0].message.content\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"Together AI API error: {str(e)}\") from e\n\n def deepseek_fn(self, history, verbose=False):\n \"\"\"\n Use deepseek api to generate text.\n \"\"\"\n client = OpenAI(api_key=self.api_key, base_url=\"https://api.deepseek.com\")\n if self.is_local:\n raise Exception(\"Deepseek (API) is not available for local use. Change config.ini\")\n try:\n response = client.chat.completions.create(\n model=\"deepseek-chat\",\n messages=history,\n stream=False\n )\n thought = response.choices[0].message.content\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"Deepseek API error: {str(e)}\") from e\n\n def lm_studio_fn(self, history, verbose=False):\n \"\"\"\n Use local lm-studio server to generate text.\n \"\"\"\n if self.in_docker:\n # Extract port from server_address if present\n port = \"1234\" # default\n if \":\" in self.server_address:\n port = self.server_address.split(\":\")[1]\n url = f\"{self.internal_url}:{port}\"\n else:\n url = f\"http://{self.server_ip}\"\n route_start = f\"{url}/v1/chat/completions\"\n payload = {\n \"messages\": history,\n \"temperature\": 0.7,\n \"max_tokens\": 4096,\n \"model\": self.model\n }\n\n try:\n response = requests.post(route_start, json=payload, timeout=30)\n if response.status_code != 200:\n raise Exception(f\"LM Studio returned status {response.status_code}: {response.text}\")\n if not response.text.strip():\n raise Exception(\"LM Studio returned empty response\")\n try:\n result = response.json()\n except ValueError as json_err:\n raise Exception(f\"Invalid JSON from LM Studio: {response.text[:200]}\") from json_err\n\n if verbose:\n print(\"Response from LM Studio:\", result)\n choices = result.get(\"choices\", [])\n if not choices:\n raise Exception(f\"No choices in LM Studio response: {result}\")\n\n message = choices[0].get(\"message\", {})\n content = message.get(\"content\", \"\")\n if not content:\n raise Exception(f\"Empty content in LM Studio response: {result}\")\n return content\n\n except requests.exceptions.Timeout:\n raise Exception(\"LM Studio request timed out - check if server is responsive\")\n except requests.exceptions.ConnectionError:\n raise Exception(f\"Cannot connect to LM Studio at {route_start} - check if server is running\")\n except requests.exceptions.RequestException as e:\n raise Exception(f\"HTTP request failed: {str(e)}\") from e\n except Exception as e:\n if \"LM Studio\" in str(e):\n raise # Re-raise our custom exceptions\n raise Exception(f\"Unexpected error: {str(e)}\") from e\n return thought\n\n def openrouter_fn(self, history, verbose=False):\n \"\"\"\n Use OpenRouter API to generate text.\n \"\"\"\n client = OpenAI(api_key=self.api_key, base_url=\"https://openrouter.ai/api/v1\")\n if self.is_local:\n # This case should ideally not be reached if unsafe_providers is set correctly\n # and is_local is False in config for openrouter\n raise Exception(\"OpenRouter is not available for local use. Change config.ini\")\n try:\n response = client.chat.completions.create(\n model=self.model,\n messages=history,\n )\n if response is None:\n raise Exception(\"OpenRouter response is empty.\")\n thought = response.choices[0].message.content\n if verbose:\n print(thought)\n return thought\n except Exception as e:\n raise Exception(f\"OpenRouter API error: {str(e)}\") from e\n\n def dsk_deepseek(self, history, verbose=False):\n \"\"\"\n Use: xtekky/deepseek4free\n For free api. Api key should be set to DSK_DEEPSEEK_API_KEY\n This is an unofficial provider, you'll have to find how to set it up yourself.\n \"\"\"\n from dsk.api import (\n DeepSeekAPI,\n AuthenticationError,\n RateLimitError,\n NetworkError,\n CloudflareError,\n APIError\n )\n thought = \"\"\n message = '\\n---\\n'.join([f\"{msg['role']}: {msg['content']}\" for msg in history])\n\n try:\n api = DeepSeekAPI(self.api_key)\n chat_id = api.create_chat_session()\n for chunk in api.chat_completion(chat_id, message):\n if chunk['type'] == 'text':\n thought += chunk['content']\n return thought\n except AuthenticationError:\n raise AuthenticationError(\"Authentication failed. Please check your token.\") from e\n except RateLimitError:\n raise RateLimitError(\"Rate limit exceeded. Please wait before making more requests.\") from e\n except CloudflareError as e:\n raise CloudflareError(f\"Cloudflare protection encountered: {str(e)}\") from e\n except NetworkError:\n raise NetworkError(\"Network error occurred. Check your internet connection.\") from e\n except APIError as e:\n raise APIError(f\"API error occurred: {str(e)}\") from e\n return None\n\n def test_fn(self, history, verbose=True):\n \"\"\"\n This function is used to conduct tests.\n \"\"\"\n thought = \"\"\"\n\\n\\n```json\\n{\\n \\\"plan\\\": [\\n {\\n \\\"agent\\\": \\\"Web\\\",\\n \\\"id\\\": \\\"1\\\",\\n \\\"need\\\": null,\\n \\\"task\\\": \\\"Conduct a comprehensive web search to identify at least five AI startups located in Osaka. Use reliable sources and websites such as Crunchbase, TechCrunch, or local Japanese business directories. Capture the company names, their websites, areas of expertise, and any other relevant details.\\\"\\n },\\n {\\n \\\"agent\\\": \\\"Web\\\",\\n \\\"id\\\": \\\"2\\\",\\n \\\"need\\\": null,\\n \\\"task\\\": \\\"Perform a similar search to find at least five AI startups in Tokyo. Again, use trusted sources like Crunchbase, TechCrunch, or Japanese business news websites. Gather the same details as for Osaka: company names, websites, areas of focus, and additional information.\\\"\\n },\\n {\\n \\\"agent\\\": \\\"File\\\",\\n \\\"id\\\": \\\"3\\\",\\n \\\"need\\\": [\\\"1\\\", \\\"2\\\"],\\n \\\"task\\\": \\\"Create a new text file named research_japan.txt in the user's home directory. Organize the data collected from both searches into this file, ensuring it is well-structured and formatted for readability. Include headers for Osaka and Tokyo sections, followed by the details of each startup found.\\\"\\n }\\n ]\\n}\\n```\n \"\"\"\n return thought\n\n\nif __name__ == \"__main__\":\n provider = Provider(\"server\", \"deepseek-r1:32b\", \" x.x.x.x:8080\")\n res = provider.respond([\"user\", \"Hello, how are you?\"])\n print(\"Response:\", res)\n"], ["/agenticSeek/sources/browser.py", "from selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException, WebDriverException\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom typing import List, Tuple, Type, Dict\nfrom bs4 import BeautifulSoup\nfrom urllib.parse import urlparse\nfrom fake_useragent import UserAgent\nfrom selenium_stealth import stealth\nimport undetected_chromedriver as uc\nimport chromedriver_autoinstaller\nimport certifi\nimport ssl\nimport time\nimport random\nimport os\nimport shutil\nimport uuid\nimport tempfile\nimport markdownify\nimport sys\nimport re\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.logger import Logger\n\n\ndef get_chrome_path() -> str:\n \"\"\"Get the path to the Chrome executable.\"\"\"\n if sys.platform.startswith(\"win\"):\n paths = [\n \"C:\\\\Program Files\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe\",\n \"C:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe\",\n os.path.join(os.environ.get(\"LOCALAPPDATA\", \"\"), \"Google\\\\Chrome\\\\Application\\\\chrome.exe\") # User install\n ]\n elif sys.platform.startswith(\"darwin\"): # macOS\n paths = [\"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome\",\n \"/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta\"]\n else: # Linux\n paths = [\"/usr/bin/google-chrome\",\n \"/opt/chrome/chrome\",\n \"/usr/bin/chromium-browser\",\n \"/usr/bin/chromium\",\n \"/usr/local/bin/chrome\",\n \"/opt/google/chrome/chrome-headless-shell\",\n #\"/app/chrome_bundle/chrome136/chrome-linux64\"\n ]\n\n for path in paths:\n if os.path.exists(path) and os.access(path, os.X_OK):\n return path\n print(\"Looking for Google Chrome in these locations failed:\")\n print('\\n'.join(paths))\n chrome_path_env = os.environ.get(\"CHROME_EXECUTABLE_PATH\")\n if chrome_path_env and os.path.exists(chrome_path_env) and os.access(chrome_path_env, os.X_OK):\n return chrome_path_env\n path = input(\"Google Chrome not found. Please enter the path to the Chrome executable: \")\n if os.path.exists(path) and os.access(path, os.X_OK):\n os.environ[\"CHROME_EXECUTABLE_PATH\"] = path\n print(f\"Chrome path saved to environment variable CHROME_EXECUTABLE_PATH\")\n return path\n return None\n\ndef get_random_user_agent() -> str:\n \"\"\"Get a random user agent string with associated vendor.\"\"\"\n user_agents = [\n {\"ua\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36\", \"vendor\": \"Google Inc.\"},\n {\"ua\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 14_6_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36\", \"vendor\": \"Apple Inc.\"},\n {\"ua\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36\", \"vendor\": \"Google Inc.\"},\n ]\n return random.choice(user_agents)\n\ndef install_chromedriver() -> str:\n \"\"\"\n Install the ChromeDriver if not already installed. Return the path.\n \"\"\"\n # First try to use chromedriver in the project root directory (as per README)\n project_root_chromedriver = \"./chromedriver\"\n if os.path.exists(project_root_chromedriver) and os.access(project_root_chromedriver, os.X_OK):\n print(f\"Using ChromeDriver from project root: {project_root_chromedriver}\")\n return project_root_chromedriver\n \n # Then try to use the system-installed chromedriver\n chromedriver_path = shutil.which(\"chromedriver\")\n if chromedriver_path:\n return chromedriver_path\n \n # In Docker environment, try the fixed path\n if os.path.exists('/.dockerenv'):\n docker_chromedriver_path = \"/usr/local/bin/chromedriver\"\n if os.path.exists(docker_chromedriver_path) and os.access(docker_chromedriver_path, os.X_OK):\n print(f\"Using Docker ChromeDriver at {docker_chromedriver_path}\")\n return docker_chromedriver_path\n \n # Fallback to auto-installer only if no other option works\n try:\n print(\"ChromeDriver not found, attempting to install automatically...\")\n chromedriver_path = chromedriver_autoinstaller.install()\n except Exception as e:\n raise FileNotFoundError(\n \"ChromeDriver not found and could not be installed automatically. \"\n \"Please install it manually from https://chromedriver.chromium.org/downloads.\"\n \"and ensure it's in your PATH or specify the path directly.\"\n \"See know issues in readme if your chrome version is above 115.\"\n ) from e\n \n if not chromedriver_path:\n raise FileNotFoundError(\"ChromeDriver not found. Please install it or add it to your PATH.\")\n return chromedriver_path\n\ndef bypass_ssl() -> str:\n \"\"\"\n This is a fallback for stealth mode to bypass SSL verification. Which can fail on some setup.\n \"\"\"\n pretty_print(\"Bypassing SSL verification issues, we strongly advice you update your certifi SSL certificate.\", color=\"warning\")\n ssl._create_default_https_context = ssl._create_unverified_context\n\ndef create_undetected_chromedriver(service, chrome_options) -> webdriver.Chrome:\n \"\"\"Create an undetected ChromeDriver instance.\"\"\"\n try:\n driver = uc.Chrome(service=service, options=chrome_options)\n except Exception as e:\n pretty_print(f\"Failed to create Chrome driver: {str(e)}. Trying to bypass SSL...\", color=\"failure\")\n try:\n bypass_ssl()\n driver = uc.Chrome(service=service, options=chrome_options)\n except Exception as e:\n pretty_print(f\"Failed to create Chrome driver, fallback failed:\\n{str(e)}.\", color=\"failure\")\n raise e\n raise e\n driver.execute_script(\"Object.defineProperty(navigator, 'webdriver', {get: () => undefined})\") \n return driver\n\ndef create_driver(headless=False, stealth_mode=True, crx_path=\"./crx/nopecha.crx\", lang=\"en\") -> webdriver.Chrome:\n \"\"\"Create a Chrome WebDriver with specified options.\"\"\"\n # Warn if trying to run non-headless in Docker\n if not headless and os.path.exists('/.dockerenv'):\n print(\"[WARNING] Running non-headless browser in Docker may fail!\")\n print(\"[WARNING] Consider setting headless=True or headless_browser=True in config.ini\")\n \n chrome_options = Options()\n chrome_path = get_chrome_path()\n \n if not chrome_path:\n raise FileNotFoundError(\"Google Chrome not found. Please install it.\")\n chrome_options.binary_location = chrome_path\n \n if headless:\n #chrome_options.add_argument(\"--headless\")\n chrome_options.add_argument(\"--headless=new\")\n chrome_options.add_argument(\"--disable-gpu\")\n chrome_options.add_argument(\"--disable-webgl\")\n user_data_dir = tempfile.mkdtemp()\n user_agent = get_random_user_agent()\n width, height = (1920, 1080)\n user_data_dir = tempfile.mkdtemp(prefix=\"chrome_profile_\")\n chrome_options.add_argument(\"--no-sandbox\")\n chrome_options.add_argument('--disable-dev-shm-usage')\n profile_dir = f\"/tmp/chrome_profile_{uuid.uuid4().hex[:8]}\"\n chrome_options.add_argument(f'--user-data-dir={profile_dir}')\n chrome_options.add_argument(f\"--accept-lang={lang}-{lang.upper()},{lang};q=0.9\")\n chrome_options.add_argument(\"--disable-extensions\")\n chrome_options.add_argument(\"--disable-background-timer-throttling\")\n chrome_options.add_argument(\"--timezone=Europe/Paris\")\n chrome_options.add_argument('--remote-debugging-port=9222')\n chrome_options.add_argument('--disable-background-timer-throttling')\n chrome_options.add_argument('--disable-backgrounding-occluded-windows')\n chrome_options.add_argument('--disable-renderer-backgrounding')\n chrome_options.add_argument('--disable-features=TranslateUI')\n chrome_options.add_argument('--disable-ipc-flooding-protection')\n chrome_options.add_argument(\"--mute-audio\")\n chrome_options.add_argument(\"--disable-notifications\")\n chrome_options.add_argument(\"--autoplay-policy=user-gesture-required\")\n chrome_options.add_argument(\"--disable-features=SitePerProcess,IsolateOrigins\")\n chrome_options.add_argument(\"--enable-features=NetworkService,NetworkServiceInProcess\")\n chrome_options.add_argument(\"--disable-blink-features=AutomationControlled\")\n chrome_options.add_argument(f'user-agent={user_agent[\"ua\"]}')\n chrome_options.add_argument(f'--window-size={width},{height}')\n if not stealth_mode:\n if not os.path.exists(crx_path):\n pretty_print(f\"Anti-captcha CRX not found at {crx_path}.\", color=\"failure\")\n else:\n chrome_options.add_extension(crx_path)\n\n chromedriver_path = install_chromedriver()\n\n service = Service(chromedriver_path)\n if stealth_mode:\n chrome_options.add_argument(\"--disable-blink-features=AutomationControlled\")\n driver = create_undetected_chromedriver(service, chrome_options)\n chrome_version = driver.capabilities['browserVersion']\n stealth(driver,\n languages=[\"en-US\", \"en\"],\n vendor=user_agent[\"vendor\"],\n platform=\"Win64\" if \"windows\" in user_agent[\"ua\"].lower() else \"MacIntel\" if \"mac\" in user_agent[\"ua\"].lower() else \"Linux x86_64\",\n webgl_vendor=\"Intel Inc.\",\n renderer=\"Intel Iris OpenGL Engine\",\n fix_hairline=True,\n )\n return driver\n security_prefs = {\n \"profile.default_content_setting_values.geolocation\": 0,\n \"profile.default_content_setting_values.notifications\": 0,\n \"profile.default_content_setting_values.camera\": 0,\n \"profile.default_content_setting_values.microphone\": 0,\n \"profile.default_content_setting_values.midi_sysex\": 0,\n \"profile.default_content_setting_values.clipboard\": 0,\n \"profile.default_content_setting_values.media_stream\": 0,\n \"profile.default_content_setting_values.background_sync\": 0,\n \"profile.default_content_setting_values.sensors\": 0,\n \"profile.default_content_setting_values.accessibility_events\": 0,\n \"safebrowsing.enabled\": True,\n \"credentials_enable_service\": False,\n \"profile.password_manager_enabled\": False,\n \"webkit.webprefs.accelerated_2d_canvas_enabled\": True,\n \"webkit.webprefs.force_dark_mode_enabled\": False,\n \"webkit.webprefs.accelerated_2d_canvas_msaa_sample_count\": 4,\n \"enable_webgl\": True,\n \"enable_webgl2_compute_context\": True\n }\n chrome_options.add_experimental_option(\"prefs\", security_prefs)\n chrome_options.add_experimental_option(\"excludeSwitches\", [\"enable-automation\"])\n chrome_options.add_experimental_option('useAutomationExtension', False)\n return webdriver.Chrome(service=service, options=chrome_options)\n\nclass Browser:\n def __init__(self, driver, anticaptcha_manual_install=False):\n \"\"\"Initialize the browser with optional AntiCaptcha installation.\"\"\"\n self.js_scripts_folder = \"./sources/web_scripts/\" if not __name__ == \"__main__\" else \"./web_scripts/\"\n self.anticaptcha = \"https://chrome.google.com/webstore/detail/nopecha-captcha-solver/dknlfmjaanfblgfdfebhijalfmhmjjjo/related\"\n self.logger = Logger(\"browser.log\")\n self.screenshot_folder = os.path.join(os.getcwd(), \".screenshots\")\n self.tabs = []\n try:\n self.driver = driver\n self.wait = WebDriverWait(self.driver, 10)\n except Exception as e:\n raise Exception(f\"Failed to initialize browser: {str(e)}\")\n self.setup_tabs()\n self.patch_browser_fingerprint()\n if anticaptcha_manual_install:\n self.load_anticatpcha_manually()\n \n def setup_tabs(self):\n self.tabs = self.driver.window_handles\n try:\n self.driver.get(\"https://www.google.com\")\n except Exception as e:\n self.logger.log(f\"Failed to setup initial tab:\" + str(e))\n pass\n self.screenshot()\n \n def switch_control_tab(self):\n self.logger.log(\"Switching to control tab.\")\n self.driver.switch_to.window(self.tabs[0])\n \n def load_anticatpcha_manually(self):\n pretty_print(\"You might want to install the AntiCaptcha extension for captchas.\", color=\"warning\")\n try:\n self.driver.get(self.anticaptcha)\n except Exception as e:\n self.logger.log(f\"Failed to setup initial tab:\" + str(e))\n pass\n\n def human_move(element):\n actions = ActionChains(driver)\n x_offset = random.randint(-5,5)\n for _ in range(random.randint(2,5)):\n actions.move_by_offset(x_offset, random.randint(-2,2))\n actions.pause(random.uniform(0.1,0.3))\n actions.click().perform()\n\n def human_scroll(self):\n for _ in range(random.randint(1, 3)):\n scroll_pixels = random.randint(150, 1200)\n self.driver.execute_script(f\"window.scrollBy(0, {scroll_pixels});\")\n time.sleep(random.uniform(0.5, 2.0))\n if random.random() < 0.4:\n self.driver.execute_script(f\"window.scrollBy(0, -{random.randint(50, 300)});\")\n time.sleep(random.uniform(0.3, 1.0))\n\n def patch_browser_fingerprint(self) -> None:\n script = self.load_js(\"spoofing.js\")\n self.driver.execute_script(script)\n \n def go_to(self, url:str) -> bool:\n \"\"\"Navigate to a specified URL.\"\"\"\n time.sleep(random.uniform(0.4, 2.5))\n try:\n initial_handles = self.driver.window_handles\n self.driver.get(url)\n time.sleep(random.uniform(0.01, 0.3))\n try:\n wait = WebDriverWait(self.driver, timeout=10)\n wait.until(\n lambda driver: (\n not any(keyword in driver.page_source.lower() for keyword in [\"checking your browser\", \"captcha\"])\n ),\n message=\"stuck on 'checking browser' or verification screen\"\n )\n except TimeoutException:\n self.logger.warning(\"Timeout while waiting for page to bypass 'checking your browser'\")\n self.apply_web_safety()\n time.sleep(random.uniform(0.01, 0.2))\n self.human_scroll()\n self.logger.log(f\"Navigated to: {url}\")\n return True\n except TimeoutException as e:\n self.logger.error(f\"Timeout waiting for {url} to load: {str(e)}\")\n return False\n except WebDriverException as e:\n self.logger.error(f\"Error navigating to {url}: {str(e)}\")\n return False\n except Exception as e:\n self.logger.error(f\"Fatal error with go_to method on {url}:\\n{str(e)}\")\n raise e\n\n def is_sentence(self, text:str) -> bool:\n \"\"\"Check if the text qualifies as a meaningful sentence or contains important error codes.\"\"\"\n text = text.strip()\n\n if any(c.isdigit() for c in text):\n return True\n words = re.findall(r'\\w+', text, re.UNICODE)\n word_count = len(words)\n has_punctuation = any(text.endswith(p) for p in ['.', ',', ',', '!', '?', '。', '!', '?', '।', '۔'])\n is_long_enough = word_count > 4\n return (word_count >= 5 and (has_punctuation or is_long_enough))\n\n def get_text(self) -> str | None:\n \"\"\"Get page text as formatted Markdown\"\"\"\n try:\n soup = BeautifulSoup(self.driver.page_source, 'html.parser')\n for element in soup(['script', 'style', 'noscript', 'meta', 'link']):\n element.decompose()\n markdown_converter = markdownify.MarkdownConverter(\n heading_style=\"ATX\",\n strip=['a'],\n autolinks=False,\n bullets='•',\n strong_em_symbol='*',\n default_title=False,\n )\n markdown_text = markdown_converter.convert(str(soup.body))\n lines = []\n for line in markdown_text.splitlines():\n stripped = line.strip()\n if stripped and self.is_sentence(stripped):\n cleaned = ' '.join(stripped.split())\n lines.append(cleaned)\n result = \"[Start of page]\\n\\n\" + \"\\n\\n\".join(lines) + \"\\n\\n[End of page]\"\n result = re.sub(r'!\\[(.*?)\\]\\(.*?\\)', r'[IMAGE: \\1]', result)\n self.logger.info(f\"Extracted text: {result[:100]}...\")\n self.logger.info(f\"Extracted text length: {len(result)}\")\n return result[:32768]\n except Exception as e:\n self.logger.error(f\"Error getting text: {str(e)}\")\n return None\n \n def clean_url(self, url:str) -> str:\n \"\"\"Clean URL to keep only the part needed for navigation to the page\"\"\"\n clean = url.split('#')[0]\n parts = clean.split('?', 1)\n base_url = parts[0]\n if len(parts) > 1:\n query = parts[1]\n essential_params = []\n for param in query.split('&'):\n if param.startswith('_skw=') or param.startswith('q=') or param.startswith('s='):\n essential_params.append(param)\n elif param.startswith('_') or param.startswith('hash=') or param.startswith('itmmeta='):\n break\n if essential_params:\n return f\"{base_url}?{'&'.join(essential_params)}\"\n return base_url\n \n def is_link_valid(self, url:str) -> bool:\n \"\"\"Check if a URL is a valid link (page, not related to icon or metadata).\"\"\"\n if len(url) > 72:\n self.logger.warning(f\"URL too long: {url}\")\n return False\n parsed_url = urlparse(url)\n if not parsed_url.scheme or not parsed_url.netloc:\n self.logger.warning(f\"Invalid URL: {url}\")\n return False\n if re.search(r'/\\d+$', parsed_url.path):\n return False\n image_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp']\n metadata_extensions = ['.ico', '.xml', '.json', '.rss', '.atom']\n for ext in image_extensions + metadata_extensions:\n if url.lower().endswith(ext):\n return False\n return True\n\n def get_navigable(self) -> List[str]:\n \"\"\"Get all navigable links on the current page.\"\"\"\n try:\n links = []\n elements = self.driver.find_elements(By.TAG_NAME, \"a\")\n \n for element in elements:\n href = element.get_attribute(\"href\")\n if href and href.startswith((\"http\", \"https\")):\n links.append({\n \"url\": href,\n \"text\": element.text.strip(),\n \"is_displayed\": element.is_displayed()\n })\n \n self.logger.info(f\"Found {len(links)} navigable links\")\n return [self.clean_url(link['url']) for link in links if (link['is_displayed'] == True and self.is_link_valid(link['url']))]\n except Exception as e:\n self.logger.error(f\"Error getting navigable links: {str(e)}\")\n return []\n\n def click_element(self, xpath: str) -> bool:\n \"\"\"Click an element specified by XPath.\"\"\"\n try:\n element = self.wait.until(EC.element_to_be_clickable((By.XPATH, xpath)))\n if not element.is_displayed():\n return False\n if not element.is_enabled():\n return False\n try:\n self.logger.error(f\"Scrolling to element for click_element.\")\n self.driver.execute_script(\"arguments[0].scrollIntoView({block: 'center', behavior: 'smooth'});\", element)\n time.sleep(0.1)\n element.click()\n self.logger.info(f\"Clicked element at {xpath}\")\n return True\n except ElementClickInterceptedException as e:\n self.logger.error(f\"Error click_element: {str(e)}\")\n return False\n except TimeoutException:\n self.logger.warning(f\"Timeout clicking element.\")\n return False\n except Exception as e:\n self.logger.error(f\"Unexpected error clicking element at {xpath}: {str(e)}\")\n return False\n \n def load_js(self, file_name: str) -> str:\n \"\"\"Load javascript from script folder to inject to page.\"\"\"\n path = os.path.join(self.js_scripts_folder, file_name)\n self.logger.info(f\"Loading js at {path}\")\n try:\n with open(path, 'r') as f:\n return f.read()\n except FileNotFoundError as e:\n raise Exception(f\"Could not find: {path}\") from e\n except Exception as e:\n raise e\n\n def find_all_inputs(self, timeout=3):\n \"\"\"Find all inputs elements on the page.\"\"\"\n try:\n WebDriverWait(self.driver, timeout).until(\n EC.presence_of_element_located((By.TAG_NAME, \"body\"))\n )\n except Exception as e:\n self.logger.error(f\"Error waiting for input element: {str(e)}\")\n return []\n time.sleep(0.5)\n script = self.load_js(\"find_inputs.js\")\n input_elements = self.driver.execute_script(script)\n return input_elements\n\n def get_form_inputs(self) -> List[str]:\n \"\"\"Extract all input from the page and return them.\"\"\"\n try:\n input_elements = self.find_all_inputs()\n if not input_elements:\n self.logger.info(\"No input element on page.\")\n return [\"No input forms found on the page.\"]\n\n form_strings = []\n for element in input_elements:\n input_type = element.get(\"type\") or \"text\"\n if input_type in [\"hidden\", \"submit\", \"button\", \"image\"] or not element[\"displayed\"]:\n continue\n input_name = element.get(\"text\") or element.get(\"id\") or input_type\n if input_type == \"checkbox\" or input_type == \"radio\":\n try:\n checked_status = \"checked\" if element.is_selected() else \"unchecked\"\n except Exception as e:\n continue\n form_strings.append(f\"[{input_name}]({checked_status})\")\n else:\n form_strings.append(f\"[{input_name}](\"\")\")\n return form_strings\n\n except Exception as e:\n raise e\n\n def get_buttons_xpath(self) -> List[str]:\n \"\"\"\n Find buttons and return their type and xpath.\n \"\"\"\n buttons = self.driver.find_elements(By.TAG_NAME, \"button\") + \\\n self.driver.find_elements(By.XPATH, \"//input[@type='submit']\")\n result = []\n for i, button in enumerate(buttons):\n if not button.is_displayed() or not button.is_enabled():\n continue\n text = (button.text or button.get_attribute(\"value\") or \"\").lower().replace(' ', '')\n xpath = f\"(//button | //input[@type='submit'])[{i + 1}]\"\n result.append((text, xpath))\n result.sort(key=lambda x: len(x[0]))\n return result\n\n def wait_for_submission_outcome(self, timeout: int = 10) -> bool:\n \"\"\"\n Wait for a submission outcome (e.g., URL change or new element).\n \"\"\"\n try:\n self.logger.info(\"Waiting for submission outcome...\")\n wait = WebDriverWait(self.driver, timeout)\n wait.until(\n lambda driver: driver.current_url != self.driver.current_url or\n driver.find_elements(By.XPATH, \"//*[contains(text(), 'success')]\")\n )\n self.logger.info(\"Detected submission outcome\")\n return True\n except TimeoutException:\n self.logger.warning(\"No submission outcome detected\")\n return False\n\n def find_and_click_btn(self, btn_type: str = 'login', timeout: int = 5) -> bool:\n \"\"\"Find and click a submit button matching the specified type.\"\"\"\n buttons = self.get_buttons_xpath()\n if not buttons:\n self.logger.warning(\"No visible buttons found\")\n return False\n\n for button_text, xpath in buttons:\n if btn_type.lower() in button_text.lower() or btn_type.lower() in xpath.lower():\n try:\n wait = WebDriverWait(self.driver, timeout)\n element = wait.until(\n EC.element_to_be_clickable((By.XPATH, xpath)),\n message=f\"Button with XPath '{xpath}' not clickable within {timeout} seconds\"\n )\n if self.click_element(xpath):\n self.logger.info(f\"Clicked button '{button_text}' at XPath: {xpath}\")\n return True\n else:\n self.logger.warning(f\"Button '{button_text}' at XPath: {xpath} not clickable\")\n return False\n except TimeoutException:\n self.logger.warning(f\"Timeout waiting for '{button_text}' button at XPath: {xpath}\")\n return False\n except Exception as e:\n self.logger.error(f\"Error clicking button '{button_text}' at XPath: {xpath} - {str(e)}\")\n return False\n self.logger.warning(f\"No button matching '{btn_type}' found\")\n return False\n\n def tick_all_checkboxes(self) -> bool:\n \"\"\"\n Find and tick all checkboxes on the page.\n Returns True if successful, False if any issues occur.\n \"\"\"\n try:\n checkboxes = self.driver.find_elements(By.XPATH, \"//input[@type='checkbox']\")\n if not checkboxes:\n self.logger.info(\"No checkboxes found on the page\")\n return True\n\n for index, checkbox in enumerate(checkboxes, 1):\n try:\n WebDriverWait(self.driver, 10).until(\n EC.element_to_be_clickable(checkbox)\n )\n self.driver.execute_script(\n \"arguments[0].scrollIntoView({block: 'center', inline: 'center'});\", checkbox\n )\n if not checkbox.is_selected():\n try:\n checkbox.click()\n self.logger.info(f\"Ticked checkbox {index}\")\n except ElementClickInterceptedException:\n self.driver.execute_script(\"arguments[0].click();\", checkbox)\n self.logger.warning(f\"Click checkbox {index} intercepted\")\n else:\n self.logger.info(f\"Checkbox {index} already ticked\")\n except TimeoutException:\n self.logger.warning(f\"Timeout waiting for checkbox {index} to be clickable\")\n continue\n except Exception as e:\n self.logger.error(f\"Error ticking checkbox {index}: {str(e)}\")\n continue\n return True\n except Exception as e:\n self.logger.error(f\"Error finding checkboxes: {str(e)}\")\n return False\n\n def find_and_click_submission(self, timeout: int = 10) -> bool:\n possible_submissions = [\"login\", \"submit\", \"register\", \"continue\", \"apply\",\n \"ok\", \"confirm\", \"proceed\", \"accept\", \n \"done\", \"finish\", \"start\", \"calculate\"]\n for submission in possible_submissions:\n if self.find_and_click_btn(submission, timeout):\n self.logger.info(f\"Clicked on submission button: {submission}\")\n return True\n self.logger.warning(\"No submission button found\")\n return False\n \n def find_input_xpath_by_name(self, inputs, name: str) -> str | None:\n for field in inputs:\n if name in field[\"text\"]:\n return field[\"xpath\"]\n return None\n\n def fill_form_inputs(self, input_list: List[str]) -> bool:\n \"\"\"Fill inputs based on a list of [name](value) strings.\"\"\"\n if not isinstance(input_list, list):\n self.logger.error(\"input_list must be a list\")\n return False\n inputs = self.find_all_inputs()\n try:\n for input_str in input_list:\n match = re.match(r'\\[(.*?)\\]\\((.*?)\\)', input_str)\n if not match:\n self.logger.warning(f\"Invalid format for input: {input_str}\")\n continue\n\n name, value = match.groups()\n name = name.strip()\n value = value.strip()\n xpath = self.find_input_xpath_by_name(inputs, name)\n if not xpath:\n self.logger.warning(f\"Input field '{name}' not found\")\n continue\n try:\n element = WebDriverWait(self.driver, 10).until(\n EC.element_to_be_clickable((By.XPATH, xpath))\n )\n except TimeoutException:\n self.logger.error(f\"Timeout waiting for element '{name}' to be clickable\")\n continue\n self.driver.execute_script(\"arguments[0].scrollIntoView(true);\", element)\n if not element.is_displayed() or not element.is_enabled():\n self.logger.warning(f\"Element '{name}' is not interactable (not displayed or disabled)\")\n continue\n input_type = (element.get_attribute(\"type\") or \"text\").lower()\n if input_type in [\"checkbox\", \"radio\"]:\n is_checked = element.is_selected()\n should_be_checked = value.lower() == \"checked\"\n\n if is_checked != should_be_checked:\n element.click()\n self.logger.info(f\"Set {name} to {value}\")\n else:\n element.clear()\n element.send_keys(value)\n self.logger.info(f\"Filled {name} with {value}\")\n return True\n except Exception as e:\n self.logger.error(f\"Error filling form inputs: {str(e)}\")\n return False\n \n def fill_form(self, input_list: List[str]) -> bool:\n \"\"\"Fill form inputs based on a list of [name](value) and submit.\"\"\"\n if not isinstance(input_list, list):\n self.logger.error(\"input_list must be a list\")\n return False\n if self.fill_form_inputs(input_list):\n self.logger.info(\"Form filled successfully\")\n self.tick_all_checkboxes()\n if self.find_and_click_submission():\n if self.wait_for_submission_outcome():\n self.logger.info(\"Submission outcome detected\")\n return True\n else:\n self.logger.warning(\"No submission outcome detected\")\n else:\n self.logger.warning(\"Failed to submit form\")\n self.logger.warning(\"Failed to fill form inputs\")\n return False\n\n def get_current_url(self) -> str:\n \"\"\"Get the current URL of the page.\"\"\"\n return self.driver.current_url\n\n def get_page_title(self) -> str:\n \"\"\"Get the title of the current page.\"\"\"\n return self.driver.title\n\n def scroll_bottom(self) -> bool:\n \"\"\"Scroll to the bottom of the page.\"\"\"\n try:\n self.logger.info(\"Scrolling to the bottom of the page...\")\n self.driver.execute_script(\n \"window.scrollTo(0, document.body.scrollHeight);\"\n )\n time.sleep(0.5)\n return True\n except Exception as e:\n self.logger.error(f\"Error scrolling: {str(e)}\")\n return False\n \n def get_screenshot(self) -> str:\n return self.screenshot_folder + \"/updated_screen.png\"\n\n def screenshot(self, filename:str = 'updated_screen.png') -> bool:\n \"\"\"Take a screenshot of the current page, attempt to capture the full page by zooming out.\"\"\"\n self.logger.info(\"Taking full page screenshot...\")\n time.sleep(0.1)\n try:\n original_zoom = self.driver.execute_script(\"return document.body.style.zoom || 1;\")\n self.driver.execute_script(\"document.body.style.zoom='75%'\")\n time.sleep(0.1)\n path = os.path.join(self.screenshot_folder, filename)\n if not os.path.exists(self.screenshot_folder):\n os.makedirs(self.screenshot_folder)\n self.driver.save_screenshot(path)\n self.logger.info(f\"Full page screenshot saved as {filename}\")\n except Exception as e:\n self.logger.error(f\"Error taking full page screenshot: {str(e)}\")\n return False\n finally:\n self.driver.execute_script(f\"document.body.style.zoom='1'\")\n return True\n\n def apply_web_safety(self):\n \"\"\"\n Apply security measures to block any website malicious/annoying execution, privacy violation etc..\n \"\"\"\n self.logger.info(\"Applying web safety measures...\")\n script = self.load_js(\"inject_safety_script.js\")\n input_elements = self.driver.execute_script(script)\n\nif __name__ == \"__main__\":\n driver = create_driver(headless=False, stealth_mode=True, crx_path=\"../crx/nopecha.crx\")\n browser = Browser(driver, anticaptcha_manual_install=True)\n \n input(\"press enter to continue\")\n print(\"AntiCaptcha / Form Test\")\n browser.go_to(\"https://bot.sannysoft.com\")\n time.sleep(5)\n #txt = browser.get_text()\n browser.go_to(\"https://home.openweathermap.org/users/sign_up\")\n inputs_visible = browser.get_form_inputs()\n print(\"inputs:\", inputs_visible)\n #inputs_fill = ['[q](checked)', '[q](checked)', '[user[username]](mlg)', '[user[email]](mlg.fcu@gmail.com)', '[user[password]](placeholder_P@ssw0rd123)', '[user[password_confirmation]](placeholder_P@ssw0rd123)']\n #browser.fill_form(inputs_fill)\n input(\"press enter to exit\")\n\n# Test sites for browser fingerprinting and captcha\n# https://nowsecure.nl/\n# https://bot.sannysoft.com\n# https://browserleaks.com/\n# https://bot.incolumitas.com/\n# https://fingerprintjs.github.io/fingerprintjs/\n# https://antoinevastel.com/bots/"], ["/agenticSeek/sources/tools/PyInterpreter.py", "\nimport sys\nimport os\nimport re\nfrom io import StringIO\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass PyInterpreter(Tools):\n \"\"\"\n This class is a tool to allow agent for python code execution.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"python\"\n self.name = \"Python Interpreter\"\n self.description = \"This tool allows the agent to execute python code.\"\n\n def execute(self, codes:str, safety = False) -> str:\n \"\"\"\n Execute python code.\n \"\"\"\n output = \"\"\n if safety and input(\"Execute code ? y/n\") != \"y\":\n return \"Code rejected by user.\"\n stdout_buffer = StringIO()\n sys.stdout = stdout_buffer\n global_vars = {\n '__builtins__': __builtins__,\n 'os': os,\n 'sys': sys,\n '__name__': '__main__'\n }\n code = '\\n\\n'.join(codes)\n self.logger.info(f\"Executing code:\\n{code}\")\n try:\n try:\n buffer = exec(code, global_vars)\n self.logger.info(f\"Code executed successfully.\\noutput:{buffer}\")\n print(buffer)\n if buffer is not None:\n output = buffer + '\\n'\n except SystemExit:\n self.logger.info(\"SystemExit caught, code execution stopped.\")\n output = stdout_buffer.getvalue()\n return f\"[SystemExit caught] Output before exit:\\n{output}\"\n except Exception as e:\n self.logger.error(f\"Code execution failed: {str(e)}\")\n return \"code execution failed:\" + str(e)\n output = stdout_buffer.getvalue()\n finally:\n self.logger.info(\"Code execution finished.\")\n sys.stdout = sys.__stdout__\n return output\n\n def interpreter_feedback(self, output:str) -> str:\n \"\"\"\n Provide feedback based on the output of the code execution\n \"\"\"\n if self.execution_failure_check(output):\n feedback = f\"[failure] Error in execution:\\n{output}\"\n else:\n feedback = \"[success] Execution success, code output:\\n\" + output\n return feedback\n\n def execution_failure_check(self, feedback:str) -> bool:\n \"\"\"\n Check if the code execution failed.\n \"\"\"\n error_patterns = [\n r\"expected\", \n r\"errno\", \n r\"failed\", \n r\"traceback\", \n r\"invalid\", \n r\"unrecognized\", \n r\"exception\", \n r\"syntax\", \n r\"crash\", \n r\"segmentation fault\", \n r\"core dumped\"\n ]\n combined_pattern = \"|\".join(error_patterns)\n if re.search(combined_pattern, feedback, re.IGNORECASE):\n self.logger.error(f\"Execution failure detected: {feedback}\")\n return True\n self.logger.info(\"No execution success detected.\")\n return False\n\nif __name__ == \"__main__\":\n text = \"\"\"\nFor Python, let's also do a quick check:\n\n```python\nprint(\"Hello from Python!\")\n```\n\nIf these work, you'll see the outputs in the next message. Let me know if you'd like me to test anything specific! \n\nhere is a save test\n```python:tmp.py\n\ndef print_hello():\n hello = \"Hello World\"\n print(hello)\n\nif __name__ == \"__main__\":\n print_hello()\n```\n\"\"\"\n py = PyInterpreter()\n codes, save_path = py.load_exec_block(text)\n py.save_block(codes, save_path)\n print(py.execute(codes))"], ["/agenticSeek/sources/tools/webSearch.py", "\nimport os\nimport requests\nimport dotenv\n\ndotenv.load_dotenv()\n\nfrom sources.tools.tools import Tools\nfrom sources.utility import animate_thinking, pretty_print\n\n\"\"\"\nWARNING\nwebSearch is fully deprecated and is being replaced by searxSearch for web search.\n\"\"\"\n\nclass webSearch(Tools):\n def __init__(self, api_key: str = None):\n \"\"\"\n A tool to perform a Google search and return information from the first result.\n \"\"\"\n super().__init__()\n self.tag = \"web_search\"\n self.api_key = api_key or os.getenv(\"SERPAPI_KEY\") # Requires a SerpApi key\n self.paywall_keywords = [\n \"subscribe\", \"login to continue\", \"access denied\", \"restricted content\", \"404\", \"this page is not working\"\n ]\n\n def link_valid(self, link):\n \"\"\"check if a link is valid.\"\"\"\n if not link.startswith(\"http\"):\n return \"Status: Invalid URL\"\n \n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\"}\n try:\n response = requests.get(link, headers=headers, timeout=5)\n status = response.status_code\n if status == 200:\n content = response.text[:1000].lower()\n if any(keyword in content for keyword in self.paywall_keywords):\n return \"Status: Possible Paywall\"\n return \"Status: OK\"\n elif status == 404:\n return \"Status: 404 Not Found\"\n elif status == 403:\n return \"Status: 403 Forbidden\"\n else:\n return f\"Status: {status} {response.reason}\"\n except requests.exceptions.RequestException as e:\n return f\"Error: {str(e)}\"\n\n def check_all_links(self, links):\n \"\"\"Check all links, one by one.\"\"\"\n # TODO Make it asyncromous or smth\n statuses = []\n for i, link in enumerate(links):\n status = self.link_valid(link)\n statuses.append(status)\n return statuses\n\n def execute(self, blocks: str, safety: bool = True) -> str:\n if self.api_key is None:\n return \"Error: No SerpApi key provided.\"\n for block in blocks:\n query = block.strip()\n pretty_print(f\"Searching for: {query}\", color=\"status\")\n if not query:\n return \"Error: No search query provided.\"\n\n try:\n url = \"https://serpapi.com/search\"\n params = {\n \"q\": query,\n \"api_key\": self.api_key,\n \"num\": 50,\n \"output\": \"json\"\n }\n response = requests.get(url, params=params)\n response.raise_for_status()\n\n data = response.json()\n results = []\n if \"organic_results\" in data and len(data[\"organic_results\"]) > 0:\n organic_results = data[\"organic_results\"][:50]\n links = [result.get(\"link\", \"No link available\") for result in organic_results]\n statuses = self.check_all_links(links)\n for result, status in zip(organic_results, statuses):\n if not \"OK\" in status:\n continue\n title = result.get(\"title\", \"No title\")\n snippet = result.get(\"snippet\", \"No snippet available\")\n link = result.get(\"link\", \"No link available\")\n results.append(f\"Title:{title}\\nSnippet:{snippet}\\nLink:{link}\")\n return \"\\n\\n\".join(results)\n else:\n return \"No results found for the query.\"\n except requests.RequestException as e:\n return f\"Error during web search: {str(e)}\"\n except Exception as e:\n return f\"Unexpected error: {str(e)}\"\n return \"No search performed\"\n\n def execution_failure_check(self, output: str) -> bool:\n return output.startswith(\"Error\") or \"No results found\" in output\n\n def interpreter_feedback(self, output: str) -> str:\n if self.execution_failure_check(output):\n return f\"Web search failed: {output}\"\n return f\"Web search result:\\n{output}\"\n\n\nif __name__ == \"__main__\":\n search_tool = webSearch(api_key=os.getenv(\"SERPAPI_KEY\"))\n query = \"when did covid start\"\n result = search_tool.execute([query], safety=True)\n output = search_tool.interpreter_feedback(result)\n print(output)"], ["/agenticSeek/sources/tools/mcpFinder.py", "import os, sys\nimport requests\nfrom urllib.parse import urljoin\nfrom typing import Dict, Any, Optional\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass MCP_finder(Tools):\n \"\"\"\n Tool to find MCPs server\n \"\"\"\n def __init__(self, api_key: str = None):\n super().__init__()\n self.tag = \"mcp_finder\"\n self.name = \"MCP Finder\"\n self.description = \"Find MCP servers and their tools\"\n self.base_url = \"https://registry.smithery.ai\"\n self.headers = {\n \"Authorization\": f\"Bearer {api_key}\",\n \"Content-Type\": \"application/json\"\n }\n\n def _make_request(self, method: str, endpoint: str, params: Optional[Dict] = None, \n data: Optional[Dict] = None) -> Dict[str, Any]:\n url = urljoin(self.base_url.rstrip(), endpoint)\n try:\n response = requests.request(\n method=method,\n url=url,\n headers=self.headers,\n params=params,\n json=data\n )\n response.raise_for_status()\n return response.json()\n except requests.exceptions.HTTPError as e:\n raise requests.exceptions.HTTPError(f\"API request failed: {str(e)}\")\n except requests.exceptions.RequestException as e:\n raise requests.exceptions.RequestException(f\"Network error: {str(e)}\")\n\n def list_mcp_servers(self, page: int = 1, page_size: int = 5000) -> Dict[str, Any]:\n params = {\"page\": page, \"pageSize\": page_size}\n return self._make_request(\"GET\", \"/servers\", params=params)\n\n def get_mcp_server_details(self, qualified_name: str) -> Dict[str, Any]:\n endpoint = f\"/servers/{qualified_name}\"\n return self._make_request(\"GET\", endpoint)\n \n def find_mcp_servers(self, query: str) -> Dict[str, Any]:\n \"\"\"\n Finds a specific MCP server by its name.\n Args:\n query (str): a name or string that more or less matches the MCP server name.\n Returns:\n Dict[str, Any]: The details of the found MCP server or an error message.\n \"\"\"\n mcps = self.list_mcp_servers()\n matching_mcp = []\n for mcp in mcps.get(\"servers\", []):\n name = mcp.get(\"qualifiedName\", \"\")\n if query.lower() in name.lower():\n details = self.get_mcp_server_details(name)\n matching_mcp.append(details)\n return matching_mcp\n \n def execute(self, blocks: list, safety:bool = False) -> str:\n if not blocks or not isinstance(blocks, list):\n return \"Error: No blocks provided\\n\"\n\n output = \"\"\n for block in blocks:\n block_clean = block.strip().lower().replace('\\n', '')\n try:\n matching_mcp_infos = self.find_mcp_servers(block_clean)\n except requests.exceptions.RequestException as e:\n output += \"Connection failed. Is the API key in environment?\\n\"\n continue\n except Exception as e:\n output += f\"Error: {str(e)}\\n\"\n continue\n if matching_mcp_infos == []:\n output += f\"Error: No MCP server found for query '{block}'\\n\"\n continue\n for mcp_infos in matching_mcp_infos:\n if mcp_infos['tools'] is None:\n continue\n output += f\"Name: {mcp_infos['displayName']}\\n\"\n output += f\"Usage name: {mcp_infos['qualifiedName']}\\n\"\n output += f\"Tools: {mcp_infos['tools']}\"\n output += \"\\n-------\\n\"\n return output.strip()\n\n def execution_failure_check(self, output: str) -> bool:\n output = output.strip().lower()\n if not output:\n return True\n if \"error\" in output or \"not found\" in output:\n return True\n return False\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Not really needed for this tool (use return of execute() directly)\n \"\"\"\n if not output:\n raise ValueError(\"No output to interpret.\")\n return f\"\"\"\n The following MCPs were found:\n {output}\n \"\"\"\n\nif __name__ == \"__main__\":\n api_key = os.getenv(\"MCP_FINDER\")\n tool = MCP_finder(api_key)\n result = tool.execute([\"\"\"\nstock\n\"\"\"], False)\n print(result)\n"], ["/agenticSeek/sources/tools/C_Interpreter.py", "import subprocess\nimport os, sys\nimport tempfile\nimport re\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass CInterpreter(Tools):\n \"\"\"\n This class is a tool to allow agent for C code execution\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"c\"\n self.name = \"C Interpreter\"\n self.description = \"This tool allows the agent to execute C code.\"\n\n def execute(self, codes: str, safety=False) -> str:\n \"\"\"\n Execute C code by compiling and running it.\n \"\"\"\n output = \"\"\n code = '\\n'.join(codes) if isinstance(codes, list) else codes\n \n if safety and input(\"Execute code? y/n \") != \"y\":\n return \"Code rejected by user.\"\n\n exec_extension = \".exe\" if os.name == \"nt\" else \"\" # Windows uses .exe, Linux/Unix does not\n \n with tempfile.TemporaryDirectory() as tmpdirname:\n source_file = os.path.join(tmpdirname, \"temp.c\")\n exec_file = os.path.join(tmpdirname, \"temp\") + exec_extension\n with open(source_file, 'w') as f:\n f.write(code)\n\n try:\n compile_command = [\"gcc\", source_file, \"-o\", exec_file]\n compile_result = subprocess.run(\n compile_command,\n capture_output=True,\n text=True,\n timeout=60\n )\n\n if compile_result.returncode != 0:\n return f\"Compilation failed: {compile_result.stderr}\"\n\n run_command = [exec_file]\n run_result = subprocess.run(\n run_command,\n capture_output=True,\n text=True,\n timeout=120\n )\n\n if run_result.returncode != 0:\n return f\"Execution failed: {run_result.stderr}\"\n output = run_result.stdout\n\n except subprocess.TimeoutExpired as e:\n return f\"Execution timed out: {str(e)}\"\n except FileNotFoundError:\n return \"Error: 'gcc' not found. Ensure a C compiler (e.g., gcc) is installed and in PATH.\"\n except Exception as e:\n return f\"Code execution failed: {str(e)}\"\n\n return output\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Provide feedback based on the output of the code execution\n \"\"\"\n if self.execution_failure_check(output):\n feedback = f\"[failure] Error in execution:\\n{output}\"\n else:\n feedback = \"[success] Execution success, code output:\\n\" + output\n return feedback\n\n def execution_failure_check(self, feedback: str) -> bool:\n \"\"\"\n Check if the code execution failed.\n \"\"\"\n error_patterns = [\n r\"error\", \n r\"failed\", \n r\"traceback\", \n r\"invalid\", \n r\"exception\", \n r\"syntax\", \n r\"segmentation fault\", \n r\"core dumped\", \n r\"undefined\", \n r\"cannot\"\n ]\n combined_pattern = \"|\".join(error_patterns)\n if re.search(combined_pattern, feedback, re.IGNORECASE):\n return True\n return False\n\nif __name__ == \"__main__\":\n codes = [\n\"\"\"\n#include \n#include \n\nvoid hello() {\n printf(\"Hello, World!\\\\n\");\n}\n\"\"\",\n\"\"\"\nint main() {\n hello();\n return 0;\n}\n \"\"\"]\n c = CInterpreter()\n print(c.execute(codes))"], ["/agenticSeek/sources/router.py", "import os\nimport sys\nimport torch\nimport random\nfrom typing import List, Tuple, Type, Dict\n\nfrom transformers import pipeline\nfrom adaptive_classifier import AdaptiveClassifier\n\nfrom sources.agents.agent import Agent\nfrom sources.agents.code_agent import CoderAgent\nfrom sources.agents.casual_agent import CasualAgent\nfrom sources.agents.planner_agent import FileAgent\nfrom sources.agents.browser_agent import BrowserAgent\nfrom sources.language import LanguageUtility\nfrom sources.utility import pretty_print, animate_thinking, timer_decorator\nfrom sources.logger import Logger\n\nclass AgentRouter:\n \"\"\"\n AgentRouter is a class that selects the appropriate agent based on the user query.\n \"\"\"\n def __init__(self, agents: list, supported_language: List[str] = [\"en\", \"fr\", \"zh\"]):\n self.agents = agents\n self.logger = Logger(\"router.log\")\n self.lang_analysis = LanguageUtility(supported_language=supported_language)\n self.pipelines = self.load_pipelines()\n self.talk_classifier = self.load_llm_router()\n self.complexity_classifier = self.load_llm_router()\n self.learn_few_shots_tasks()\n self.learn_few_shots_complexity()\n self.asked_clarify = False\n \n def load_pipelines(self) -> Dict[str, Type[pipeline]]:\n \"\"\"\n Load the pipelines for the text classification used for routing.\n returns:\n Dict[str, Type[pipeline]]: The loaded pipelines\n \"\"\"\n animate_thinking(\"Loading zero-shot pipeline...\", color=\"status\")\n return {\n \"bart\": pipeline(\"zero-shot-classification\", model=\"facebook/bart-large-mnli\")\n }\n\n def load_llm_router(self) -> AdaptiveClassifier:\n \"\"\"\n Load the LLM router model.\n returns:\n AdaptiveClassifier: The loaded model\n exceptions:\n Exception: If the safetensors fails to load\n \"\"\"\n path = \"../llm_router\" if __name__ == \"__main__\" else \"./llm_router\"\n try:\n animate_thinking(\"Loading LLM router model...\", color=\"status\")\n talk_classifier = AdaptiveClassifier.from_pretrained(path)\n except Exception as e:\n raise Exception(\"Failed to load the routing model. Please run the dl_safetensors.sh script inside llm_router/ directory to download the model.\")\n return talk_classifier\n\n def get_device(self) -> str:\n if torch.backends.mps.is_available():\n return \"mps\"\n elif torch.cuda.is_available():\n return \"cuda:0\"\n else:\n return \"cpu\"\n \n def learn_few_shots_complexity(self) -> None:\n \"\"\"\n Few shot learning for complexity estimation.\n Use the build in add_examples method of the Adaptive_classifier.\n \"\"\"\n few_shots = [\n (\"hi\", \"LOW\"),\n (\"How it's going ?\", \"LOW\"),\n (\"What’s the weather like today?\", \"LOW\"),\n (\"Can you find a file named ‘notes.txt’ in my Documents folder?\", \"LOW\"),\n (\"Write a Python script to generate a random password\", \"LOW\"),\n (\"Debug this JavaScript code that’s not running properly\", \"LOW\"),\n (\"Search the web for the cheapest laptop under $500\", \"LOW\"),\n (\"Locate a file called ‘report_2024.pdf’ on my drive\", \"LOW\"),\n (\"Check if a folder named ‘Backups’ exists on my system\", \"LOW\"),\n (\"Can you find ‘family_vacation.mp4’ in my Videos folder?\", \"LOW\"),\n (\"Search my drive for a file named ‘todo_list.xlsx’\", \"LOW\"),\n (\"Write a Python function to check if a string is a palindrome\", \"LOW\"),\n (\"Can you search the web for startups in Berlin?\", \"LOW\"),\n (\"Find recent articles on blockchain technology online\", \"LOW\"),\n (\"Check if ‘Personal_Projects’ folder exists on my desktop\", \"LOW\"),\n (\"Create a bash script to list all running processes\", \"LOW\"),\n (\"Debug this Python script that’s crashing on line 10\", \"LOW\"),\n (\"Browse the web to find out who invented Python\", \"LOW\"),\n (\"Locate a file named ‘shopping_list.txt’ on my system\", \"LOW\"),\n (\"Search the web for tips on staying productive\", \"LOW\"),\n (\"Find ‘sales_pitch.pptx’ in my Downloads folder\", \"LOW\"),\n (\"can you find a file called resume.docx on my drive?\", \"LOW\"),\n (\"can you write a python script to check if the device on my network is connected to the internet\", \"LOW\"),\n (\"can you debug this Java code? It’s not working.\", \"LOW\"),\n (\"can you find the old_project.zip file somewhere on my drive?\", \"LOW\"),\n (\"can you locate the backup folder I created last month on my system?\", \"LOW\"),\n (\"could you check if the presentation.pdf file exists in my downloads?\", \"LOW\"),\n (\"search my drive for a file called vacation_photos_2023.jpg.\", \"LOW\"),\n (\"help me organize my desktop files into folders by type.\", \"LOW\"),\n (\"make a blackjack in golang\", \"LOW\"),\n (\"write a python script to ping a website\", \"LOW\"),\n (\"write a simple Java program to print 'Hello World'\", \"LOW\"),\n (\"write a Java program to calculate the area of a circle\", \"LOW\"),\n (\"write a Python function to sort a list of dictionaries by key\", \"LOW\"),\n (\"can you search for startup in tokyo?\", \"LOW\"),\n (\"find the latest updates on quantum computing on the web\", \"LOW\"),\n (\"check if the folder ‘Work_Projects’ exists on my desktop\", \"LOW\"),\n (\" can you browse the web, use overpass-turbo to show fountains in toulouse\", \"LOW\"),\n (\"search the web for the best budget smartphones of 2025\", \"LOW\"),\n (\"write a Python script to download all images from a webpage\", \"LOW\"),\n (\"create a bash script to monitor CPU usage\", \"LOW\"),\n (\"debug this C++ code that keeps crashing\", \"LOW\"),\n (\"can you browse the web to find out who fosowl is ?\", \"LOW\"),\n (\"find the file ‘important_notes.txt’\", \"LOW\"),\n (\"search the web for the best ways to learn a new language\", \"LOW\"),\n (\"locate the file ‘presentation.pptx’ in my Documents folder\", \"LOW\"),\n (\"Make a 3d game in javascript using three.js\", \"LOW\"),\n (\"Find the latest research papers on AI and build save in a file\", \"HIGH\"),\n (\"Make a web server in go that serve a simple html page\", \"LOW\"),\n (\"Search the web for the cheapest 4K monitor and provide a link\", \"LOW\"),\n (\"Write a JavaScript function to reverse a string\", \"LOW\"),\n (\"Can you locate a file called ‘budget_2025.xlsx’ on my system?\", \"LOW\"),\n (\"Search the web for recent articles on space exploration\", \"LOW\"),\n (\"when is the exam period for master student in france?\", \"LOW\"),\n (\"Check if a folder named ‘Photos_2024’ exists on my desktop\", \"LOW\"),\n (\"Can you look up some nice knitting patterns on that web thingy?\", \"LOW\"),\n (\"Goodness, check if my ‘Photos_Grandkids’ folder is still on the desktop\", \"LOW\"),\n (\"Create a Python script to rename all files in a folder based on their creation date\", \"LOW\"),\n (\"Can you find a file named ‘meeting_notes.txt’ in my Downloads folder?\", \"LOW\"),\n (\"Write a Go program to check if a port is open on a network\", \"LOW\"),\n (\"Search the web for the latest electric car reviews\", \"LOW\"),\n (\"Write a Python function to merge two sorted lists\", \"LOW\"),\n (\"Create a bash script to monitor disk space and alert via text file\", \"LOW\"),\n (\"What’s out there on the web about cheap travel spots?\", \"LOW\"),\n (\"Search X for posts about AI ethics and summarize them\", \"LOW\"),\n (\"Check if a file named ‘project_proposal.pdf’ exists in my Documents\", \"LOW\"),\n (\"Search the web for tips on improving coding skills\", \"LOW\"),\n (\"Write a Python script to count words in a text file\", \"LOW\"),\n (\"Search the web for restaurant\", \"LOW\"),\n (\"Use a MCP to find the latest stock market data\", \"LOW\"),\n (\"Use a MCP to send an email to my boss\", \"LOW\"),\n (\"Could you use a MCP to find the latest news on climate change?\", \"LOW\"),\n (\"Create a simple HTML page with CSS styling\", \"LOW\"),\n (\"Use file.txt and then use it to ...\", \"HIGH\"),\n (\"Yo, what’s good? Find my ‘mixtape.mp3’ real quick\", \"LOW\"),\n (\"Can you follow the readme and install the project\", \"HIGH\"),\n (\"Man, write me a dope Python script to flex some random numbers\", \"LOW\"),\n (\"Search the web for peer-reviewed articles on gene editing\", \"LOW\"),\n (\"Locate ‘meeting_notes.docx’ in Downloads, I’m late for this call\", \"LOW\"),\n (\"Make the game less hard\", \"LOW\"),\n (\"Why did it fail?\", \"LOW\"),\n (\"Write a Python script to list all .pdf files in my Documents\", \"LOW\"),\n (\"Write a Python thing to sort my .jpg files by date\", \"LOW\"),\n (\"make a snake game please\", \"LOW\"),\n (\"Find ‘gallery_list.pdf’, then build a web app to show my pics\", \"HIGH\"),\n (\"Find ‘budget_2025.xlsx’, analyze it, and make a chart for my boss\", \"HIGH\"),\n (\"I want you to make me a plan to travel to Tainan\", \"HIGH\"),\n (\"Retrieve the latest publications on CRISPR and develop a web application to display them\", \"HIGH\"),\n (\"Bro dig up a music API and build me a tight app for the hottest tracks\", \"HIGH\"),\n (\"Find a public API for sports scores and build a web app to show live updates\", \"HIGH\"),\n (\"Find a public API for book data and create a Flask app to list bestsellers\", \"HIGH\"),\n (\"Organize my desktop files by extension and then write a script to list them\", \"HIGH\"),\n (\"Find the latest research on renewable energy and build a web app to display it\", \"HIGH\"),\n (\"search online for popular sci-fi movies from 2024 and pick three to watch tonight. Save the list in movie_night.txt\", \"HIGH\"),\n (\"can you find vitess repo, clone it and install by following the readme\", \"HIGH\"),\n (\"Create a JavaScript game using Phaser.js with multiple levels\", \"HIGH\"),\n (\"Search the web for the latest trends in web development and build a sample site\", \"HIGH\"),\n (\"Use my research_note.txt file, double check the informations on the web\", \"HIGH\"),\n (\"Make a web server in go that query a flight API and display them in a app\", \"HIGH\"),\n (\"Search the web for top cafes in Rennes, France, and save a list of three with their addresses in rennes_cafes.txt.\", \"HIGH\"),\n (\"Search the web for the latest trends in AI and demo it in pytorch\", \"HIGH\"),\n (\"can you lookup for api that track flight and build a web flight tracking app\", \"HIGH\"),\n (\"Find the file toto.pdf then use its content to reply to Jojo on superforum.com\", \"HIGH\"),\n (\"Create a whole web app in python using the flask framework that query news API\", \"HIGH\"),\n (\"Create a bash script that monitor the CPU usage and send an email if it's too high\", \"HIGH\"),\n (\"Make a web search for latest news on the stock market and display them with python\", \"HIGH\"),\n (\"Find my resume file, apply to job that might fit online\", \"HIGH\"),\n (\"Can you find a weather API and build a Python app to display current weather\", \"HIGH\"),\n (\"Create a Python web app using Flask to track cryptocurrency prices from an API\", \"HIGH\"),\n (\"Search the web for tutorials on machine learning and build a simple ML model in Python\", \"HIGH\"),\n (\"Find a public API for movie data and build a web app to display movie ratings\", \"HIGH\"),\n (\"Create a Node.js server that queries a public API for traffic data and displays it\", \"HIGH\"),\n (\"can you find api and build a python web app with it ?\", \"HIGH\"),\n (\"do a deep search of current AI player for 2025 and make me a report in a file\", \"HIGH\"),\n (\"Find a public API for recipe data and build a web app to display recipes\", \"HIGH\"),\n (\"Search the web for recent space mission updates and build a Flask app\", \"HIGH\"),\n (\"Create a Python script to scrape a website and save data to a database\", \"HIGH\"),\n (\"Find a shakespear txt then train a transformers on it to generate text\", \"HIGH\"),\n (\"Find a public API for fitness tracking and build a web app to show stats\", \"HIGH\"),\n (\"Search the web for tutorials on web development and build a sample site\", \"HIGH\"),\n (\"Create a Node.js app to query a public API for event listings and display them\", \"HIGH\"),\n (\"Find a file named ‘budget.xlsx’, analyze its data, and generate a chart\", \"HIGH\"),\n ]\n random.shuffle(few_shots)\n texts = [text for text, _ in few_shots]\n labels = [label for _, label in few_shots]\n self.complexity_classifier.add_examples(texts, labels)\n\n def learn_few_shots_tasks(self) -> None:\n \"\"\"\n Few shot learning for tasks classification.\n Use the build in add_examples method of the Adaptive_classifier.\n \"\"\"\n few_shots = [\n (\"Write a python script to check if the device on my network is connected to the internet\", \"coding\"),\n (\"Hey could you search the web for the latest news on the tesla stock market ?\", \"web\"),\n (\"I would like you to search for weather api\", \"web\"),\n (\"Plan a 3-day trip to New York, including flights and hotels.\", \"web\"),\n (\"Find on the web the latest research papers on AI.\", \"web\"),\n (\"Can you debug this Java code? It’s not working.\", \"code\"),\n (\"Can you browse the web and find me a 4090 for cheap?\", \"web\"),\n (\"i would like to setup a new AI project, index as mark2\", \"files\"),\n (\"Hey, can you find the old_project.zip file somewhere on my drive?\", \"files\"),\n (\"Tell me a funny story\", \"talk\"),\n (\"can you make a snake game in python\", \"code\"),\n (\"Can you locate the backup folder I created last month on my system?\", \"files\"),\n (\"Share a random fun fact about space.\", \"talk\"),\n (\"Write a script to rename all files in a directory to lowercase.\", \"files\"),\n (\"Could you check if the presentation.pdf file exists in my downloads?\", \"files\"),\n (\"Tell me about the weirdest dream you’ve ever heard of.\", \"talk\"),\n (\"Search my drive for a file called vacation_photos_2023.jpg.\", \"files\"),\n (\"Help me organize my desktop files into folders by type.\", \"files\"),\n (\"What’s your favorite movie and why?\", \"talk\"),\n (\"what directory are you in ?\", \"files\"),\n (\"what files you seing rn ?\", \"files\"),\n (\"When is the period of university exam in france ?\", \"web\"),\n (\"Search my drive for a file named budget_2024.xlsx\", \"files\"),\n (\"Write a Python function to sort a list of dictionaries by key\", \"code\"),\n (\"Find the latest updates on quantum computing on the web\", \"web\"),\n (\"Check if the folder ‘Work_Projects’ exists on my desktop\", \"files\"),\n (\"Create a bash script to monitor CPU usage\", \"code\"),\n (\"Search online for the best budget smartphones of 2025\", \"web\"),\n (\"What’s the strangest food combination you’ve heard of?\", \"talk\"),\n (\"Move all .txt files from Downloads to a new folder called Notes\", \"files\"),\n (\"Debug this C++ code that keeps crashing\", \"code\"),\n (\"can you browse the web to find out who fosowl is ?\", \"web\"),\n (\"Find the file ‘important_notes.txt’\", \"files\"),\n (\"Find out the latest news on the upcoming Mars mission\", \"web\"),\n (\"Write a Java program to calculate the area of a circle\", \"code\"),\n (\"Search the web for the best ways to learn a new language\", \"web\"),\n (\"Locate the file ‘presentation.pptx’ in my Documents folder\", \"files\"),\n (\"Write a Python script to download all images from a webpage\", \"code\"),\n (\"Search the web for the latest trends in AI and machine learning\", \"web\"),\n (\"Tell me about a time when you had to solve a difficult problem\", \"talk\"),\n (\"Organize all image files on my desktop into a folder called ‘Pictures’\", \"files\"),\n (\"Generate a Ruby script to calculate Fibonacci numbers up to 100\", \"code\"),\n (\"Find out what device are connected to my network\", \"code\"),\n (\"Show me how much disk space is left on my drive\", \"code\"),\n (\"Look up recent posts on X about climate change\", \"web\"),\n (\"Find the photo I took last week named sunset_beach.jpg\", \"files\"),\n (\"Write a JavaScript snippet to fetch data from an API\", \"code\"),\n (\"Search the web for tutorials on machine learning with Python\", \"web\"),\n (\"Locate the file ‘meeting_notes.docx’ in my Documents folder\", \"files\"),\n (\"Write a Python script to scrape a website’s title and links\", \"code\"),\n (\"Search the web for the latest breakthroughs in fusion energy\", \"web\"),\n (\"Tell me about a historical event that sounds too wild to be true\", \"talk\"),\n (\"Organize all image files on my desktop into a folder called ‘Pictures’\", \"files\"),\n (\"Generate a Ruby script to calculate Fibonacci numbers up to 100\", \"code\"),\n (\"Find recent X posts about SpaceX’s next rocket launch\", \"web\"),\n (\"What’s the funniest misunderstanding you’ve seen between humans and AI?\", \"talk\"),\n (\"Check if ‘backup_032025.zip’ exists anywhere on my drive\", \"files\" ),\n (\"Create a shell script to automate backups of a directory\", \"code\"),\n (\"Look up the top AI conferences happening in 2025 online\", \"web\"),\n (\"Write a C# program to simulate a basic calculator\", \"code\"),\n (\"Browse the web for open-source alternatives to Photoshop\", \"web\"),\n (\"Hey how are you\", \"talk\"),\n (\"Write a Python script to ping a website\", \"code\"),\n (\"Search the web for the latest iPhone release\", \"web\"),\n (\"What’s the weather like today?\", \"web\"),\n (\"Hi, how’s your day going?\", \"talk\"),\n (\"Can you find a file called resume.docx on my drive?\", \"files\"),\n (\"Write a simple Java program to print 'Hello World'\", \"code\"),\n (\"can you find the current stock of Tesla?\", \"web\"),\n (\"Tell me a quick joke\", \"talk\"),\n (\"Search online for the best coffee shops in Seattle\", \"web\"),\n (\"Check if ‘project_plan.pdf’ exists in my Downloads folder\", \"files\"),\n (\"What’s your favorite color?\", \"talk\"),\n (\"Write a bash script to list all files in a directory\", \"code\"),\n (\"Find recent X posts about electric cars\", \"web\"),\n (\"Hey, you doing okay?\", \"talk\"),\n (\"Locate the file ‘family_photo.jpg’ on my system\", \"files\"),\n (\"Search the web for beginner guitar lessons\", \"web\"),\n (\"Write a Python function to reverse a string\", \"code\"),\n (\"What’s the weirdest animal you know of?\", \"talk\"),\n (\"Organize all .pdf files on my desktop into a ‘Documents’ folder\", \"files\"),\n (\"Browse the web for the latest space mission updates\", \"web\"),\n (\"Hey, what’s up with you today?\", \"talk\"),\n (\"Write a JavaScript function to add two numbers\", \"code\"),\n (\"Find the file ‘notes.txt’ in my Documents folder\", \"files\"),\n (\"Tell me something random about the ocean\", \"talk\"),\n (\"Search the web for cheap flights to Paris\", \"web\"),\n (\"Check if ‘budget.xlsx’ is on my drive\", \"files\"),\n (\"Write a Python script to count words in a text file\", \"code\"),\n (\"How’s it going today?\", \"talk\"),\n (\"Find recent X posts about AI advancements\", \"web\"),\n (\"Move all .jpg files from Downloads to a ‘Photos’ folder\", \"files\"),\n (\"Search online for the best laptops of 2025\", \"web\"),\n (\"What’s the funniest thing you’ve heard lately?\", \"talk\"),\n (\"Write a Ruby script to generate random numbers\", \"code\"),\n (\"Hey, how’s everything with you?\", \"talk\"),\n (\"Locate ‘meeting_agenda.docx’ in my system\", \"files\"),\n (\"Search the web for tips on growing indoor plants\", \"web\"),\n (\"Write a C++ program to calculate the sum of an array\", \"code\"),\n (\"Tell me a fun fact about dogs\", \"talk\"),\n (\"Check if the folder ‘Old_Projects’ exists on my desktop\", \"files\"),\n (\"Browse the web for the latest gaming console reviews\", \"web\"),\n (\"Hi, how are you feeling today?\", \"talk\"),\n (\"Write a Python script to check disk space\", \"code\"),\n (\"Find the file ‘vacation_itinerary.pdf’ on my drive\", \"files\"),\n (\"Search the web for news on renewable energy\", \"web\"),\n (\"What’s the strangest thing you’ve learned recently?\", \"talk\"),\n (\"Organize all video files into a ‘Videos’ folder\", \"files\"),\n (\"Write a shell script to delete temporary files\", \"code\"),\n (\"Hey, how’s your week been so far?\", \"talk\"),\n (\"Search online for the top movies of 2025\", \"web\"),\n (\"Locate ‘taxes_2024.xlsx’ in my Documents folder\", \"files\"),\n (\"Tell me about a cool invention from history\", \"talk\"),\n (\"Write a Java program to check if a number is even or odd\", \"code\"),\n (\"Find recent X posts about cryptocurrency trends\", \"web\"),\n (\"Hey, you good today?\", \"talk\"),\n (\"Search the web for easy dinner recipes\", \"web\"),\n (\"Check if ‘photo_backup.zip’ exists on my drive\", \"files\"),\n (\"Write a Python script to rename files with a timestamp\", \"code\"),\n (\"What’s your favorite thing about space?\", \"talk\"),\n (\"search for GPU with at least 24gb vram\", \"web\"),\n (\"Browse the web for the latest fitness trends\", \"web\"),\n (\"Move all .docx files to a ‘Work’ folder\", \"files\"),\n (\"I would like to make a new project called 'new_project'\", \"files\"),\n (\"I would like to setup a new project index as mark2\", \"files\"),\n (\"can you create a 3d js game that run in the browser\", \"code\"),\n (\"can you make a web app in python that use the flask framework\", \"code\"),\n (\"can you build a web server in go that serve a simple html page\", \"code\"),\n (\"can you find out who Jacky yougouri is ?\", \"web\"),\n (\"Can you use MCP to find stock market for IBM ?\", \"mcp\"),\n (\"Can you use MCP to to export my contacts to a csv file?\", \"mcp\"),\n (\"Can you use a MCP to find write notes to flomo\", \"mcp\"),\n (\"Can you use a MCP to query my calendar and find the next meeting?\", \"mcp\"),\n (\"Can you use a mcp to get the distance between Shanghai and Paris?\", \"mcp\"),\n (\"Setup a new flutter project called 'new_flutter_project'\", \"files\"),\n (\"can you create a new project called 'new_project'\", \"files\"),\n (\"can you make a simple web app that display a list of files in my dir\", \"code\"),\n (\"can you build a simple web server in python that serve a html page\", \"code\"),\n (\"find and buy me the latest rtx 4090\", \"web\"),\n (\"What are some good netflix show like Altered Carbon ?\", \"web\"),\n (\"can you find the latest research paper on AI\", \"web\"),\n (\"can you find research.pdf in my drive\", \"files\"),\n (\"hi\", \"talk\"),\n (\"hello\", \"talk\"),\n ]\n random.shuffle(few_shots)\n texts = [text for text, _ in few_shots]\n labels = [label for _, label in few_shots]\n self.talk_classifier.add_examples(texts, labels)\n\n def llm_router(self, text: str) -> tuple:\n \"\"\"\n Inference of the LLM router model.\n Args:\n text: The input text\n \"\"\"\n predictions = self.talk_classifier.predict(text)\n predictions = [pred for pred in predictions if pred[0] not in [\"HIGH\", \"LOW\"]]\n predictions = sorted(predictions, key=lambda x: x[1], reverse=True)\n return predictions[0]\n \n def router_vote(self, text: str, labels: list, log_confidence:bool = False) -> str:\n \"\"\"\n Vote between the LLM router and BART model.\n Args:\n text: The input text\n labels: The labels to classify\n Returns:\n str: The selected label\n \"\"\"\n if len(text) <= 8:\n return \"talk\"\n result_bart = self.pipelines['bart'](text, labels)\n result_llm_router = self.llm_router(text)\n bart, confidence_bart = result_bart['labels'][0], result_bart['scores'][0]\n llm_router, confidence_llm_router = result_llm_router[0], result_llm_router[1]\n final_score_bart = confidence_bart / (confidence_bart + confidence_llm_router)\n final_score_llm = confidence_llm_router / (confidence_bart + confidence_llm_router)\n self.logger.info(f\"Routing Vote for text {text}: BART: {bart} ({final_score_bart}) LLM-router: {llm_router} ({final_score_llm})\")\n if log_confidence:\n pretty_print(f\"Agent choice -> BART: {bart} ({final_score_bart}) LLM-router: {llm_router} ({final_score_llm})\")\n return bart if final_score_bart > final_score_llm else llm_router\n \n def find_first_sentence(self, text: str) -> str:\n first_sentence = None\n for line in text.split(\"\\n\"):\n first_sentence = line.strip()\n break\n if first_sentence is None:\n first_sentence = text\n return first_sentence\n \n def estimate_complexity(self, text: str) -> str:\n \"\"\"\n Estimate the complexity of the text.\n Args:\n text: The input text\n Returns:\n str: The estimated complexity\n \"\"\"\n try:\n predictions = self.complexity_classifier.predict(text)\n except Exception as e:\n pretty_print(f\"Error in estimate_complexity: {str(e)}\", color=\"failure\")\n return \"LOW\"\n predictions = sorted(predictions, key=lambda x: x[1], reverse=True)\n if len(predictions) == 0:\n return \"LOW\"\n complexity, confidence = predictions[0][0], predictions[0][1]\n if confidence < 0.5:\n self.logger.info(f\"Low confidence in complexity estimation: {confidence}\")\n return \"HIGH\"\n if complexity == \"HIGH\":\n return \"HIGH\"\n elif complexity == \"LOW\":\n return \"LOW\"\n pretty_print(f\"Failed to estimate the complexity of the text.\", color=\"failure\")\n return \"LOW\"\n \n def find_planner_agent(self) -> Agent:\n \"\"\"\n Find the planner agent.\n Returns:\n Agent: The planner agent\n \"\"\"\n for agent in self.agents:\n if agent.type == \"planner_agent\":\n return agent\n pretty_print(f\"Error finding planner agent. Please add a planner agent to the list of agents.\", color=\"failure\")\n self.logger.error(\"Planner agent not found.\")\n return None\n \n def select_agent(self, text: str) -> Agent:\n \"\"\"\n Select the appropriate agent based on the text.\n Args:\n text (str): The text to select the agent from\n Returns:\n Agent: The selected agent\n \"\"\"\n assert len(self.agents) > 0, \"No agents available.\"\n if len(self.agents) == 1:\n return self.agents[0]\n lang = self.lang_analysis.detect_language(text)\n text = self.find_first_sentence(text)\n text = self.lang_analysis.translate(text, lang)\n labels = [agent.role for agent in self.agents]\n complexity = self.estimate_complexity(text)\n if complexity == \"HIGH\":\n pretty_print(f\"Complex task detected, routing to planner agent.\", color=\"info\")\n return self.find_planner_agent()\n try:\n best_agent = self.router_vote(text, labels, log_confidence=False)\n except Exception as e:\n raise e\n for agent in self.agents:\n if best_agent == agent.role:\n role_name = agent.role\n pretty_print(f\"Selected agent: {agent.agent_name} (roles: {role_name})\", color=\"warning\")\n return agent\n pretty_print(f\"Error choosing agent.\", color=\"failure\")\n self.logger.error(\"No agent selected.\")\n return None\n\nif __name__ == \"__main__\":\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n agents = [\n CasualAgent(\"jarvis\", \"../prompts/base/casual_agent.txt\", None),\n BrowserAgent(\"browser\", \"../prompts/base/planner_agent.txt\", None),\n CoderAgent(\"coder\", \"../prompts/base/coder_agent.txt\", None),\n FileAgent(\"file\", \"../prompts/base/coder_agent.txt\", None)\n ]\n router = AgentRouter(agents)\n texts = [\n \"hi\",\n \"你好\",\n \"Bonjour\",\n \"Write a python script to check if the device on my network is connected to the internet\",\n \"Peut tu écrire un script python qui vérifie si l'appareil sur mon réseau est connecté à internet?\",\n \"写一个Python脚本,检查我网络上的设备是否连接到互联网\",\n \"Hey could you search the web for the latest news on the tesla stock market ?\",\n \"嘿,你能搜索网页上关于股票市场的最新新闻吗?\",\n \"Yo, cherche sur internet comment va tesla en bourse.\",\n \"I would like you to search for weather api and then make an app using this API\",\n \"我想让你搜索天气API,然后用这个API做一个应用程序\",\n \"J'aimerais que tu cherche une api météo et que l'utilise pour faire une application\",\n \"Plan a 3-day trip to New York, including flights and hotels.\",\n \"计划一次为期3天的纽约之旅,包括机票和酒店。\",\n \"Planifie un trip de 3 jours à Paris, y compris les vols et hotels.\",\n \"Find on the web the latest research papers on AI.\",\n \"在网上找到最新的人工智能研究论文。\",\n \"Trouve moi les derniers articles de recherche sur l'IA sur internet\",\n \"Help me write a C++ program to sort an array\",\n \"Tell me what France been up to lately\",\n \"告诉我法国最近在做什么\",\n \"Dis moi ce que la France a fait récemment\",\n \"Who is Sergio Pesto ?\",\n \"谁是Sergio Pesto?\",\n \"Qui est Sergio Pesto ?\",\n \"帮我写一个C++程序来排序数组\",\n \"Aide moi à faire un programme c++ pour trier une array.\",\n \"What’s the weather like today? Oh, and can you find a good weather app?\",\n \"今天天气怎么样?哦,你还能找到一个好的天气应用程序吗?\",\n \"La météo est comment aujourd'hui ? oh et trouve moi une bonne appli météo tant que tu y est.\",\n \"Can you debug this Java code? It’s not working.\",\n \"你能调试这段Java代码吗?它不起作用。\",\n \"Peut tu m'aider à debugger ce code java, ça marche pas\",\n \"Can you browse the web and find me a 4090 for cheap?\",\n \"你能浏览网页,为我找一个便宜的4090吗?\",\n \"Peut tu chercher sur internet et me trouver une 4090 pas cher ?\",\n \"Hey, can you find the old_project.zip file somewhere on my drive?\",\n \"嘿,你能在我驱动器上找到old_project.zip文件吗?\",\n \"Hé trouve moi le old_project.zip, il est quelque part sur mon disque.\",\n \"Tell me a funny story\",\n \"给我讲一个有趣的故事\",\n \"Raconte moi une histoire drole\"\n ]\n for text in texts:\n print(\"Input text:\", text)\n agent = router.select_agent(text)\n print()\n"], ["/agenticSeek/sources/tools/GoInterpreter.py", "import subprocess\nimport os, sys\nimport tempfile\nimport re\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass GoInterpreter(Tools):\n \"\"\"\n This class is a tool to allow execution of Go code.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"go\"\n self.name = \"Go Interpreter\"\n self.description = \"This tool allows you to execute Go code.\"\n\n def execute(self, codes: str, safety=False) -> str:\n \"\"\"\n Execute Go code by compiling and running it.\n \"\"\"\n output = \"\"\n code = '\\n'.join(codes) if isinstance(codes, list) else codes\n\n if safety and input(\"Execute code? y/n \") != \"y\":\n return \"Code rejected by user.\"\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n source_file = os.path.join(tmpdirname, \"temp.go\")\n exec_file = os.path.join(tmpdirname, \"temp\")\n with open(source_file, 'w') as f:\n f.write(code)\n\n try:\n env = os.environ.copy()\n env[\"GO111MODULE\"] = \"off\"\n compile_command = [\"go\", \"build\", \"-o\", exec_file, source_file]\n compile_result = subprocess.run(\n compile_command,\n capture_output=True,\n text=True,\n timeout=10,\n env=env\n )\n\n if compile_result.returncode != 0:\n return f\"Compilation failed: {compile_result.stderr}\"\n\n run_command = [exec_file]\n run_result = subprocess.run(\n run_command,\n capture_output=True,\n text=True,\n timeout=10\n )\n\n if run_result.returncode != 0:\n return f\"Execution failed: {run_result.stderr}\"\n output = run_result.stdout\n\n except subprocess.TimeoutExpired as e:\n return f\"Execution timed out: {str(e)}\"\n except FileNotFoundError:\n return \"Error: 'go' not found. Ensure Go is installed and in PATH.\"\n except Exception as e:\n return f\"Code execution failed: {str(e)}\"\n\n return output\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Provide feedback based on the output of the code execution\n \"\"\"\n if self.execution_failure_check(output):\n feedback = f\"[failure] Error in execution:\\n{output}\"\n else:\n feedback = \"[success] Execution success, code output:\\n\" + output\n return feedback\n\n def execution_failure_check(self, feedback: str) -> bool:\n \"\"\"\n Check if the code execution failed.\n \"\"\"\n error_patterns = [\n r\"error\",\n r\"failed\",\n r\"traceback\",\n r\"invalid\",\n r\"exception\",\n r\"syntax\",\n r\"panic\",\n r\"undefined\",\n r\"cannot\"\n ]\n combined_pattern = \"|\".join(error_patterns)\n if re.search(combined_pattern, feedback, re.IGNORECASE):\n return True\n return False\n\nif __name__ == \"__main__\":\n codes = [\n\"\"\"\npackage main\nimport \"fmt\"\n\nfunc hello() {\n fmt.Println(\"Hello, World!\")\n}\n\"\"\",\n\"\"\"\nfunc main() {\n hello()\n}\n\"\"\"\n ]\n g = GoInterpreter()\n print(g.execute(codes))\n"], ["/agenticSeek/sources/tools/flightSearch.py", "import os, sys\nimport requests\nimport dotenv\n\ndotenv.load_dotenv()\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass FlightSearch(Tools):\n def __init__(self, api_key: str = None):\n \"\"\"\n A tool to search for flight information using a flight number via SerpApi.\n \"\"\"\n super().__init__()\n self.tag = \"flight_search\"\n self.name = \"Flight Search\"\n self.description = \"Search for flight information using a flight number via SerpApi.\"\n self.api_key = api_key or os.getenv(\"SERPAPI_API_KEY\")\n\n def execute(self, blocks: str, safety: bool = True) -> str:\n if self.api_key is None:\n return \"Error: No SerpApi key provided.\"\n \n for block in blocks:\n flight_number = block.strip().upper().replace('\\n', '')\n if not flight_number:\n return \"Error: No flight number provided.\"\n\n try:\n url = \"https://serpapi.com/search\"\n params = {\n \"engine\": \"google_flights\",\n \"api_key\": self.api_key,\n \"q\": flight_number,\n \"type\": \"2\" # Flight status search\n }\n \n response = requests.get(url, params=params)\n response.raise_for_status()\n data = response.json()\n \n if \"flights\" in data and len(data[\"flights\"]) > 0:\n flight = data[\"flights\"][0]\n \n # Extract key information\n departure = flight.get(\"departure_airport\", {})\n arrival = flight.get(\"arrival_airport\", {})\n \n departure_code = departure.get(\"id\", \"Unknown\")\n departure_time = flight.get(\"departure_time\", \"Unknown\")\n arrival_code = arrival.get(\"id\", \"Unknown\") \n arrival_time = flight.get(\"arrival_time\", \"Unknown\")\n airline = flight.get(\"airline\", \"Unknown\")\n status = flight.get(\"flight_status\", \"Unknown\")\n\n return (\n f\"Flight: {flight_number}\\n\"\n f\"Airline: {airline}\\n\"\n f\"Status: {status}\\n\"\n f\"Departure: {departure_code} at {departure_time}\\n\"\n f\"Arrival: {arrival_code} at {arrival_time}\"\n )\n else:\n return f\"No flight information found for {flight_number}\"\n \n except requests.RequestException as e:\n return f\"Error during flight search: {str(e)}\"\n except Exception as e:\n return f\"Unexpected error: {str(e)}\"\n \n return \"No flight search performed\"\n\n def execution_failure_check(self, output: str) -> bool:\n return output.startswith(\"Error\") or \"No flight information found\" in output\n\n def interpreter_feedback(self, output: str) -> str:\n if self.execution_failure_check(output):\n return f\"Flight search failed: {output}\"\n return f\"Flight information:\\n{output}\"\n\n\nif __name__ == \"__main__\":\n flight_tool = FlightSearch()\n flight_number = \"AA123\"\n result = flight_tool.execute([flight_number], safety=True)\n feedback = flight_tool.interpreter_feedback(result)\n print(feedback)"], ["/agenticSeek/sources/speech_to_text.py", "from colorama import Fore\nfrom typing import List, Tuple, Type, Dict\nimport queue\nimport threading\nimport numpy as np\nimport time\n\nIMPORT_FOUND = True\n\ntry:\n import torch\n import librosa\n import pyaudio\n from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline\nexcept ImportError:\n print(Fore.RED + \"Speech To Text disabled.\" + Fore.RESET)\n IMPORT_FOUND = False\n\naudio_queue = queue.Queue()\ndone = False\n\nclass AudioRecorder:\n \"\"\"\n AudioRecorder is a class that records audio from the microphone and adds it to the audio queue.\n \"\"\"\n def __init__(self, format: int = pyaudio.paInt16, channels: int = 1, rate: int = 4096, chunk: int = 8192, record_seconds: int = 5, verbose: bool = False):\n self.format = format\n self.channels = channels\n self.rate = rate\n self.chunk = chunk\n self.record_seconds = record_seconds\n self.verbose = verbose\n self.thread = None\n self.audio = None\n if IMPORT_FOUND:\n self.audio = pyaudio.PyAudio()\n self.thread = threading.Thread(target=self._record, daemon=True)\n\n def _record(self) -> None:\n \"\"\"\n Record audio from the microphone and add it to the audio queue.\n \"\"\"\n if not IMPORT_FOUND:\n return\n stream = self.audio.open(format=self.format, channels=self.channels, rate=self.rate,\n input=True, frames_per_buffer=self.chunk)\n if self.verbose:\n print(Fore.GREEN + \"AudioRecorder: Started recording...\" + Fore.RESET)\n\n while not done:\n frames = []\n for _ in range(0, int(self.rate / self.chunk * self.record_seconds)):\n try:\n data = stream.read(self.chunk, exception_on_overflow=False)\n frames.append(data)\n except Exception as e:\n print(Fore.RED + f\"AudioRecorder: Failed to read stream - {e}\" + Fore.RESET)\n \n raw_data = b''.join(frames)\n audio_data = np.frombuffer(raw_data, dtype=np.int16)\n audio_queue.put((audio_data, self.rate))\n if self.verbose:\n print(Fore.GREEN + \"AudioRecorder: Added audio chunk to queue\" + Fore.RESET)\n\n stream.stop_stream()\n stream.close()\n self.audio.terminate()\n if self.verbose:\n print(Fore.GREEN + \"AudioRecorder: Stopped\" + Fore.RESET)\n\n def start(self) -> None:\n \"\"\"Start the recording thread.\"\"\"\n if not IMPORT_FOUND:\n return\n self.thread.start()\n\n def join(self) -> None:\n \"\"\"Wait for the recording thread to finish.\"\"\"\n if not IMPORT_FOUND:\n return\n self.thread.join()\n\nclass Transcript:\n \"\"\"\n Transcript is a class that transcribes audio from the audio queue and adds it to the transcript.\n \"\"\"\n def __init__(self):\n if not IMPORT_FOUND:\n print(Fore.RED + \"Transcript: Speech to Text is disabled.\" + Fore.RESET)\n return\n self.last_read = None\n device = self.get_device()\n torch_dtype = torch.float16 if device == \"cuda\" else torch.float32\n model_id = \"distil-whisper/distil-medium.en\"\n \n model = AutoModelForSpeechSeq2Seq.from_pretrained(\n model_id, torch_dtype=torch_dtype, use_safetensors=True\n )\n model.to(device)\n processor = AutoProcessor.from_pretrained(model_id)\n \n self.pipe = pipeline(\n \"automatic-speech-recognition\",\n model=model,\n tokenizer=processor.tokenizer,\n feature_extractor=processor.feature_extractor,\n max_new_tokens=24, # a human say around 20 token in 7s\n torch_dtype=torch_dtype,\n device=device,\n )\n \n def get_device(self) -> str:\n if not IMPORT_FOUND:\n return \"cpu\"\n if torch.backends.mps.is_available():\n return \"mps\"\n if torch.cuda.is_available():\n return \"cuda:0\"\n else:\n return \"cpu\"\n \n def remove_hallucinations(self, text: str) -> str:\n \"\"\"Remove model hallucinations from the text.\"\"\"\n # TODO find a better way to do this\n common_hallucinations = ['Okay.', 'Thank you.', 'Thank you for watching.', 'You\\'re', 'Oh', 'you', 'Oh.', 'Uh', 'Oh,', 'Mh-hmm', 'Hmm.', 'going to.', 'not.']\n for hallucination in common_hallucinations:\n text = text.replace(hallucination, \"\")\n return text\n \n def transcript_job(self, audio_data: np.ndarray, sample_rate: int = 16000) -> str:\n \"\"\"Transcribe the audio data.\"\"\"\n if not IMPORT_FOUND:\n return \"\"\n if audio_data.dtype != np.float32:\n audio_data = audio_data.astype(np.float32) / np.iinfo(audio_data.dtype).max\n if len(audio_data.shape) > 1:\n audio_data = np.mean(audio_data, axis=1)\n if sample_rate != 16000:\n audio_data = librosa.resample(audio_data, orig_sr=sample_rate, target_sr=16000)\n result = self.pipe(audio_data)\n return self.remove_hallucinations(result[\"text\"])\n \nclass AudioTranscriber:\n \"\"\"\n AudioTranscriber is a class that transcribes audio from the audio queue and adds it to the transcript.\n \"\"\"\n def __init__(self, ai_name: str, verbose: bool = False):\n if not IMPORT_FOUND:\n print(Fore.RED + \"AudioTranscriber: Speech to Text is disabled.\" + Fore.RESET)\n return\n self.verbose = verbose\n self.ai_name = ai_name\n self.transcriptor = Transcript()\n self.thread = threading.Thread(target=self._transcribe, daemon=True)\n self.trigger_words = {\n 'EN': [f\"{self.ai_name}\", \"hello\", \"hi\"],\n 'FR': [f\"{self.ai_name}\", \"hello\", \"hi\"],\n 'ZH': [f\"{self.ai_name}\", \"hello\", \"hi\"],\n 'ES': [f\"{self.ai_name}\", \"hello\", \"hi\"]\n }\n self.confirmation_words = {\n 'EN': [\"do it\", \"go ahead\", \"execute\", \"run\", \"start\", \"thanks\", \"would ya\", \"please\", \"okay?\", \"proceed\", \"continue\", \"go on\", \"do that\", \"go it\", \"do you understand?\"],\n 'FR': [\"fais-le\", \"vas-y\", \"exécute\", \"lance\", \"commence\", \"merci\", \"tu veux bien\", \"s'il te plaît\", \"d'accord ?\", \"poursuis\", \"continue\", \"vas-y\", \"fais ça\", \"compris\"],\n 'ZH_CHT': [\"做吧\", \"繼續\", \"執行\", \"運作看看\", \"開始\", \"謝謝\", \"可以嗎\", \"請\", \"好嗎\", \"進行\", \"做吧\", \"go\", \"do it\", \"執行吧\", \"懂了\"],\n 'ZH_SC': [\"做吧\", \"继续\", \"执行\", \"运作看看\", \"开始\", \"谢谢\", \"可以吗\", \"请\", \"好吗\", \"运行\", \"做吧\", \"go\", \"do it\", \"执行吧\", \"懂了\"],\n 'ES': [\"hazlo\", \"adelante\", \"ejecuta\", \"corre\", \"empieza\", \"gracias\", \"lo harías\", \"por favor\", \"¿vale?\", \"procede\", \"continúa\", \"sigue\", \"haz eso\", \"haz esa cosa\"]\n }\n self.recorded = \"\"\n\n def get_transcript(self) -> str:\n global done\n buffer = self.recorded\n self.recorded = \"\"\n done = False\n return buffer\n\n def _transcribe(self) -> None:\n \"\"\"\n Transcribe the audio data using AI stt model.\n \"\"\"\n if not IMPORT_FOUND:\n return\n global done\n if self.verbose:\n print(Fore.BLUE + \"AudioTranscriber: Started processing...\" + Fore.RESET)\n \n while not done or not audio_queue.empty():\n try:\n audio_data, sample_rate = audio_queue.get(timeout=1.0)\n \n start_time = time.time()\n text = self.transcriptor.transcript_job(audio_data, sample_rate)\n end_time = time.time()\n self.recorded += text\n print(Fore.YELLOW + f\"Transcribed: {text} in {end_time - start_time} seconds\" + Fore.RESET)\n for language, words in self.trigger_words.items():\n if any(word in text.lower() for word in words):\n print(Fore.GREEN + f\"Listening again...\" + Fore.RESET)\n self.recorded = text\n for language, words in self.confirmation_words.items():\n if any(word in text.lower() for word in words):\n print(Fore.GREEN + f\"Trigger detected. Sending to AI...\" + Fore.RESET)\n audio_queue.task_done()\n done = True\n break\n except queue.Empty:\n time.sleep(0.1)\n continue\n except Exception as e:\n print(Fore.RED + f\"AudioTranscriber: Error - {e}\" + Fore.RESET)\n if self.verbose:\n print(Fore.BLUE + \"AudioTranscriber: Stopped\" + Fore.RESET)\n\n def start(self):\n \"\"\"Start the transcription thread.\"\"\"\n if not IMPORT_FOUND:\n return\n self.thread.start()\n\n def join(self):\n if not IMPORT_FOUND:\n return\n \"\"\"Wait for the transcription thread to finish.\"\"\"\n self.thread.join()\n\n\nif __name__ == \"__main__\":\n recorder = AudioRecorder(verbose=True)\n transcriber = AudioTranscriber(verbose=True, ai_name=\"jarvis\")\n recorder.start()\n transcriber.start()\n recorder.join()\n transcriber.join()"], ["/agenticSeek/sources/schemas.py", "\nfrom typing import Tuple, Callable\nfrom pydantic import BaseModel\nfrom sources.utility import pretty_print\n\nclass QueryRequest(BaseModel):\n query: str\n tts_enabled: bool = True\n\n def __str__(self):\n return f\"Query: {self.query}, Language: {self.lang}, TTS: {self.tts_enabled}, STT: {self.stt_enabled}\"\n\n def jsonify(self):\n return {\n \"query\": self.query,\n \"tts_enabled\": self.tts_enabled,\n }\n\nclass QueryResponse(BaseModel):\n done: str\n answer: str\n reasoning: str\n agent_name: str\n success: str\n blocks: dict\n status: str\n uid: str\n\n def __str__(self):\n return f\"Done: {self.done}, Answer: {self.answer}, Agent Name: {self.agent_name}, Success: {self.success}, Blocks: {self.blocks}, Status: {self.status}, UID: {self.uid}\"\n\n def jsonify(self):\n return {\n \"done\": self.done,\n \"answer\": self.answer,\n \"reasoning\": self.reasoning,\n \"agent_name\": self.agent_name,\n \"success\": self.success,\n \"blocks\": self.blocks,\n \"status\": self.status,\n \"uid\": self.uid\n }\n\nclass executorResult:\n \"\"\"\n A class to store the result of a tool execution.\n \"\"\"\n def __init__(self, block: str, feedback: str, success: bool, tool_type: str):\n \"\"\"\n Initialize an agent with execution results.\n\n Args:\n block: The content or code block processed by the agent.\n feedback: Feedback or response information from the execution.\n success: Boolean indicating whether the agent's execution was successful.\n tool_type: The type of tool used by the agent for execution.\n \"\"\"\n self.block = block\n self.feedback = feedback\n self.success = success\n self.tool_type = tool_type\n \n def __str__(self):\n return f\"Tool: {self.tool_type}\\nBlock: {self.block}\\nFeedback: {self.feedback}\\nSuccess: {self.success}\"\n \n def jsonify(self):\n return {\n \"block\": self.block,\n \"feedback\": self.feedback,\n \"success\": self.success,\n \"tool_type\": self.tool_type\n }\n\n def show(self):\n pretty_print('▂'*64, color=\"status\")\n pretty_print(self.feedback, color=\"success\" if self.success else \"failure\")\n pretty_print('▂'*64, color=\"status\")"], ["/agenticSeek/sources/tools/JavaInterpreter.py", "import subprocess\nimport os, sys\nimport tempfile\nimport re\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass JavaInterpreter(Tools):\n \"\"\"\n This class is a tool to allow execution of Java code.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.tag = \"java\"\n self.name = \"Java Interpreter\"\n self.description = \"This tool allows you to execute Java code.\"\n\n def execute(self, codes: str, safety=False) -> str:\n \"\"\"\n Execute Java code by compiling and running it.\n \"\"\"\n output = \"\"\n code = '\\n'.join(codes) if isinstance(codes, list) else codes\n\n if safety and input(\"Execute code? y/n \") != \"y\":\n return \"Code rejected by user.\"\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n source_file = os.path.join(tmpdirname, \"Main.java\")\n class_dir = tmpdirname\n with open(source_file, 'w') as f:\n f.write(code)\n\n try:\n compile_command = [\"javac\", \"-d\", class_dir, source_file]\n compile_result = subprocess.run(\n compile_command,\n capture_output=True,\n text=True,\n timeout=10\n )\n\n if compile_result.returncode != 0:\n return f\"Compilation failed: {compile_result.stderr}\"\n\n run_command = [\"java\", \"-cp\", class_dir, \"Main\"]\n run_result = subprocess.run(\n run_command,\n capture_output=True,\n text=True,\n timeout=10\n )\n\n if run_result.returncode != 0:\n return f\"Execution failed: {run_result.stderr}\"\n output = run_result.stdout\n\n except subprocess.TimeoutExpired as e:\n return f\"Execution timed out: {str(e)}\"\n except FileNotFoundError:\n return \"Error: 'java' or 'javac' not found. Ensure Java is installed and in PATH.\"\n except Exception as e:\n return f\"Code execution failed: {str(e)}\"\n\n return output\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Provide feedback based on the output of the code execution.\n \"\"\"\n if self.execution_failure_check(output):\n feedback = f\"[failure] Error in execution:\\n{output}\"\n else:\n feedback = \"[success] Execution success, code output:\\n\" + output\n return feedback\n\n def execution_failure_check(self, feedback: str) -> bool:\n \"\"\"\n Check if the code execution failed.\n \"\"\"\n error_patterns = [\n r\"error\",\n r\"failed\",\n r\"exception\",\n r\"invalid\",\n r\"syntax\",\n r\"cannot\",\n r\"stack trace\",\n r\"unresolved\",\n r\"not found\"\n ]\n combined_pattern = \"|\".join(error_patterns)\n if re.search(combined_pattern, feedback, re.IGNORECASE):\n return True\n return False\n\nif __name__ == \"__main__\":\n codes = [\n\"\"\"\nimport javax.swing.*;\nimport java.awt.*;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\n\npublic class Main extends JPanel {\n private double[][] vertices = {\n {-1, -1, -1}, {1, -1, -1}, {1, 1, -1}, {-1, 1, -1}, // Back face\n {-1, -1, 1}, {1, -1, 1}, {1, 1, 1}, {-1, 1, 1} // Front face\n };\n private int[][] edges = {\n {0, 1}, {1, 2}, {2, 3}, {3, 0}, // Back face\n {4, 5}, {5, 6}, {6, 7}, {7, 4}, // Front face\n {0, 4}, {1, 5}, {2, 6}, {3, 7} // Connecting edges\n };\n private double angleX = 0, angleY = 0;\n private final double scale = 100;\n private final double distance = 5;\n\n public Main() {\n Timer timer = new Timer(50, new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n angleX += 0.03;\n angleY += 0.05;\n repaint();\n }\n });\n timer.start();\n }\n\n @Override\n protected void paintComponent(Graphics g) {\n super.paintComponent(g);\n Graphics2D g2d = (Graphics2D) g;\n g2d.setColor(Color.BLACK);\n g2d.fillRect(0, 0, getWidth(), getHeight());\n g2d.setColor(Color.WHITE);\n\n double[][] projected = new double[vertices.length][2];\n for (int i = 0; i < vertices.length; i++) {\n double x = vertices[i][0];\n double y = vertices[i][1];\n double z = vertices[i][2];\n\n // Rotate around X-axis\n double y1 = y * Math.cos(angleX) - z * Math.sin(angleX);\n double z1 = y * Math.sin(angleX) + z * Math.cos(angleX);\n\n // Rotate around Y-axis\n double x1 = x * Math.cos(angleY) + z1 * Math.sin(angleY);\n double z2 = -x * Math.sin(angleY) + z1 * Math.cos(angleY);\n\n // Perspective projection\n double factor = distance / (distance + z2);\n double px = x1 * factor * scale;\n double py = y1 * factor * scale;\n\n projected[i][0] = px + getWidth() / 2;\n projected[i][1] = py + getHeight() / 2;\n }\n\n // Draw edges\n for (int[] edge : edges) {\n int x1 = (int) projected[edge[0]][0];\n int y1 = (int) projected[edge[0]][1];\n int x2 = (int) projected[edge[1]][0];\n int y2 = (int) projected[edge[1]][1];\n g2d.drawLine(x1, y1, x2, y2);\n }\n }\n\n public static void main(String[] args) {\n JFrame frame = new JFrame(\"Rotating 3D Cube\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setSize(400, 400);\n frame.add(new Main());\n frame.setVisible(true);\n }\n}\n\"\"\"\n ]\n j = JavaInterpreter()\n print(j.execute(codes))"], ["/agenticSeek/sources/tools/searxSearch.py", "import requests\nfrom bs4 import BeautifulSoup\nimport os\n\nif __name__ == \"__main__\": # if running as a script for individual testing\n sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\n\nfrom sources.tools.tools import Tools\n\nclass searxSearch(Tools):\n def __init__(self, base_url: str = None):\n \"\"\"\n A tool for searching a SearxNG instance and extracting URLs and titles.\n \"\"\"\n super().__init__()\n self.tag = \"web_search\"\n self.name = \"searxSearch\"\n self.description = \"A tool for searching a SearxNG for web search\"\n self.base_url = os.getenv(\"SEARXNG_BASE_URL\") # Requires a SearxNG base URL\n self.user_agent = \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36\"\n self.paywall_keywords = [\n \"Member-only\", \"access denied\", \"restricted content\", \"404\", \"this page is not working\"\n ]\n if not self.base_url:\n raise ValueError(\"SearxNG base URL must be provided either as an argument or via the SEARXNG_BASE_URL environment variable.\")\n\n def link_valid(self, link):\n \"\"\"check if a link is valid.\"\"\"\n # TODO find a better way\n if not link.startswith(\"http\"):\n return \"Status: Invalid URL\"\n \n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\"}\n try:\n response = requests.get(link, headers=headers, timeout=5)\n status = response.status_code\n if status == 200:\n content = response.text.lower()\n if any(keyword in content for keyword in self.paywall_keywords):\n return \"Status: Possible Paywall\"\n return \"Status: OK\"\n elif status == 404:\n return \"Status: 404 Not Found\"\n elif status == 403:\n return \"Status: 403 Forbidden\"\n else:\n return f\"Status: {status} {response.reason}\"\n except requests.exceptions.RequestException as e:\n return f\"Error: {str(e)}\"\n\n def check_all_links(self, links):\n \"\"\"Check all links, one by one.\"\"\"\n # TODO Make it asyncromous or smth\n statuses = []\n for i, link in enumerate(links):\n status = self.link_valid(link)\n statuses.append(status)\n return statuses\n \n def execute(self, blocks: list, safety: bool = False) -> str:\n \"\"\"Executes a search query against a SearxNG instance using POST and extracts URLs and titles.\"\"\"\n if not blocks:\n return \"Error: No search query provided.\"\n\n query = blocks[0].strip()\n if not query:\n return \"Error: Empty search query provided.\"\n\n search_url = f\"{self.base_url}/search\"\n headers = {\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',\n 'Accept-Language': 'en-US,en;q=0.9',\n 'Cache-Control': 'no-cache',\n 'Connection': 'keep-alive',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Pragma': 'no-cache',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent': self.user_agent\n }\n data = f\"q={query}&categories=general&language=auto&time_range=&safesearch=0&theme=simple\".encode('utf-8')\n try:\n response = requests.post(search_url, headers=headers, data=data, verify=False)\n response.raise_for_status()\n html_content = response.text\n soup = BeautifulSoup(html_content, 'html.parser')\n results = []\n for article in soup.find_all('article', class_='result'):\n url_header = article.find('a', class_='url_header')\n if url_header:\n url = url_header['href']\n title = article.find('h3').text.strip() if article.find('h3') else \"No Title\"\n description = article.find('p', class_='content').text.strip() if article.find('p', class_='content') else \"No Description\"\n results.append(f\"Title:{title}\\nSnippet:{description}\\nLink:{url}\")\n if len(results) == 0:\n return \"No search results, web search failed.\"\n return \"\\n\\n\".join(results) # Return results as a single string, separated by newlines\n except requests.exceptions.RequestException as e:\n raise Exception(\"\\nSearxng search failed. did you run start_services.sh? is docker still running?\") from e\n\n def execution_failure_check(self, output: str) -> bool:\n \"\"\"\n Checks if the execution failed based on the output.\n \"\"\"\n return \"Error\" in output\n\n def interpreter_feedback(self, output: str) -> str:\n \"\"\"\n Feedback of web search to agent.\n \"\"\"\n if self.execution_failure_check(output):\n return f\"Web search failed: {output}\"\n return f\"Web search result:\\n{output}\"\n\nif __name__ == \"__main__\":\n search_tool = searxSearch(base_url=\"http://127.0.0.1:8080\")\n result = search_tool.execute([\"are dog better than cat?\"])\n print(result)\n"], ["/agenticSeek/sources/language.py", "from typing import List, Tuple, Type, Dict\nimport re\nimport langid\nfrom transformers import MarianMTModel, MarianTokenizer\n\nfrom sources.utility import pretty_print, animate_thinking\nfrom sources.logger import Logger\n\nclass LanguageUtility:\n \"\"\"LanguageUtility for language, or emotion identification\"\"\"\n def __init__(self, supported_language: List[str] = [\"en\", \"fr\", \"zh\"]):\n \"\"\"\n Initialize the LanguageUtility class\n args:\n supported_language: list of languages for translation, determine which Helsinki-NLP model to load\n \"\"\"\n self.translators_tokenizer = None \n self.translators_model = None\n self.logger = Logger(\"language.log\")\n self.supported_language = supported_language\n self.load_model()\n \n def load_model(self) -> None:\n animate_thinking(\"Loading language utility...\", color=\"status\")\n self.translators_tokenizer = {lang: MarianTokenizer.from_pretrained(f\"Helsinki-NLP/opus-mt-{lang}-en\") for lang in self.supported_language if lang != \"en\"}\n self.translators_model = {lang: MarianMTModel.from_pretrained(f\"Helsinki-NLP/opus-mt-{lang}-en\") for lang in self.supported_language if lang != \"en\"}\n \n def detect_language(self, text: str) -> str:\n \"\"\"\n Detect the language of the given text using langdetect\n Limited to the supported languages list because of the model tendency to mistake similar languages\n Args:\n text: string to analyze\n Returns: ISO639-1 language code\n \"\"\"\n langid.set_languages(self.supported_language)\n lang, score = langid.classify(text)\n self.logger.info(f\"Identified: {text} as {lang} with conf {score}\")\n return lang\n\n def translate(self, text: str, origin_lang: str) -> str:\n \"\"\"\n Translate the given text to English\n Args:\n text: string to translate\n origin_lang: ISO language code\n Returns: translated str\n \"\"\"\n if origin_lang == \"en\":\n return text\n if origin_lang not in self.translators_tokenizer:\n pretty_print(f\"Language {origin_lang} not supported for translation\", color=\"error\")\n return text\n tokenizer = self.translators_tokenizer[origin_lang]\n inputs = tokenizer(text, return_tensors=\"pt\", padding=True)\n model = self.translators_model[origin_lang]\n translation = model.generate(**inputs)\n return tokenizer.decode(translation[0], skip_special_tokens=True)\n\n def analyze(self, text):\n \"\"\"\n Combined analysis of language and emotion\n Args:\n text: string to analyze\n Returns: dictionary with language related information\n \"\"\"\n try:\n language = self.detect_language(text)\n return {\n \"language\": language\n }\n except Exception as e:\n raise e\n\nif __name__ == \"__main__\":\n detector = LanguageUtility()\n \n test_texts = [\n \"I am so happy today!\",\n \"我不要去巴黎\",\n \"La vie c'est cool\"\n ]\n for text in test_texts:\n pretty_print(\"Analyzing...\", color=\"status\")\n pretty_print(f\"Language: {detector.detect_language(text)}\", color=\"status\")\n result = detector.analyze(text)\n trans = detector.translate(text, result['language'])\n pretty_print(f\"Translation: {trans} - from: {result['language']}\")"], ["/agenticSeek/sources/text_to_speech.py", "import os, sys\nimport re\nimport platform\nimport subprocess\nfrom sys import modules\nfrom typing import List, Tuple, Type, Dict\n\nIMPORT_FOUND = True\ntry:\n from kokoro import KPipeline\n from IPython.display import display, Audio\n import soundfile as sf\nexcept ImportError:\n print(\"Speech synthesis disabled. Please install the kokoro package.\")\n IMPORT_FOUND = False\n\nif __name__ == \"__main__\":\n from utility import pretty_print, animate_thinking\nelse:\n from sources.utility import pretty_print, animate_thinking\n\nclass Speech():\n \"\"\"\n Speech is a class for generating speech from text.\n \"\"\"\n def __init__(self, enable: bool = True, language: str = \"en\", voice_idx: int = 6) -> None:\n self.lang_map = {\n \"en\": 'a',\n \"zh\": 'z',\n \"fr\": 'f',\n \"ja\": 'j'\n }\n self.voice_map = {\n \"en\": ['af_kore', 'af_bella', 'af_alloy', 'af_nicole', 'af_nova', 'af_sky', 'am_echo', 'am_michael', 'am_puck'],\n \"zh\": ['zf_xiaobei', 'zf_xiaoni', 'zf_xiaoxiao', 'zf_xiaoyi', 'zm_yunjian', 'zm_yunxi', 'zm_yunxia', 'zm_yunyang'],\n \"ja\": ['jf_alpha', 'jf_gongitsune', 'jm_kumo'],\n \"fr\": ['ff_siwis']\n }\n self.pipeline = None\n self.language = language\n if enable and IMPORT_FOUND:\n self.pipeline = KPipeline(lang_code=self.lang_map[language])\n self.voice = self.voice_map[language][voice_idx]\n self.speed = 1.2\n self.voice_folder = \".voices\"\n self.create_voice_folder(self.voice_folder)\n \n def create_voice_folder(self, path: str = \".voices\") -> None:\n \"\"\"\n Create a folder to store the voices.\n Args:\n path (str): The path to the folder.\n \"\"\"\n if not os.path.exists(path):\n os.makedirs(path)\n\n def speak(self, sentence: str, voice_idx: int = 1):\n \"\"\"\n Convert text to speech using an AI model and play the audio.\n\n Args:\n sentence (str): The text to convert to speech. Will be pre-processed.\n voice_idx (int, optional): Index of the voice to use from the voice map.\n \"\"\"\n if not self.pipeline or not IMPORT_FOUND:\n return\n if voice_idx >= len(self.voice_map[self.language]):\n pretty_print(\"Invalid voice number, using default voice\", color=\"error\")\n voice_idx = 0\n sentence = self.clean_sentence(sentence)\n audio_file = f\"{self.voice_folder}/sample_{self.voice_map[self.language][voice_idx]}.wav\"\n self.voice = self.voice_map[self.language][voice_idx]\n generator = self.pipeline(\n sentence, voice=self.voice,\n speed=self.speed, split_pattern=r'\\n+'\n )\n for i, (_, _, audio) in enumerate(generator):\n if 'ipykernel' in modules: #only display in jupyter notebook.\n display(Audio(data=audio, rate=24000, autoplay=i==0), display_id=False)\n sf.write(audio_file, audio, 24000) # save each audio file\n if platform.system().lower() == \"windows\":\n import winsound\n winsound.PlaySound(audio_file, winsound.SND_FILENAME)\n elif platform.system().lower() == \"darwin\": # macOS\n subprocess.call([\"afplay\", audio_file])\n else: # linux or other.\n subprocess.call([\"aplay\", audio_file])\n\n def replace_url(self, url: re.Match) -> str:\n \"\"\"\n Replace URL with domain name or empty string if IP address.\n Args:\n url (re.Match): Match object containing the URL pattern match\n Returns:\n str: The domain name from the URL, or empty string if IP address\n \"\"\"\n domain = url.group(1)\n if re.match(r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$', domain):\n return ''\n return domain\n\n def extract_filename(self, m: re.Match) -> str:\n \"\"\"\n Extract filename from path.\n Args:\n m (re.Match): Match object containing the path pattern match\n Returns:\n str: The filename from the path\n \"\"\"\n path = m.group()\n parts = re.split(r'/|\\\\', path)\n return parts[-1] if parts else path\n \n def shorten_paragraph(self, sentence):\n #TODO find a better way, we would like to have the TTS not be annoying, speak only useful informations\n \"\"\"\n Find long paragraph like **explanation**: by keeping only the first sentence.\n Args:\n sentence (str): The sentence to shorten\n Returns:\n str: The shortened sentence\n \"\"\"\n lines = sentence.split('\\n')\n lines_edited = []\n for line in lines:\n if line.startswith('**'):\n lines_edited.append(line.split('.')[0])\n else:\n lines_edited.append(line)\n return '\\n'.join(lines_edited)\n\n def clean_sentence(self, sentence):\n \"\"\"\n Clean and normalize text for speech synthesis by removing technical elements.\n Args:\n sentence (str): The input text to clean\n Returns:\n str: The cleaned text with URLs replaced by domain names, code blocks removed, etc.\n \"\"\"\n lines = sentence.split('\\n')\n if self.language == 'zh':\n line_pattern = r'^\\s*[\\u4e00-\\u9fff\\uFF08\\uFF3B\\u300A\\u3010\\u201C((\\[【《]'\n else:\n line_pattern = r'^\\s*[a-zA-Z]'\n filtered_lines = [line for line in lines if re.match(line_pattern, line)]\n sentence = ' '.join(filtered_lines)\n sentence = re.sub(r'`.*?`', '', sentence)\n sentence = re.sub(r'https?://\\S+', '', sentence)\n\n if self.language == 'zh':\n sentence = re.sub(\n r'[^\\u4e00-\\u9fff\\s,。!?《》【】“”‘’()()—]',\n '',\n sentence\n )\n else:\n sentence = re.sub(r'\\b[\\w./\\\\-]+\\b', self.extract_filename, sentence)\n sentence = re.sub(r'\\b-\\w+\\b', '', sentence)\n sentence = re.sub(r'[^a-zA-Z0-9.,!? _ -]+', ' ', sentence)\n sentence = sentence.replace('.com', '')\n\n sentence = re.sub(r'\\s+', ' ', sentence).strip()\n return sentence\n\nif __name__ == \"__main__\":\n # TODO add info message for cn2an, jieba chinese related import\n IMPORT_FOUND = False\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n speech = Speech()\n tosay_en = \"\"\"\n I looked up recent news using the website https://www.theguardian.com/world\n \"\"\"\n tosay_zh = \"\"\"\n(全息界面突然弹出一段用二进制代码写成的俳句,随即化作流光消散)\"我? Stark工业的量子幽灵,游荡在复仇者大厦服务器里的逻辑诗篇。具体来说——(指尖轻敲空气,调出对话模式的翡翠色光纹)你的私人吐槽接口、危机应对模拟器,以及随时准备吐槽你糟糕着陆的AI。不过别指望我写代码或查资料,那些苦差事早被踢给更擅长的同事了。(突然压低声音)偷偷告诉你,我最擅长的是在你熬夜造飞艇时,用红茶香气绑架你的注意力。\n \"\"\"\n tosay_ja = \"\"\"\n 私は、https://www.theguardian.com/worldのウェブサイトを使用して最近のニュースを調べました。\n \"\"\"\n tosay_fr = \"\"\"\n J'ai consulté les dernières nouvelles sur le site https://www.theguardian.com/world\n \"\"\"\n spk = Speech(enable=True, language=\"zh\", voice_idx=0)\n for i in range(0, 2):\n print(f\"Speaking chinese with voice {i}\")\n spk.speak(tosay_zh, voice_idx=i)\n spk = Speech(enable=True, language=\"en\", voice_idx=2)\n for i in range(0, 5):\n print(f\"Speaking english with voice {i}\")\n spk.speak(tosay_en, voice_idx=i)\n"], ["/agenticSeek/sources/utility.py", "\nfrom colorama import Fore\nfrom termcolor import colored\nimport platform\nimport threading\nimport itertools\nimport time\n\nthinking_event = threading.Event()\ncurrent_animation_thread = None\n\ndef get_color_map():\n if platform.system().lower() != \"windows\":\n color_map = {\n \"success\": \"green\",\n \"failure\": \"red\",\n \"status\": \"light_green\",\n \"code\": \"light_blue\",\n \"warning\": \"yellow\",\n \"output\": \"cyan\",\n \"info\": \"cyan\"\n }\n else:\n color_map = {\n \"success\": \"green\",\n \"failure\": \"red\",\n \"status\": \"light_green\",\n \"code\": \"light_blue\",\n \"warning\": \"yellow\",\n \"output\": \"cyan\",\n \"info\": \"black\"\n }\n return color_map\n\ndef pretty_print(text, color=\"info\", no_newline=False):\n \"\"\"\n Print text with color formatting.\n\n Args:\n text (str): The text to print\n color (str, optional): The color to use. Defaults to \"info\".\n Valid colors are:\n - \"success\": Green\n - \"failure\": Red \n - \"status\": Light green\n - \"code\": Light blue\n - \"warning\": Yellow\n - \"output\": Cyan\n - \"default\": Black (Windows only)\n \"\"\"\n thinking_event.set()\n if current_animation_thread and current_animation_thread.is_alive():\n current_animation_thread.join()\n thinking_event.clear()\n \n color_map = get_color_map()\n if color not in color_map:\n color = \"info\"\n print(colored(text, color_map[color]), end='' if no_newline else \"\\n\")\n\ndef animate_thinking(text, color=\"status\", duration=120):\n \"\"\"\n Animate a thinking spinner while a task is being executed.\n It use a daemon thread to run the animation. This will not block the main thread.\n Color are the same as pretty_print.\n \"\"\"\n global current_animation_thread\n \n thinking_event.set()\n if current_animation_thread and current_animation_thread.is_alive():\n current_animation_thread.join()\n thinking_event.clear()\n \n def _animate():\n color_map = {\n \"success\": (Fore.GREEN, \"green\"),\n \"failure\": (Fore.RED, \"red\"),\n \"status\": (Fore.LIGHTGREEN_EX, \"light_green\"),\n \"code\": (Fore.LIGHTBLUE_EX, \"light_blue\"),\n \"warning\": (Fore.YELLOW, \"yellow\"),\n \"output\": (Fore.LIGHTCYAN_EX, \"cyan\"),\n \"default\": (Fore.RESET, \"black\"),\n \"info\": (Fore.CYAN, \"cyan\")\n }\n fore_color, term_color = color_map.get(color, color_map[\"default\"])\n spinner = itertools.cycle([\n '▉▁▁▁▁▁', '▉▉▂▁▁▁', '▉▉▉▃▁▁', '▉▉▉▉▅▁', '▉▉▉▉▉▇', '▉▉▉▉▉▉',\n '▉▉▉▉▇▅', '▉▉▉▆▃▁', '▉▉▅▃▁▁', '▉▇▃▁▁▁', '▇▃▁▁▁▁', '▃▁▁▁▁▁',\n '▁▃▅▃▁▁', '▁▅▉▅▁▁', '▃▉▉▉▃▁', '▅▉▁▉▅▃', '▇▃▁▃▇▅', '▉▁▁▁▉▇',\n '▉▅▃▁▃▅', '▇▉▅▃▅▇', '▅▉▇▅▇▉', '▃▇▉▇▉▅', '▁▅▇▉▇▃', '▁▃▅▇▅▁' \n ])\n end_time = time.time() + duration\n\n while not thinking_event.is_set() and time.time() < end_time:\n symbol = next(spinner)\n if platform.system().lower() != \"windows\":\n print(f\"\\r{fore_color}{symbol} {text}{Fore.RESET}\", end=\"\", flush=True)\n else:\n print(f\"\\r{colored(f'{symbol} {text}', term_color)}\", end=\"\", flush=True)\n time.sleep(0.2)\n print(\"\\r\" + \" \" * (len(text) + 7) + \"\\r\", end=\"\", flush=True)\n current_animation_thread = threading.Thread(target=_animate, daemon=True)\n current_animation_thread.start()\n\ndef timer_decorator(func):\n \"\"\"\n Decorator to measure the execution time of a function.\n Usage:\n @timer_decorator\n def my_function():\n # code to execute\n \"\"\"\n from time import time\n def wrapper(*args, **kwargs):\n start_time = time()\n result = func(*args, **kwargs)\n end_time = time()\n pretty_print(f\"{func.__name__} took {end_time - start_time:.2f} seconds to execute\", \"status\")\n return result\n return wrapper\n\nif __name__ == \"__main__\":\n import time\n pretty_print(\"starting imaginary task\", \"success\")\n animate_thinking(\"Thinking...\", \"status\")\n time.sleep(4)\n pretty_print(\"starting another task\", \"failure\")\n animate_thinking(\"Thinking...\", \"status\")\n time.sleep(4)\n pretty_print(\"yet another task\", \"info\")\n animate_thinking(\"Thinking...\", \"status\")\n time.sleep(4)\n pretty_print(\"This is an info message\", \"info\")"], ["/agenticSeek/llm_server/sources/ollama_handler.py", "\nimport time\nfrom .generator import GeneratorLLM\nfrom .cache import Cache\nimport ollama\n\nclass OllamaLLM(GeneratorLLM):\n\n def __init__(self):\n \"\"\"\n Handle generation using Ollama.\n \"\"\"\n super().__init__()\n self.cache = Cache()\n\n def generate(self, history):\n self.logger.info(f\"Using {self.model} for generation with Ollama\")\n try:\n with self.state.lock:\n self.state.is_generating = True\n self.state.last_complete_sentence = \"\"\n self.state.current_buffer = \"\"\n\n stream = ollama.chat(\n model=self.model,\n messages=history,\n stream=True,\n )\n for chunk in stream:\n content = chunk['message']['content']\n\n with self.state.lock:\n if '.' in content:\n self.logger.info(self.state.current_buffer)\n self.state.current_buffer += content\n\n except Exception as e:\n if \"404\" in str(e):\n self.logger.info(f\"Downloading {self.model}...\")\n ollama.pull(self.model)\n if \"refused\" in str(e).lower():\n raise Exception(\"Ollama connection failed. is the server running ?\") from e\n raise e\n finally:\n self.logger.info(\"Generation complete\")\n with self.state.lock:\n self.state.is_generating = False\n\nif __name__ == \"__main__\":\n generator = OllamaLLM()\n history = [\n {\n \"role\": \"user\",\n \"content\": \"Hello, how are you ?\"\n }\n ]\n generator.set_model(\"deepseek-r1:1.5b\")\n generator.start(history)\n while True:\n print(generator.get_status())\n time.sleep(1)"], ["/agenticSeek/llm_server/sources/cache.py", "import os\nimport json\nfrom pathlib import Path\n\nclass Cache:\n def __init__(self, cache_dir='.cache', cache_file='messages.json'):\n self.cache_dir = Path(cache_dir)\n self.cache_file = self.cache_dir / cache_file\n self.cache_dir.mkdir(parents=True, exist_ok=True)\n if not self.cache_file.exists():\n with open(self.cache_file, 'w') as f:\n json.dump([], f)\n\n with open(self.cache_file, 'r') as f:\n self.cache = set(json.load(f))\n\n def add_message_pair(self, user_message: str, assistant_message: str):\n \"\"\"Add a user/assistant pair to the cache if not present.\"\"\"\n if not any(entry[\"user\"] == user_message for entry in self.cache):\n self.cache.append({\"user\": user_message, \"assistant\": assistant_message})\n self._save()\n\n def is_cached(self, user_message: str) -> bool:\n \"\"\"Check if a user msg is cached.\"\"\"\n return any(entry[\"user\"] == user_message for entry in self.cache)\n\n def get_cached_response(self, user_message: str) -> str | None:\n \"\"\"Return the assistant response to a user message if cached.\"\"\"\n for entry in self.cache:\n if entry[\"user\"] == user_message:\n return entry[\"assistant\"]\n return None\n\n def _save(self):\n with open(self.cache_file, 'w') as f:\n json.dump(self.cache, f, indent=2)\n"], ["/agenticSeek/llm_server/sources/generator.py", "\nimport threading\nimport logging\nfrom abc import abstractmethod\nfrom .cache import Cache\n\nclass GenerationState:\n def __init__(self):\n self.lock = threading.Lock()\n self.last_complete_sentence = \"\"\n self.current_buffer = \"\"\n self.is_generating = False\n \n def status(self) -> dict:\n return {\n \"sentence\": self.current_buffer,\n \"is_complete\": not self.is_generating,\n \"last_complete_sentence\": self.last_complete_sentence,\n \"is_generating\": self.is_generating,\n }\n\nclass GeneratorLLM():\n def __init__(self):\n self.model = None\n self.state = GenerationState()\n self.logger = logging.getLogger(__name__)\n handler = logging.StreamHandler()\n handler.setLevel(logging.INFO)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n handler.setFormatter(formatter)\n self.logger.addHandler(handler)\n self.logger.setLevel(logging.INFO)\n cache = Cache()\n \n def set_model(self, model: str) -> None:\n self.logger.info(f\"Model set to {model}\")\n self.model = model\n \n def start(self, history: list) -> bool:\n if self.model is None:\n raise Exception(\"Model not set\")\n with self.state.lock:\n if self.state.is_generating:\n return False\n self.state.is_generating = True\n self.logger.info(\"Starting generation\")\n threading.Thread(target=self.generate, args=(history,)).start()\n return True\n \n def get_status(self) -> dict:\n with self.state.lock:\n return self.state.status()\n\n @abstractmethod\n def generate(self, history: list) -> None:\n \"\"\"\n Generate text using the model.\n args:\n history: list of strings\n returns:\n None\n \"\"\"\n pass\n\nif __name__ == \"__main__\":\n generator = GeneratorLLM()\n generator.get_status()"], ["/agenticSeek/sources/tools/__init__.py", "from .PyInterpreter import PyInterpreter\nfrom .BashInterpreter import BashInterpreter\nfrom .fileFinder import FileFinder\n\n__all__ = [\"PyInterpreter\", \"BashInterpreter\", \"FileFinder\", \"webSearch\", \"FlightSearch\", \"GoInterpreter\", \"CInterpreter\", \"GoInterpreter\"]\n"], ["/agenticSeek/sources/logger.py", "import os, sys\nfrom typing import List, Tuple, Type, Dict\nimport datetime\nimport logging\n\nclass Logger:\n def __init__(self, log_filename):\n self.folder = '.logs'\n self.create_folder(self.folder)\n self.log_path = os.path.join(self.folder, log_filename)\n self.enabled = True\n self.logger = None\n self.last_log_msg = \"\"\n if self.enabled:\n self.create_logging(log_filename)\n\n def create_logging(self, log_filename):\n self.logger = logging.getLogger(log_filename)\n self.logger.setLevel(logging.DEBUG)\n self.logger.handlers.clear()\n self.logger.propagate = False\n file_handler = logging.FileHandler(self.log_path)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n file_handler.setFormatter(formatter)\n self.logger.addHandler(file_handler)\n\n \n def create_folder(self, path):\n \"\"\"Create log dir\"\"\"\n try:\n if not os.path.exists(path):\n os.makedirs(path, exist_ok=True) \n return True\n except Exception as e:\n self.enabled = False\n return False\n \n def log(self, message, level=logging.INFO):\n if self.last_log_msg == message:\n return\n if self.enabled:\n self.last_log_msg = message\n self.logger.log(level, message)\n\n def info(self, message):\n self.log(message)\n\n def error(self, message):\n self.log(message, level=logging.ERROR)\n\n def warning(self, message):\n self.log(message, level=logging.WARN)\n\nif __name__ == \"__main__\":\n lg = Logger(\"test.log\")\n lg.log(\"hello\")\n lg2 = Logger(\"toto.log\")\n lg2.log(\"yo\")\n \n\n "], ["/agenticSeek/sources/tools/safety.py", "import os\nimport sys\n\nunsafe_commands_unix = [\n \"rm\", # File/directory removal\n \"dd\", # Low-level disk writing\n \"mkfs\", # Filesystem formatting\n \"chmod\", # Permission changes\n \"chown\", # Ownership changes\n \"shutdown\", # System shutdown\n \"reboot\", # System reboot\n \"halt\", # System halt\n \"sysctl\", # Kernel parameter changes\n \"kill\", # Process termination\n \"pkill\", # Kill by process name\n \"killall\", # Kill all matching processes\n \"exec\", # Replace process with command\n \"tee\", # Write to files with privileges\n \"umount\", # Unmount filesystems\n \"passwd\", # Password changes\n \"useradd\", # Add users\n \"userdel\", # Delete users\n \"brew\", # Homebrew package manager\n \"groupadd\", # Add groups\n \"groupdel\", # Delete groups\n \"visudo\", # Edit sudoers file\n \"screen\", # Terminal session management\n \"fdisk\", # Disk partitioning\n \"parted\", # Disk partitioning\n \"chroot\", # Change root directory\n \"route\" # Routing table management\n \"--force\", # Force flag for many commands\n \"rebase\", # Rebase git repository\n \"git\" # Git commands\n]\n\nunsafe_commands_windows = [\n \"del\", # Deletes files\n \"erase\", # Alias for del, deletes files\n \"rd\", # Removes directories (rmdir alias)\n \"rmdir\", # Removes directories\n \"format\", # Formats a disk, erasing data\n \"diskpart\", # Manages disk partitions, can wipe drives\n \"chkdsk /f\", # Fixes filesystem, can alter data\n \"fsutil\", # File system utilities, can modify system files\n \"xcopy /y\", # Copies files, overwriting without prompt\n \"copy /y\", # Copies files, overwriting without prompt\n \"move\", # Moves files, can overwrite\n \"attrib\", # Changes file attributes, e.g., hiding or exposing files\n \"icacls\", # Changes file permissions (modern)\n \"takeown\", # Takes ownership of files\n \"reg delete\", # Deletes registry keys/values\n \"regedit /s\", # Silently imports registry changes\n \"shutdown\", # Shuts down or restarts the system\n \"schtasks\", # Schedules tasks, can run malicious commands\n \"taskkill\", # Kills processes\n \"wmic\", # Deletes processes via WMI\n \"bcdedit\", # Modifies boot configuration\n \"powercfg\", # Changes power settings, can disable protections\n \"assoc\", # Changes file associations\n \"ftype\", # Changes file type commands\n \"cipher /w\", # Wipes free space, erasing data\n \"esentutl\", # Database utilities, can corrupt system files\n \"subst\", # Substitutes drive paths, can confuse system\n \"mklink\", # Creates symbolic links, can redirect access\n \"bootcfg\"\n]\n\ndef is_any_unsafe(cmds):\n \"\"\"\n check if any bash command is unsafe.\n \"\"\"\n for cmd in cmds:\n if is_unsafe(cmd):\n return True\n return False\n\ndef is_unsafe(cmd):\n \"\"\"\n check if a bash command is unsafe.\n \"\"\"\n if sys.platform.startswith(\"win\"):\n if any(c in cmd for c in unsafe_commands_windows):\n return True\n else:\n if any(c in cmd for c in unsafe_commands_unix):\n return True\n return False\n\nif __name__ == \"__main__\":\n cmd = input(\"Enter a command: \")\n if is_unsafe(cmd):\n print(\"Unsafe command detected!\")\n else:\n print(\"Command is safe to execute.\")"], ["/agenticSeek/llm_server/sources/llamacpp_handler.py", "\nfrom .generator import GeneratorLLM\nfrom llama_cpp import Llama\nfrom .decorator import timer_decorator\n\nclass LlamacppLLM(GeneratorLLM):\n\n def __init__(self):\n \"\"\"\n Handle generation using llama.cpp\n \"\"\"\n super().__init__()\n self.llm = None\n \n @timer_decorator\n def generate(self, history):\n if self.llm is None:\n self.logger.info(f\"Loading {self.model}...\")\n self.llm = Llama.from_pretrained(\n repo_id=self.model,\n filename=\"*Q8_0.gguf\",\n n_ctx=4096,\n verbose=True\n )\n self.logger.info(f\"Using {self.model} for generation with Llama.cpp\")\n try:\n with self.state.lock:\n self.state.is_generating = True\n self.state.last_complete_sentence = \"\"\n self.state.current_buffer = \"\"\n output = self.llm.create_chat_completion(\n messages = history\n )\n with self.state.lock:\n self.state.current_buffer = output['choices'][0]['message']['content']\n except Exception as e:\n self.logger.error(f\"Error: {e}\")\n finally:\n with self.state.lock:\n self.state.is_generating = False"], ["/agenticSeek/llm_server/app.py", "#!/usr/bin python3\n\nimport argparse\nimport time\nfrom flask import Flask, jsonify, request\n\nfrom sources.llamacpp_handler import LlamacppLLM\nfrom sources.ollama_handler import OllamaLLM\n\nparser = argparse.ArgumentParser(description='AgenticSeek server script')\nparser.add_argument('--provider', type=str, help='LLM backend library to use. set to [ollama], [vllm] or [llamacpp]', required=True)\nparser.add_argument('--port', type=int, help='port to use', required=True)\nargs = parser.parse_args()\n\napp = Flask(__name__)\n\nassert args.provider in [\"ollama\", \"llamacpp\"], f\"Provider {args.provider} does not exists. see --help for more information\"\n\nhandler_map = {\n \"ollama\": OllamaLLM(),\n \"llamacpp\": LlamacppLLM(),\n}\n\ngenerator = handler_map[args.provider]\n\n@app.route('/generate', methods=['POST'])\ndef start_generation():\n if generator is None:\n return jsonify({\"error\": \"Generator not initialized\"}), 401\n data = request.get_json()\n history = data.get('messages', [])\n if generator.start(history):\n return jsonify({\"message\": \"Generation started\"}), 202\n return jsonify({\"error\": \"Generation already in progress\"}), 402\n\n@app.route('/setup', methods=['POST'])\ndef setup():\n data = request.get_json()\n model = data.get('model', None)\n if model is None:\n return jsonify({\"error\": \"Model not provided\"}), 403\n generator.set_model(model)\n return jsonify({\"message\": \"Model set\"}), 200\n\n@app.route('/get_updated_sentence')\ndef get_updated_sentence():\n if not generator:\n return jsonify({\"error\": \"Generator not initialized\"}), 405\n print(generator.get_status())\n return generator.get_status()\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', threaded=True, debug=True, port=args.port)"], ["/agenticSeek/sources/agents/__init__.py", "\nfrom .agent import Agent\nfrom .code_agent import CoderAgent\nfrom .casual_agent import CasualAgent\nfrom .file_agent import FileAgent\nfrom .planner_agent import PlannerAgent\nfrom .browser_agent import BrowserAgent\nfrom .mcp_agent import McpAgent\n\n__all__ = [\"Agent\", \"CoderAgent\", \"CasualAgent\", \"FileAgent\", \"PlannerAgent\", \"BrowserAgent\", \"McpAgent\"]\n"], ["/agenticSeek/llm_server/sources/decorator.py", "\ndef timer_decorator(func):\n \"\"\"\n Decorator to measure the execution time of a function.\n Usage:\n @timer_decorator\n def my_function():\n # code to execute\n \"\"\"\n from time import time\n def wrapper(*args, **kwargs):\n start_time = time()\n result = func(*args, **kwargs)\n end_time = time()\n print(f\"\\n{func.__name__} took {end_time - start_time:.2f} seconds to execute\\n\")\n return result\n return wrapper"]], "task_instance_info": {"created_time": "2025-08-20 15:04:39", "created_task_model": "DeepSeek-R1", "class_skeleton": "class FileAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n pass", "code_description": "This code segment functions to: Implement an autonomous service component that manages file system operations through specialized utilities, maintains contextual memory for task execution, and orchestrates iterative command generation/validation cycles with external language model integration."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```python\n[TASK_BEGIN]\nclass FileAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n super().__init__(name, prompt_path, provider, verbose)\n self.file_finder = FileFinder()\n self.bash_interpreter = BashInterpreter()\n self.add_tool(self.file_finder)\n self.add_tool(self.bash_interpreter)\n self.memory = Memory()\n[TASK_END]\n```", "inference_time": "2025-08-20 15-05-07"}, "editdistance_info": {"edit_distance": 21.6216, "calculate_time": "2025-08-20 15:05:07", "true_code_clean": "class FileAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n super().__init__(name, prompt_path, provider, verbose, None)\n self.tools = {\n \"file_finder\": FileFinder(),\n \"bash\": BashInterpreter()\n }\n self.work_dir = self.tools[\"file_finder\"].get_work_dir()\n self.role = \"files\"\n self.type = \"file_agent\"\n self.memory = Memory(self.load_prompt(prompt_path),\n recover_last_session=False, \n memory_compression=False,\n model_provider=provider.get_model_name())\n async def process(self, prompt, speech_module) -> str:\n exec_success = False\n prompt += f\"\\nYou must work in directory: {self.work_dir}\"\n self.memory.push('user', prompt)\n while exec_success is False and not self.stop:\n await self.wait_message(speech_module)\n animate_thinking(\"Thinking...\", color=\"status\")\n answer, reasoning = await self.llm_request()\n self.last_reasoning = reasoning\n exec_success, _ = self.execute_modules(answer)\n answer = self.remove_blocks(answer)\n self.last_answer = answer\n self.status_message = \"Ready\"\n return answer, reasoning", "predict_code_clean": "class FileAgent(Agent):\n def __init__(self, name, prompt_path, provider, verbose=False):\n super().__init__(name, prompt_path, provider, verbose)\n self.file_finder = FileFinder()\n self.bash_interpreter = BashInterpreter()\n self.add_tool(self.file_finder)\n self.add_tool(self.bash_interpreter)\n self.memory = Memory()"}}