Update agent.py
Browse files
agent.py
CHANGED
|
@@ -1,47 +1,110 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
from __future__ import annotations
|
| 5 |
-
import os, textwrap
|
| 6 |
-
from smolagents import CodeAgent, DuckDuckGoSearchTool
|
| 7 |
-
from tools import WikipediaTool, ArxivTool
|
| 8 |
-
import openai
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
#
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise.
|
| 20 |
-
If you are asked for a string, don't use articles, neither abbreviations, and write digits in plain text unless specified otherwise.
|
| 21 |
-
Return ONLY the final answer line.
|
| 22 |
-
""").strip()
|
| 23 |
-
|
| 24 |
-
# βββ Build CodeAgent βββββββββββββββββββββββββββββββ
|
| 25 |
-
MODEL_ID = os.getenv("GAIA_MODEL_ID", "gpt-4o") # override se hai βgpt-4.1β
|
| 26 |
-
|
| 27 |
-
core_agent = CodeAgent(
|
| 28 |
-
model=MODEL_ID,
|
| 29 |
-
tools=[
|
| 30 |
-
DuckDuckGoSearchTool(),
|
| 31 |
-
WikipediaTool(),
|
| 32 |
-
ArxivTool(),
|
| 33 |
-
],
|
| 34 |
-
max_steps=6,
|
| 35 |
-
temperature=0,
|
| 36 |
-
system_prompt=SYSTEM_PROMPT,
|
| 37 |
-
stream_outputs=False,
|
| 38 |
)
|
|
|
|
| 39 |
|
| 40 |
-
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
def __init__(self):
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
def __call__(self, question: str) -> str:
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import logging
|
| 3 |
+
from typing import List, Dict, Any, Optional
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
+
from smalagents.agent import Agent
|
| 6 |
+
from smalagents.llms import OpenAILLM
|
| 7 |
+
from smalagents.tools import Tool
|
| 8 |
+
from smalagents.tools.web_search import DuckDuckGoSearchTool
|
| 9 |
+
from smalagents.tools.wikipedia import WikipediaSearchTool
|
| 10 |
+
from smalagents.tools.arxiv import ArxivSearchTool
|
| 11 |
+
from smalagents.tools.code_interpreter import CodeInterpreterTool
|
| 12 |
|
| 13 |
+
# Configurazione del logging
|
| 14 |
+
logging.basicConfig(
|
| 15 |
+
level=logging.INFO,
|
| 16 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
)
|
| 18 |
+
logger = logging.getLogger("GaiaAgent")
|
| 19 |
|
| 20 |
+
class GaiaAgent:
|
| 21 |
+
"""
|
| 22 |
+
Agente AI per superare il test GAIA livello 1.
|
| 23 |
+
Utilizza smalagents con capacitΓ di ricerca Wikipedia, DuckDuckGo, arXiv e code execution.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
def __init__(self):
|
| 27 |
+
logger.info("Inizializzazione GaiaAgent")
|
| 28 |
+
|
| 29 |
+
# Verifica della chiave API
|
| 30 |
+
api_key = os.environ.get("OPENAI_API_KEY")
|
| 31 |
+
if not api_key:
|
| 32 |
+
logger.error("OPENAI_API_KEY non trovata nelle variabili d'ambiente")
|
| 33 |
+
raise ValueError("OPENAI_API_KEY non trovata. Configura il secret in Hugging Face.")
|
| 34 |
+
|
| 35 |
+
# Configurazione del modello LLM
|
| 36 |
+
self.llm = OpenAILLM(
|
| 37 |
+
model="gpt-4.1",
|
| 38 |
+
api_key=api_key
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
# Configurazione degli strumenti
|
| 42 |
+
self.tools: List[Tool] = [
|
| 43 |
+
WikipediaSearchTool(),
|
| 44 |
+
DuckDuckGoSearchTool(),
|
| 45 |
+
ArxivSearchTool(),
|
| 46 |
+
CodeInterpreterTool()
|
| 47 |
+
]
|
| 48 |
+
|
| 49 |
+
# Istruzioni specifiche per il formato delle risposte
|
| 50 |
+
system_prompt = """You are a helpful assistant tasked with answering questions using a set of tools.
|
| 51 |
+
Your final answer should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
|
| 52 |
+
If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise.
|
| 53 |
+
If you are asked for a string, don't use articles, neither abbreviations, and write digits in plain text unless specified otherwise.
|
| 54 |
+
Return ONLY the final answer line."""
|
| 55 |
+
|
| 56 |
+
# Creazione dell'agente
|
| 57 |
+
self.agent = Agent(
|
| 58 |
+
llm=self.llm,
|
| 59 |
+
tools=self.tools,
|
| 60 |
+
system_prompt=system_prompt,
|
| 61 |
+
verbose=True # Per logging essenziale
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
logger.info("GaiaAgent inizializzato con successo")
|
| 65 |
+
|
| 66 |
def __call__(self, question: str) -> str:
|
| 67 |
+
"""
|
| 68 |
+
Processa una domanda e restituisce la risposta.
|
| 69 |
+
|
| 70 |
+
Args:
|
| 71 |
+
question: La domanda da processare
|
| 72 |
+
|
| 73 |
+
Returns:
|
| 74 |
+
La risposta alla domanda
|
| 75 |
+
"""
|
| 76 |
+
logger.info(f"Elaborazione domanda: {question[:50]}...")
|
| 77 |
+
|
| 78 |
+
try:
|
| 79 |
+
# Esecuzione dell'agente sulla domanda
|
| 80 |
+
response = self.agent.run(question)
|
| 81 |
+
|
| 82 |
+
# Estrazione della risposta finale
|
| 83 |
+
answer = self._extract_final_answer(response)
|
| 84 |
+
|
| 85 |
+
logger.info(f"Risposta generata: {answer[:50]}...")
|
| 86 |
+
return answer
|
| 87 |
+
|
| 88 |
+
except Exception as e:
|
| 89 |
+
logger.error(f"Errore durante l'elaborazione della domanda: {str(e)}")
|
| 90 |
+
return f"Errore: {str(e)}"
|
| 91 |
+
|
| 92 |
+
def _extract_final_answer(self, response: Dict[str, Any]) -> str:
|
| 93 |
+
"""
|
| 94 |
+
Estrae la risposta finale dal risultato dell'agente.
|
| 95 |
+
|
| 96 |
+
Args:
|
| 97 |
+
response: Il risultato completo dell'agente
|
| 98 |
+
|
| 99 |
+
Returns:
|
| 100 |
+
La risposta finale estratta
|
| 101 |
+
"""
|
| 102 |
+
# Estrazione della risposta finale dal risultato dell'agente
|
| 103 |
+
if isinstance(response, dict) and "output" in response:
|
| 104 |
+
return response["output"].strip()
|
| 105 |
+
elif isinstance(response, str):
|
| 106 |
+
return response.strip()
|
| 107 |
+
else:
|
| 108 |
+
logger.warning(f"Formato di risposta inatteso: {type(response)}")
|
| 109 |
+
# Tentativo di conversione a stringa
|
| 110 |
+
return str(response).strip()
|