jjvelezo commited on
Commit
427cae4
·
verified ·
1 Parent(s): 61e90fc

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +50 -35
agent.py CHANGED
@@ -1,42 +1,57 @@
1
- from smolagents import CodeAgent, HfApiModel, DuckDuckGoSearchTool, WikipediaSearchTool
2
- import datetime
 
 
 
 
 
3
 
4
- class SmartDuckDuckGoAgent:
5
- def __init__(self):
6
- # Definir los tools de búsqueda
7
- self.wikipedia_tool = WikipediaSearchTool()
8
- self.duckduckgo_tool = DuckDuckGoSearchTool()
9
 
10
- # Modelo
11
- self.model = HfApiModel()
12
-
13
- # Crear el agente con los tools y el modelo
14
- self.agent = CodeAgent(
15
- tools=[self.wikipedia_tool, self.duckduckgo_tool],
16
- model=self.model,
17
- additional_authorized_imports=['datetime']
 
 
 
 
 
 
 
 
 
18
  )
19
 
20
- def __call__(self, question: str) -> str:
21
- # Intentar buscar en Wikipedia primero
22
- try:
23
- wiki_response = self.wikipedia_tool.search(question) # Usa 'search' en lugar de 'run'
24
- if wiki_response:
25
- return wiki_response
26
- except Exception as e:
27
- print(f"Error buscando en Wikipedia: {e}")
28
-
29
- # Si Wikipedia no tiene resultados, intentar con DuckDuckGo
30
  try:
31
- duck_response = self.duckduckgo_tool.run(question)
32
- if duck_response:
33
- return duck_response
34
  except Exception as e:
35
- print(f"Error buscando en DuckDuckGo: {e}")
36
 
37
- # Si ambos fallan, usar el modelo para generar una respuesta
38
- fallback_prompt = f"""I couldn't find a direct answer to the following question:
39
- {question}
40
-
41
- Based on your general knowledge, provide a reasonable and well-written answer."""
42
- return self.model.run(fallback_prompt)
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ from langchain.memory import ConversationBufferMemory
3
+ from langchain.agents import AgentExecutor, Tool
4
+ from langchain.chat_models import ChatGoogleGenerativeAI
5
+ import genai
6
+ from gemini import GeminiAgent
7
+ from smolagent_tools import WikipediaSearchTool, WebSearchTool, SmolagentToolWrapper
8
 
9
+ # Función para configuración de llm
10
+ def setup_llm(api_key: str, model_name: str = "gemini-2.0-flash"):
11
+ """Configuración del modelo de lenguaje con Gemini."""
12
+ genai.configure(api_key=api_key)
13
+ return ChatGoogleGenerativeAI(model_name=model_name)
14
 
15
+ # Herramientas adicionales
16
+ class EnhancedAgent:
17
+ def __init__(self, api_key: str, model_name: str = "gemini-2.0-flash"):
18
+ self.api_key = api_key
19
+ self.model_name = model_name
20
+ self.llm = setup_llm(api_key, model_name)
21
+ self.memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
22
+
23
+ self.tools = [
24
+ SmolagentToolWrapper(WikipediaSearchTool()),
25
+ Tool(name="web_search", func=self._web_search, description="Realizar búsqueda web avanzada")
26
+ ]
27
+
28
+ self.agent = GeminiAgent(
29
+ tools=self.tools,
30
+ llm=self.llm,
31
+ memory=self.memory,
32
  )
33
 
34
+ def _web_search(self, query: str, domain: Optional[str] = None) -> str:
35
+ """Realiza una búsqueda en la web usando DuckDuckGo con limitación de tasa y reintentos."""
 
 
 
 
 
 
 
 
36
  try:
37
+ search_tool = WebSearchTool()
38
+ results = search_tool.search(query, domain)
39
+ return results
40
  except Exception as e:
41
+ return f"Error al realizar la búsqueda: {str(e)}"
42
 
43
+ def run(self, query: str) -> str:
44
+ """Procesa las consultas del usuario con reintentos y manejo de errores."""
45
+ max_retries = 3
46
+ base_sleep = 1
47
+ for attempt in range(max_retries):
48
+ try:
49
+ response = self.agent.run(query)
50
+ return response
51
+ except Exception as e:
52
+ sleep_time = base_sleep * (attempt + 1)
53
+ if attempt < max_retries - 1:
54
+ print(f"Intento {attempt + 1} fallido. Reintentando en {sleep_time} segundos...")
55
+ time.sleep(sleep_time)
56
+ continue
57
+ return f"Error procesando la consulta: {str(e)}"