1from typing import Callable, Any
2import json
3
4class SimpleAgent:
5 """A minimal AI agent implementation."""
6
7 def __init__(self, name: str):
8 self.name = name
9 self.tools: dict[str, Callable] = {}
10 self.memory: list[dict] = []
11
12 def register_tool(self, name: str, func: Callable, description: str):
13 """Register a tool the agent can use."""
14 self.tools[name] = {
15 "function": func,
16 "description": description
17 }
18 print(f"✓ Registered tool: {name}")
19
20 def think(self, user_input: str) -> dict:
21 """Decide what action to take (simplified)."""
22
23 if "calculate" in user_input.lower():
24 return {"action": "calculator", "input": user_input}
25 elif "search" in user_input.lower():
26 return {"action": "search", "input": user_input}
27 return {"action": "respond", "input": user_input}
28
29 def act(self, action: dict) -> str:
30 """Execute the decided action."""
31 tool_name = action["action"]
32
33 if tool_name in self.tools:
34 tool = self.tools[tool_name]
35 result = tool["function"](action["input"])
36 return f"Tool result: {result}"
37
38 return f"I'll help with: {action['input']}"
39
40 def run(self, user_input: str) -> str:
41 """Main agent loop."""
42 print(f"\n👤 User: {user_input}")
43
44
45 action = self.think(user_input)
46 print(f"🤔 Thinking: {action}")
47
48
49 result = self.act(action)
50 print(f"🤖 {self.name}: {result}")
51
52
53 self.memory.append({"input": user_input, "output": result})
54
55 return result
56
57
58agent = SimpleAgent("Helper")
59
60agent.register_tool(
61 "calculator",
62 lambda x: "42 (simulated calculation)",
63 "Performs calculations"
64)
65
66agent.register_tool(
67 "search",
68 lambda x: "Found 3 results (simulated)",
69 "Searches the web"
70)
71
72
73agent.run("Can you search for Python tutorials?")
74agent.run("Calculate 6 times 7")
75agent.run("Tell me a joke")