Nancy1906 commited on
Commit
1cfd1a2
·
verified ·
1 Parent(s): ed31b4e

Update my_tools.py

Browse files
Files changed (1) hide show
  1. my_tools.py +28 -33
my_tools.py CHANGED
@@ -6,17 +6,15 @@ import time
6
  import asyncio
7
  import subprocess
8
  import pandas as pd
9
- from io import StringIO
10
  from duckduckgo_search import DDGS
11
  import wikipedia
 
 
 
12
  from llama_index.core.llms import ChatMessage, LLMMetadata, LLM, CompletionResponse
13
  from llama_index.core.tools import FunctionTool
14
  from llama_index.core.agent import ReActAgent
15
- from llama_index.indices.object_index import ObjectIndex
16
- from llama_index.indices.vector_store import VectorStoreIndex
17
  from llama_index.core.callbacks.llama_debug import LlamaDebugHandler
18
- from pydantic import Field
19
- import google.generativeai as genai
20
 
21
  # -------------------------------------------------------------------
22
  # 1) GeminiLLM personalizado
@@ -128,8 +126,8 @@ def buscar_web(query: str, max_attempts: int = 2) -> str:
128
  return "\n".join(f"Título: {r['title']}\nCuerpo: {r['body']}" for r in results)
129
  return "No se encontraron resultados."
130
  except Exception as e:
131
- if i < max_attempts-1:
132
- time.sleep(5*(i+1))
133
  else:
134
  return f"Error buscar_web tras {max_attempts} intentos: {e}"
135
 
@@ -140,7 +138,7 @@ def analyze_table(table_md: str, question: str) -> str:
140
  try:
141
  lines = [l.strip() for l in table_md.strip().splitlines() if l.strip()]
142
  content = [l for l in lines if not set(l) <= set("|- ")]
143
- rows = [ [c.strip() for c in r.split("|")[1:-1]] for r in content ]
144
  df = pd.DataFrame(rows[1:], columns=rows[0])
145
  if "no conmut" in question.lower():
146
  S = df.columns.tolist()
@@ -150,7 +148,7 @@ def analyze_table(table_md: str, question: str) -> str:
150
  a = df.loc[df[rows[0][0]]==x, y].values[0]
151
  b = df.loc[df[rows[0][0]]==y, x].values[0]
152
  if a != b:
153
- counter.update([x,y])
154
  return ", ".join(sorted(counter)) or "No hay contraejemplos"
155
  return df.to_csv(index=False)
156
  except Exception as e:
@@ -158,8 +156,10 @@ def analyze_table(table_md: str, question: str) -> str:
158
 
159
  def execute_code(code: str) -> str:
160
  try:
161
- res = subprocess.run(["python","- << 'EOF'\n" + code + "\nEOF"], shell=True,
162
- capture_output=True, text=True, timeout=5)
 
 
163
  if res.stderr:
164
  return f"Error código: {res.stderr.strip()}"
165
  return res.stdout.strip() or "(sin salida)"
@@ -169,42 +169,39 @@ def execute_code(code: str) -> str:
169
  def no_tool_solution(query: str) -> str:
170
  return "Procedo con conocimiento interno."
171
 
172
- # -------------------------------------------------------------------
173
- # 3) FunctionTools
174
- # -------------------------------------------------------------------
175
- search_tool = FunctionTool.from_defaults(fn=buscar_web, name="web_search", description="Búsqueda DDG (3 resultados).")
176
- reverse_tool = FunctionTool.from_defaults(fn=reverse_text, name="reverse_text", description="Invierte texto.")
177
- table_tool = FunctionTool.from_defaults(fn=analyze_table, name="analyze_table", description="Parses Markdown tables y responde conmutatividad.")
178
- code_tool = FunctionTool.from_defaults(fn=execute_code, name="execute_code", description="Ejecuta Python para cálculos.")
179
- fallback_tool = FunctionTool.from_defaults(fn=no_tool_solution, name="no_tool_solution", description="Fallback: conocimiento interno.")
180
 
181
  # -------------------------------------------------------------------
182
- # 4) ObjectIndex + Retriever
183
  # -------------------------------------------------------------------
184
- all_tools = [search_tool, reverse_tool, table_tool, code_tool, fallback_tool]
185
- obj_index = ObjectIndex.from_objects(all_tools, index_cls=VectorStoreIndex)
186
- tool_retriever = obj_index.as_retriever(similarity_top_k=3)
 
 
 
 
187
 
188
  # -------------------------------------------------------------------
189
- # 5) Prompt de sistema
190
  # -------------------------------------------------------------------
191
  system_prompt = (
192
  "Eres Alfred, un agente ReAct paso a paso.\n"
193
  "1) Analiza la pregunta.\n"
194
- "2) Decide la herramienta adecuada.\n"
195
- "3) Usa web_search, reverse_text, analyze_table, execute_code o no_tool_solution.\n"
196
- "4) Si no puedes procesar audio/video, indícalo.\n"
197
- "5) Responde claramente.\n"
 
198
  "Herramientas: {tool_descriptions}"
199
  )
200
 
201
  # -------------------------------------------------------------------
202
- # 6) Inicializar agente
203
  # -------------------------------------------------------------------
204
  llm = GeminiLLM(model_name="models/gemini-1.5-flash-latest", temperature=0.0)
205
 
