Building AI Agents

Agent Architecture

AI Agent Architecture

An AI agent is a system that can perceive its environment, make decisions, and take actions to achieve goals.

Core Components

  • LLM Core — The "brain" that processes and generates
  • Memory — Conversation history and context
  • Tools — Functions the agent can call
  • Orchestrator — Logic that ties everything together

Agent Loop

1. Receive input
2. Think (LLM generates plan)
3. Act (call tools if needed)
4. Observe (get tool results)
5. Respond (generate final output)
6. Loop back if needed

Design Principles

  • Single responsibility — Each tool does one thing
  • Clear interfaces — Well-defined inputs/outputs
  • Error handling — Graceful failure recovery
  • Observability — Log important events

Try It Yourself

Run this code example to practice what you've learned.

example.py
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 # In real agents, this would call an LLM
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 # Think
45 action = self.think(user_input)
46 print(f"🤔 Thinking: {action}")
47
48 # Act
49 result = self.act(action)
50 print(f"🤖 {self.name}: {result}")
51
52 # Store in memory
53 self.memory.append({"input": user_input, "output": result})
54
55 return result
56
57# Create agent and register tools
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# Run the agent
73agent.run("Can you search for Python tutorials?")
74agent.run("Calculate 6 times 7")
75agent.run("Tell me a joke")