Repository navigation
Expand file tree
/
Copy pathdebug_tools.py
More file actions
191 lines (164 loc) · 7.28 KB
/
Copy pathdebug_tools.py
File metadata and controls
191 lines (164 loc) · 7.28 KB
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
#!/usr/bin/env python3
"""
debug_tools.py — Diagnóstico completo del sistema de herramientas de AXIOM.
Ejecuta: python debug_tools.py
"""
import asyncio, json, sys, os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ".")
SEP = "─" * 60
def ok(msg): print(f" ✓ {msg}")
def fail(msg): print(f" ✗ {msg}")
def info(msg): print(f" {msg}")
# ══ 1. Internet access ════════════════════════════════════════════════════════
print(f"\n{SEP}")
print("1. ACCESO A INTERNET")
print(SEP)
import urllib.request
tests = [
("DuckDuckGo API", "https://api.duckduckgo.com/?q=python&format=json&no_html=1"),
("DuckDuckGo HTML", "https://html.duckduckgo.com/html/?q=python"),
("Google", "https://www.google.com"),
("GitHub", "https://github.com"),
]
for name, url in tests:
try:
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(req, timeout=5) as r:
size = len(r.read())
ok(f"{name} — {size} bytes")
except Exception as e:
fail(f"{name} — {type(e).__name__}: {e}")
# ══ 2. web_search tool directly ═══════════════════════════════════════════════
print(f"\n{SEP}")
print("2. TOOL web_search DIRECTO")
print(SEP)
try:
from core.tools import ALL_TOOLS
tool = ALL_TOOLS["web_search"]
result = tool.execute({"query": "Lewis Hamilton F1 2024", "max_results": 2})
if "Error" in result or "Sin resultados" in result:
fail(f"web_search falló: {result[:200]}")
else:
ok(f"web_search funcionó — {len(result)} chars")
info(result[:300])
except Exception as e:
fail(f"web_search excepción: {e}")
# ══ 3. web_fetch tool directly ════════════════════════════════════════════════
print(f"\n{SEP}")
print("3. TOOL web_fetch DIRECTO")
print(SEP)
try:
tool = ALL_TOOLS["web_fetch"]
result = tool.execute({"url": "https://www.formula1.com/en/results", "max_chars": 500})
if "Error" in result:
fail(f"web_fetch falló: {result[:200]}")
else:
ok(f"web_fetch funcionó — {len(result)} chars")
info(result[:200])
except Exception as e:
fail(f"web_fetch excepción: {e}")
# ══ 4. Ollama connection + tool calling capability ════════════════════════════
print(f"\n{SEP}")
print("4. OLLAMA — CONEXIÓN Y CAPACIDAD DE TOOLS")
print(SEP)
import httpx
async def test_ollama():
try:
import yaml
cfg = yaml.safe_load(open("config.yaml"))
model = cfg["model"]["name"]
url = cfg["model"]["base_url"]
info(f"Modelo: {model} @ {url}")
# Test 1: basic connection
async with httpx.AsyncClient(timeout=5) as c:
r = await c.get(f"{url}/api/tags")
models = [m["name"] for m in r.json().get("models", [])]
ok(f"Ollama corriendo — modelos: {models}")
# Test 2: does model support native tool calling?
tool_def = [{
"type": "function",
"function": {
"name": "web_search",
"description": "Buscar en internet",
"parameters": {
"type": "object",
"properties": {"query": {"type": "string", "description": "búsqueda"}},
"required": ["query"]
}
}
}]
async with httpx.AsyncClient(timeout=30) as c:
r = await c.post(f"{url}/api/chat", json={
"model": model,
"messages": [{"role": "user", "content": "Busca quién ganó el último GP de F1. Usa la herramienta web_search."}],
"stream": False,
"tools": tool_def,
"options": {"temperature": 0.1}
})
data = r.json()
msg = data.get("message", {})
native_calls = msg.get("tool_calls", [])
content = msg.get("content", "")
if native_calls:
ok(f"Native tool calling: SÍ — llamó a: {[tc.get('function',{}).get('name') for tc in native_calls]}")
else:
fail(f"Native tool calling: NO — el modelo no generó tool_calls")
info(f"Contenido generado: {content[:200]}")
# Check if it used text format
from core.tools import has_tool_calls, parse_tool_calls
if has_tool_calls(content):
calls = parse_tool_calls(content)
if calls:
ok(f"Text-based tool call detectado: {calls[0]['name']} args={calls[0]['args']}")
else:
fail("has_tool_calls=True pero parse_tool_calls devolvió vacío")
else:
fail("No generó tool call en ningún formato — el modelo ignoró las herramientas")
info("→ El modelo necesita mejor prompt o no soporta function calling")
except Exception as e:
fail(f"Error Ollama: {e}")
asyncio.run(test_ollama())
# ══ 5. Full agent tool loop simulation ═══════════════════════════════════════
print(f"\n{SEP}")
print("5. SIMULACIÓN DEL LOOP COMPLETO")
print(SEP)
async def test_agent_loop():
try:
from core.agent import Agent
agent = Agent()
info(f"Agent: {agent.name} | tools: {list(agent.tools.keys())[:4]}...")
# Fake message list as agent would build it
import yaml
cfg = yaml.safe_load(open("config.yaml"))
soul = agent.self_editor.read_soul()
# Build system prompt with tools
from core.tools import build_tools_prompt
sys_prompt = f"""Eres {agent.name}. SOUL: {soul[:200]}
{build_tools_prompt(agent.tools)}"""
messages = [
{"role": "system", "content": sys_prompt},
{"role": "user", "content": "¿Quién ganó el último Gran Premio de F1? Busca en internet."}
]
events = []
def on_tool(ev):
events.append(ev)
if ev["type"] == "tool_start":
ok(f"Tool ejecutada: {ev['name']} | args={ev['args']}")
elif ev["type"] == "tool_result":
ok(f"Tool resultado: {ev['result'][:100]}")
result = await agent._run_tool_loop(messages, on_tool_event=on_tool)
if events:
ok(f"Loop completó — {len(events)//2} tool(s) ejecutada(s)")
else:
fail("Loop completó SIN ejecutar ninguna herramienta")
info(f"Respuesta final: {result[:300]}")
except Exception as e:
import traceback
fail(f"Agent loop error: {e}")
traceback.print_exc()
asyncio.run(test_agent_loop())
# ══ Summary ═══════════════════════════════════════════════════════════════════
print(f"\n{SEP}")
print("RESUMEN — pega el output completo en el chat")
print(SEP)