-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.py
More file actions
95 lines (83 loc) · 2.92 KB
/
agent.py
File metadata and controls
95 lines (83 loc) · 2.92 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
import ollama
from tools import calculate, get_weather
# --- Tool Registry ---
# Maps tool name (string) -> actual python function
TOOL_REGISTRY = {
"calculate": calculate,
"get_weather": get_weather,
}
# --- Tool Schema ---
# This is what the LLM sees
TOOL_SCHEMAS = [
{
"type": "function",
"function": {
"name": "calculate",
"description": "Evaluate a mathematical expression. Use this for any arithmetic.",
"parameters": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "A valid math expression e.g. '2847 * 193' or 'sqrt(144)'",
},
},
"required": ["expression"],
},
},
},
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "Name of the city e.g. 'London'",
}
},
"required": ["city"],
}
},
}
]
def run_agent(user_message: str) -> str:
print(f"\n 👤 User: {user_message}")
# Conversation history - this is the agent's short term memory
messages = [{"role": "user", "content": user_message}]
# --- ReAct Loop ---
while True:
# Step 1: Send message + tool schema to LLM
response = ollama.chat(
model="qwen2.5:7b",
messages=messages,
tools=TOOL_SCHEMAS
)
msg = response.message
# Step 2: Did the LLM want to call a tool?
if msg.tool_calls:
# Append LLM's intent to history
messages.append({"role": "assistant", "content": msg.content or "", "tool_calls": msg.tool_calls})
# Step 3: Execute each tool call OUR side
for tool_call in msg.tool_calls:
name = tool_call.function.name
args = tool_call.function.arguments
print(f"\n 🔧 Tool called: {name}({args})")
# Lookup actual python function and run it
if name in TOOL_REGISTRY:
result = TOOL_REGISTRY[name](**args)
else:
result = f"Error: tool '{name}' not found."
print(f"📤 Tool result: {result}")
# Step 4: Feed the result back to the LLM as a new message
messages.append({
"role": "tool",
"content": str(result),
})
else:
# LLM gave a final answer; no more tool calls
print(f"\n🤖 Agent: {msg.content}")
break