206
  alfred_agent = ReActAgent.from_tools(
207
- tool_retriever=tool_retriever,
208
  llm=llm,
209
  system_prompt=system_prompt,
210
  verbose=True,
@@ -212,7 +209,7 @@ alfred_agent = ReActAgent.from_tools(
212
  )
213
 
214
  # -------------------------------------------------------------------
215
- # 7) Función pública
216
  # -------------------------------------------------------------------
217
  def basic_agent_response(question: str) -> str:
218
  try:
@@ -220,5 +217,3 @@ def basic_agent_response(question: str) -> str:
220
  return resp.response or "No se generó respuesta."
221
  except Exception as e:
222
  return f"Error crítico del agente: {e}"
223
-
224
-
 
6
  import asyncio
7
  import subprocess
8
  import pandas as pd
 
9
  from duckduckgo_search import DDGS
10
  import wikipedia
11
+ from pydantic import Field
12
+ import google.generativeai as genai
13
+
14
  from llama_index.core.llms import ChatMessage, LLMMetadata, LLM, CompletionResponse
15
  from llama_index.core.tools import FunctionTool
16
  from llama_index.core.agent import ReActAgent
 
 
17
  from llama_index.core.callbacks.llama_debug import LlamaDebugHandler
 
 
18
 
19
  # -------------------------------------------------------------------
20
  # 1) GeminiLLM personalizado
 
126
  return "\n".join(f"Título: {r['title']}\nCuerpo: {r['body']}" for r in results)
127
  return "No se encontraron resultados."
128
  except Exception as e:
129
+ if i < max_attempts - 1:
130
+ time.sleep(5 * (i + 1))
131
  else:
132
  return f"Error buscar_web tras {max_attempts} intentos: {e}"
133
 
 
138
  try:
139
  lines = [l.strip() for l in table_md.strip().splitlines() if l.strip()]
140
  content = [l for l in lines if not set(l) <= set("|- ")]
141
+ rows = [[c.strip() for c in r.split("|")[1:-1]] for r in content]
142
  df = pd.DataFrame(rows[1:], columns=rows[0])
143
  if "no conmut" in question.lower():
144
  S = df.columns.tolist()
 
148
  a = df.loc[df[rows[0][0]]==x, y].values[0]
149
  b = df.loc[df[rows[0][0]]==y, x].values[0]
150
  if a != b:
151
+ counter.update([x, y])
152
  return ", ".join(sorted(counter)) or "No hay contraejemplos"
153
  return df.to_csv(index=False)
154
  except Exception as e:
 
156
 
157
  def execute_code(code: str) -> str:
158
  try:
159
+ res = subprocess.run(
160
+ ["python", "-c", code],
161
+ capture_output=True, text=True, timeout=5
162
+ )
163
  if res.stderr:
164
  return f"Error código: {res.stderr.strip()}"
165
  return res.stdout.strip() or "(sin salida)"
 
169
  def no_tool_solution(query: str) -> str:
170
  return "Procedo con conocimiento interno."
171
 
 
 
 
 
 
 
 
 
172
 
173
  # -------------------------------------------------------------------
174
+ # 3) Encapsular como FunctionTool
175
  # -------------------------------------------------------------------
176
+ search_tool = FunctionTool.from_defaults(fn=buscar_web, name="web_search", description="Búsqueda DDG (3 resultados).")
177
+ reverse_tool = FunctionTool.from_defaults(fn=reverse_text, name="reverse_text", description="Invierte texto.")
178
+ table_tool = FunctionTool.from_defaults(fn=analyze_table, name="analyze_table", description="Parses Markdown tables y responde conmutatividad.")
179
+ code_tool = FunctionTool.from_defaults(fn=execute_code, name="execute_code", description="Ejecuta Python para cálculos.")
180
+ fallback_tool = FunctionTool.from_defaults(fn=no_tool_solution,name="no_tool_solution", description="Fallback: conocimiento interno.")
181
+
182
+ all_tools = [search_tool, reverse_tool, table_tool, code_tool, fallback_tool]
183
 
184
  # -------------------------------------------------------------------
185
+ # 4) Prompt de sistema
186
  # -------------------------------------------------------------------
187
  system_prompt = (
188
  "Eres Alfred, un agente ReAct paso a paso.\n"
189
  "1) Analiza la pregunta.\n"
190
+ "2) Usa la herramienta adecuada.\n"
191
+ "3) Si es posible, responde con web_search, reverse_text, analyze_table o execute_code.\n"
192
+ "4) Si nada aplica, usa no_tool_solution.\n"
193
+ "5) Si la pregunta requiere audio/video, informa que no puedes procesarlos.\n"
194
+ "6) Responde claro al usuario.\n"
195
  "Herramientas: {tool_descriptions}"
196
  )
197
 
198
  # -------------------------------------------------------------------
199
+ # 5) Inicializar agente con GeminiLLM
200
  # -------------------------------------------------------------------
201
  llm = GeminiLLM(model_name="models/gemini-1.5-flash-latest", temperature=0.0)
202
 
203
  alfred_agent = ReActAgent.from_tools(
204
+ tools=all_tools,
205
  llm=llm,
206
  system_prompt=system_prompt,
207
  verbose=True,
 
209
  )
210
 
211
  # -------------------------------------------------------------------
212
+ # 6) Función pública
213
  # -------------------------------------------------------------------
214
  def basic_agent_response(question: str) -> str:
215
  try:
 
217
  return resp.response or "No se generó respuesta."
218
  except Exception as e:
219
  return f"Error crítico del agente: {e}"