Final_Assignment_Template / src /custom_tool_node.py
porla
Implement CustomAgent and CustomToolNode; refactor tools and agent initialization
ec946c6
class CustomToolNode:
"""Tool node personalizzato che può accedere allo stato completo"""
def __init__(self, tools_dict):
self.tools_dict = tools_dict
def __call__(self, state):
messages = state["messages"]
last_message = messages[-1]
# Estrai i tool calls dall'ultimo messaggio
if hasattr(last_message, 'tool_calls') and last_message.tool_calls:
results = []
for tool_call in last_message.tool_calls:
tool_name = tool_call["name"]
tool_args = tool_call["args"]
# Aggiungi task_id agli argomenti del tool
tool_args_with_state = {
**tool_args,
"task_id": state["task_id"],
"state": state # Opzionale: passa tutto lo stato
}
if tool_name in self.tools_dict:
try:
result = self.tools_dict[tool_name].invoke(tool_args_with_state)
results.append({
"type": "tool",
"name": tool_name,
"tool_call_id": tool_call["id"],
"content": str(result)
})
except Exception as e:
results.append({
"type": "tool",
"name": tool_name,
"tool_call_id": tool_call["id"],
"content": f"Error: {str(e)}"
})
return {"messages": results}
return {"messages": []}