1import json, math
2
3# 两个工具函数(前置知识,内联以保证本例可独立运行)
4def calculator(expression):
5 allowed = set("0123456789+-*/.() ")
6 if not all(c in allowed for c in expression):
7 return json.dumps({"error": "非法字符"})
8 try:
9 return json.dumps({"expression": expression, "result": eval(expression, {"__builtins__": {}}, {"math": math})})
10 except Exception as e:
11 return json.dumps({"error": str(e)})
12
13def get_weather(city):
14 fake = {"北京": {"temp": 28, "weather": "晴"}, "深圳": {"temp": 33, "weather": "雷阵雨"}}
15 data = fake.get(city, {"temp": 25, "weather": "未知"})
16 return json.dumps({"city": city, **data}, ensure_ascii=False)
17
18class ToolAgent:
19 """工具调用 Agent(模拟版)"""
20 def __init__(self):
21 self.tools = {"calculator": calculator, "get_weather": get_weather}
22
23 def should_use_tool(self, user_input):
24 """模拟 AI 判断是否需要工具"""
25 if any(w in user_input for w in ["天气", "气温"]):
26 for city in ["北京", "上海", "深圳", "广州"]:
27 if city in user_input:
28 return "get_weather", {"city": city}
29 if any(c in user_input for c in "+-*/") and any(c.isdigit() for c in user_input):
30 expr = "".join(c for c in user_input if c.isdigit() or c in "+-*/.() ").strip()
31 if expr:
32 return "calculator", {"expression": expr}
33 return None, None
34
35 def run(self, user_input):
36 print(f"用户: {user_input}")
37 tool_name, tool_args = self.should_use_tool(user_input)
38 if tool_name:
39 print(f"[Agent] 调用: {tool_name}({tool_args})")
40 result = self.tools[tool_name](**tool_args)
41 print(f"[结果] {result}")
42 data = json.loads(result)
43 if tool_name == "get_weather":
44 reply = f"{data['city']}当前{data['weather']},{data['temp']}度。"
45 else:
46 reply = f"结果是 {data['result']}。"
47 else:
48 reply = f"[AI] 收到:{user_input}"
49 print(f"AI: {reply}\n")
50
51agent = ToolAgent()
52agent.run("深圳天气怎么样?")
53agent.run("帮我算 123 * 456")