final-agent-course / agent.py
jjvelezo's picture
Update agent.py
61e90fc verified
raw
history blame
1.6 kB
from smolagents import CodeAgent, HfApiModel, DuckDuckGoSearchTool, WikipediaSearchTool
import datetime
class SmartDuckDuckGoAgent:
def __init__(self):
# Definir los tools de búsqueda
self.wikipedia_tool = WikipediaSearchTool()
self.duckduckgo_tool = DuckDuckGoSearchTool()
# Modelo
self.model = HfApiModel()
# Crear el agente con los tools y el modelo
self.agent = CodeAgent(
tools=[self.wikipedia_tool, self.duckduckgo_tool],
model=self.model,
additional_authorized_imports=['datetime']
)
def __call__(self, question: str) -> str:
# Intentar buscar en Wikipedia primero
try:
wiki_response = self.wikipedia_tool.search(question) # Usa 'search' en lugar de 'run'
if wiki_response:
return wiki_response
except Exception as e:
print(f"Error buscando en Wikipedia: {e}")
# Si Wikipedia no tiene resultados, intentar con DuckDuckGo
try:
duck_response = self.duckduckgo_tool.run(question)
if duck_response:
return duck_response
except Exception as e:
print(f"Error buscando en DuckDuckGo: {e}")
# Si ambos fallan, usar el modelo para generar una respuesta
fallback_prompt = f"""I couldn't find a direct answer to the following question:
{question}
Based on your general knowledge, provide a reasonable and well-written answer."""
return self.model.run(fallback_prompt)