fix: langcode.py usa result['response'] invece di messages[-1]

Il bug era che langcode.py prendeva l'ultimo messaggio dalla cronologia invece del campo 'response' che OllamaToolAgent restituisce.
This commit is contained in:
opencode committed 2026-03-23 18:35:45 +01:00
1 parent d16102587d
commit cffac60211
3 files changed
+156 -2

No files matched your search

+110
View File
@@ -0,0 +1,110 @@
# Stato Debug LangCode Agent - 23 Marzo 2026
## Situazione Attuale
L'agente **funziona** a livello di esecuzione tool, ma **non mostra il risultato** all'utente.
## Cosa Funziona
1. **Intent Detection**: Rileva correttamente "che SO sto usando" come richiesta di system_info
2. **Tool Execution**: Il tool `system_info` viene eseguito e restituisce il risultato corretto
3. **Response Generation**: `response_text` contiene i dati corretti
### Debug Output Osservato (CORRETTO):
```
OLLAMA_AGENT: user_content='che so sto usando'
OLLAMA_AGENT: detected_tool=ToolCall(id='intent', name='system_info', arguments={})
_execute_tool: name=system_info, args={}
_execute_tool: got result type=<class 'str'>, value=OS: Linux 6.17.4-2-pve...
OLLAMA_AGENT: result type=<class 'dict'>, value={'result': 'OS: Linux 6.17.4-2-pve...'}
OLLAMA_AGENT: response_text=OS: Linux 6.17.4-2-pve
Python: 3.12.3
Current dir: /root/tryout/langcode_agent
User: root
```
## Problema
Nonostante `response_text` sia corretto, l'output mostra:
```
🤖 LangCode: che so sto usando
```
Invece di:
```
🤖 LangCode: OS: Linux 6.17.4-2-pve
Python: 3.12.3...
```
## Ipotesi
1. **L'agente viene chiamato due volte**: Prima con SimpleAgent (fallback) e poi con OllamaToolAgent
2. **L'eccezione viene mangiata**: Il blocco try/except in main.py potrebbe nascondere l'errore
3. **Bufferizzazione output**: I print() non vengono visualizzati prima dell'eco
## Codicemain.py (main loop)
```python
while True:
user_input = input("\n👤 You: ").strip()
if not user_input:
continue
# Check if it's a command (starts with /)
if process_command(user_input):
continue
# Otherwise, treat it as a chat message
try:
print("MAIN: before invoke", flush=True)
result = agent.invoke({"messages": [HumanMessage(content=user_input)]})
print(f"MAIN: after invoke, result type={type(result)}", flush=True)
# Extract the AI's response
if result and "response" in result:
response_text = result["response"]
else:
ai_message = result["messages"][-1]
response_text = ai_message.content if hasattr(ai_message, 'content') else str(ai_message)
print(f"\n🤖 LangCode: {response_text}")
except Exception as e:
print(f"\n❌ Errore: {str(e)}")
```
## Osservazioni Critiche
1. `MAIN: before invoke` NON viene mai visualizzato
2. Questo significa che `agent.invoke()` potrebbe:
- Essere chiamato ma stampare prima di return
- Sollevare un'eccezione che viene catturata
- Restituire qualcosa di inaspettato
3. L'eco `🤖 LangCode: che so sto usando` è identico all'input `👤 You: che so sto usando`
- Questo suggerisce che l'agent sta restituendo l'input invece del risultato
## Prossimi Passi Suggeriti
1. **Verificare quale agente viene creato**: Aggiungere print in `create_langcode_agent()`
2. **Verificare il tipo di agent restituito**: Stampare `type(agent)` dopo la creazione
3. **Forzare output non bufferizzato**: Usare `sys.stdout.flush()` dopo ogni print
4. **Verificare se l'eccezione viene mangiata**: Stampare SEMPRE l'eccezione, anche se vuota
## File Principali
- `main.py` - Entry point, main loop
- `ollama_agent.py` - OllamaToolAgent con intent detection
- `langcode.py` - CLI entry point
## Comandi di Test
```bash
# Sul server
cd ~/tryout/langcode_agent
source venv/bin/activate
python langcode.py
# Testare: "che SO sto usando"
# Osservare: Il debug output dell'agente MA NON l'output MAIN
```
+9 -2
View File
@@ -70,8 +70,15 @@ def cmd_chat(args):
# Otherwise, treat it as a chat message
try:
result = agent.invoke({"messages": [HumanMessage(content=user_input)]})
ai_message = result["messages"][-1]
print(f"\n🤖 LangCode: {ai_message.content}")
# Extract response - support both simple agent (messages[-1]) and tool agent (response)
if "response" in result:
response_text = result["response"]
else:
ai_message = result["messages"][-1]
response_text = ai_message.content if hasattr(ai_message, 'content') else str(ai_message)
print(f"\n🤖 LangCode: {response_text}")
except Exception as e:
print(f"\n❌ Errore: {str(e)}")
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""
Test script per debuggare langcode agent
"""
import sys
sys.path.insert(0, '/home/codex/langChainAgent/langcode_agent')
print("1. Importing modules...", flush=True)
from langchain_core.messages import HumanMessage
print("2. Importing main...", flush=True)
from main import create_langcode_agent
print("3. Creating agent...", flush=True)
agent = create_langcode_agent()
print(f"4. Agent type: {type(agent)}", flush=True)
print("5. Invoking with test message...", flush=True)
try:
result = agent.invoke({"messages": [HumanMessage(content="che SO sto usando")]})
print(f"6. Result type: {type(result)}", flush=True)
print(f"7. Result keys: {result.keys() if hasattr(result, 'keys') else 'NO KEYS'}", flush=True)
if "response" in result:
print(f"8. Response: {result['response'][:200]}...", flush=True)
else:
print("8. No 'response' key in result!", flush=True)
if result.get("messages"):
last_msg = result["messages"][-1]
print(f" Last message: {last_msg.content if hasattr(last_msg, 'content') else str(last_msg)[:100]}", flush=True)
except Exception as e:
print(f"ERROR: {type(e).__name__}: {e}", flush=True)
import traceback
traceback.print_exc()