1import json, math, re
2from datetime import datetime
3
4def safe_calc(expr):
5 allowed = set("0123456789+-*/.()% ")
6 if not all(c in allowed for c in expr):
7 return json.dumps({"error": "非法字符"})
8 try:
9 r = eval(expr, {"__builtins__": {}}, {"math": math})
10 return json.dumps({"expression": expr, "result": r})
11 except Exception as e:
12 return json.dumps({"error": str(e)})
13
14def get_time():
15 now = datetime.now()
16 return json.dumps({"time": now.strftime("%H:%M:%S")})
17
18class TodoMgr:
19 def __init__(self):
20 self.todos = []
21 def add(self, task):
22 self.todos.append({"task": task, "done": False, "id": len(self.todos)+1})
23 return json.dumps({"status": "added", "task": task})
24 def list_all(self):
25 return json.dumps({"todos": self.todos}, ensure_ascii=False)
26 def complete(self, tid):
27 for t in self.todos:
28 if t["id"] == tid:
29 t["done"] = True
30 return json.dumps({"status": "done", "id": tid})
31 return json.dumps({"error": "未找到"})
32
33class AIAssistant:
34 def __init__(self):
35 self.todo = TodoMgr()
36 self.tools = {
37 "calculator": safe_calc,
38 "get_time": get_time,
39 "todo_add": self.todo.add,
40 "todo_list": self.todo.list_all,
41 "todo_complete": self.todo.complete,
42 }
43
44 def decide(self, text):
45 if any(w in text for w in ["几点", "时间"]):
46 return ("get_time", {})
47 if "添加待办" in text or "记一下" in text:
48 task = re.sub(r"^(添加待办|记一下)[::\s]*", "", text).strip()
49 if task: return ("todo_add", {"task": task})
50 if "待办列表" in text or "我的待办" in text:
51 return ("todo_list", {})
52 m = re.search(r"完成(?:待办)?\s*(\d+)", text)
53 if m: return ("todo_complete", {"tid": int(m.group(1))})
54 m2 = re.search(r"[\d.]+\s*[+\-*/%]+\s*[\d.]+", text)
55 if m2: return ("calculator", {"expr": m2.group()})
56 return (None, {})
57
58 def chat(self, text):
59 tool, args = self.decide(text)
60 if not tool:
61 return f"我可以帮你计算、查时间、管理待办。你说:{text}"
62 try:
63 result = self.tools[tool](**args)
64 data = json.loads(result)
65 if tool == "calculator":
66 return f"结果:{data.get('expression')} = {data.get('result', data.get('error'))}"
67 if tool == "get_time":
68 return f"现在是 {data['time']}"
69 if tool == "todo_add":
70 return f"已添加:{data['task']}"
71 if tool == "todo_list":
72 if not data["todos"]: return "待办是空的"
73 lines = [f" {t['id']}. [{'✓' if t['done'] else ' '}] {t['task']}" for t in data["todos"]]
74 return "待办列表:\n" + "\n".join(lines)
75 if tool == "todo_complete":
76 return f"已完成 #{data.get('id', '?')}"
77 except Exception as e:
78 return f"出错了:{e}"
79
80bot = AIAssistant()
81for q in ["现在几点", "算 1234*5678", "添加待办:学Agent", "我的待办列表", "完成待办1"]:
82 print(f"你: {q}")
83 print(f"AI: {bot.chat(q)}\n")