File size: 7,092 Bytes
d03c5e0
f3f36bb
d03c5e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# 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