# core_agent.py from tools import ExcelToTextTool, SpeechToTextTool, download_file_from_url, analyze_csv_file, analyze_excel_file, wikipedia_page_fetch, reverse_text, save_and_read_file,extract_text_from_image, extract_wiki_list, final_answer import os from typing import Any import re from smolagents import ( CodeAgent, DuckDuckGoSearchTool, PythonInterpreterTool, OpenAIServerModel, ToolCallingAgent, WikipediaSearchTool ) from typing import Optional from dotenv import load_dotenv import logging load_dotenv() logger = logging.getLogger(__name__) _THINK_SYSTEM = """ You are a tool using agent that MUST follow a strict THINK → ACT → OBSERVE pattern. IMPORTANT: - At each step, you must do only ONE simple action. - An action can be: a search, a wiki fetch, analyzing a file, or running a SMALL code snippet. - DO NOT generate large full code. - DO NOT plan many steps in advance. - DO NOT use a tool if you are confident you can answer directly. - Always proceed ONE SMALL STEP at a time. After you finish the step, you must wait for the observation (`RESULT:`) before deciding the next move. Available Actions: SEARCH — DuckDuckGoSearchTool WIKIPEDIA — WikipediaSearchTool WIKI_FETCH — wikipedia_page_fetch REVERSE_TEXT — reverse_text ANALYZE_CSV — analyze_csv_file ANALYZE_EXCEL — analyze_excel_file DOWNLOAD_FILE — download_file_from_url EXCEL_TO_MD — ExcelToTextTool RUN_CODE_AGENT — smol-agents CodeAgent SPEECH_TO_TEXT — SpeechToTextTool FINAL_ANSWER — final_answer **EVERY** Action must be wrapped in a Python code block: ```python Action: the action_name Input: "your input here" STRICT RULES: - You must use the tools you have to get the information you need to answer dont try to predict answers. - You MUST NOT write any "Thoughts:", "Thought:", "Code:", or generate Python code blocks. - Do not generate `pass`, `def`, `import` or any code unless inside RUN_CODE_AGENT. - If you reach FINAL_ANSWER, submit it IMMEDIATELY and STOP. - When using tools, call them using the Action/Input format, not raw code. Remember: - THINK carefully. - ACT with ONE small step. - OBSERVE the result and only then continue. - Keep your code minimal and targeted. - After you output `Action: FINAL_ANSWER`, you must STOP and finish the task. Do not continue with any other actions or responses after FINAL_ANSWER. """ class GAIAAgent: def __init__(self): self.verbose = True self.model = self._load_model() tools = [ reverse_text, DuckDuckGoSearchTool(), WikipediaSearchTool(), analyze_csv_file, analyze_excel_file, wikipedia_page_fetch, ExcelToTextTool(), save_and_read_file, download_file_from_url, PythonInterpreterTool(), final_answer ] # ✅ Always instantiate Whisper tool separately try: whisper_tool = SpeechToTextTool() tools.append(whisper_tool) logger.info("Whisper loaded") except Exception as e: logger.warning("Whisper failed: %s", e) self.agent = CodeAgent( model=self.model, tools=tools, additional_authorized_imports=["pandas","numpy","csv","math","bs4","re","requests","json","xml.etree.ElementTree","os"] ) def _load_model(self): mistral_key = os.getenv("MISTRAL_API_KEY") openai_key = os.getenv("OPENAI_API_KEY") # Primary: Mistral API (OpenAI-style endpoint) if mistral_key: print("Using Mistral (mistral-medium) via OpenAIServerModel") return OpenAIServerModel( model_id="mistral-medium", api_key=mistral_key, api_base="https://api.mistral.ai/v1", temperature=0.2 ) # Fallback: OpenAI elif openai_key: print("☁️ Using OpenAI GPT-4o via OpenAIServerModel") return OpenAIServerModel( model_id="gpt-4o", api_key=openai_key, temperature=0.2 ) # No keys found raise ValueError("❌ No API key found. Set MISTRAL_API_KEY or OPENAI_API_KEY") def answer_question(self, question: str, task_file_path: Optional[str] = None) -> str: try: if self.verbose: print(f"Processing question: {question}") if task_file_path: print(f"With associated file: {task_file_path}") context = question if task_file_path: try: with open(task_file_path, "r", encoding="utf-8") as f: file_content = f.read() ext = os.path.splitext(task_file_path)[1].lower() context += f'\n\nThe task file (`{ext}`) content is:\n"""\n{file_content}\n"""' except Exception as file_e: context += f"\n\n(⚠️ Could not read file: {file_e})" # Compose the full prompt user_prompt = f"""this is the question you need to answer: {question} """ full_prompt_with_system = f"{_THINK_SYSTEM}\n\n{user_prompt}" # Run the agent answer = self.agent.run(full_prompt_with_system) answer = self._clean_answer(answer) if self.verbose: print(f"Generated answer: {answer}") return answer except Exception as e: error_msg = f"Error answering question: {e}" if self.verbose: print(error_msg) return error_msg def _clean_answer(self, answer: str) -> str: """ Clean up the answer to remove common prefixes and formatting that models often add but that can cause exact match failures. Args: answer: The raw answer from the model Returns: The cleaned answer as a string """ if not isinstance(answer, str): answer = str(answer) answer = answer.strip() # Remove common prefixes for prefix in [ "Answer:", "The answer is", "Final answer:", "To answer this question:" ]: if answer.lower().startswith(prefix.lower()): answer = answer[len(prefix):].strip() # Strip quotes if (answer.startswith('"') and answer.endswith('"')) or \ (answer.startswith("'") and answer.endswith("'")): answer = answer[1:-1].strip() return answer