AI agents are the hottest topic in 2026. But most tutorials either oversimplify (here's a chatbot with `while True`) or overcomplicate (here's a 12-repo microservice architecture).
This is the middle path. You'll build a working AI agent in about 50 lines of code.
What Makes Something an "Agent"?
An agent is an AI system that can:
- **Use tools** — call APIs, run code, search the web
- Search the web for Tokyo's population
- **Long-term memory** — Store conversations in a vector database
- **Multi-step planning** — Break complex tasks into sub-tasks
- **Parallel tool calls** — Run independent tools simultaneously
- **Human-in-the-loop** — Ask for confirmation before destructive actions
- Rate limiting and cost tracking
- Timeouts for tool calls
- Retry logic on failures
- Structured logging
- Authentication for external tools
2. Make decisions — choose which tool to use based on context
3. Maintain state — remember what it's doing across steps
Not just "chat." Not just "function calling." An agent loops: think → act → observe → think again.
Step 1: The Core Loop
import json
from openai import OpenAI
client = OpenAI()
def agent_loop(messages, tools, max_steps=10):
for step in range(max_steps):
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools,
tool_choice="auto"
)
msg = response.choices[0].message
messages.append(msg)
# No tool call? Agent is done
if not msg.tool_calls:
return msg.content
# Execute each tool call
for tc in msg.tool_calls:
result = execute_tool(tc.function.name, tc.function.arguments)
messages.append({
"role": "tool",
"tool_call_id": tc.id,
"content": json.dumps(result)
})
return "Max steps reached"
That's the engine. 20 lines. Everything else is just tools and prompts.
Step 2: Define Tools
Tools are functions the agent can call. Each needs a name, description, and parameter schema:
tools = [
{
"type": "function",
"function": {
"name": "web_search",
"description": "Search the web for current information",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Search query"
}
},
"required": ["query"]
}
}
},
{
"type": "function",
"function": {
"name": "calculate",
"description": "Perform mathematical calculations",
"parameters": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "Math expression"
}
},
"required": ["expression"]
}
}
}
]
Step 3: Implement Tool Execution
import requests
import math
def execute_tool(name, args_str):
args = json.loads(args_str)
if name == "web_search":
resp = requests.get(f"https://api.duckduckgo.com/?q={args['query']}&format=json")
return resp.json()
elif name == "calculate":
# SAFE eval for math only
allowed = {"abs": abs, "round": round, "sqrt": math.sqrt, "pow": pow}
result = eval(args["expression"], {"__builtins__": {}}, allowed)
return {"result": result}
return {"error": f"Unknown tool: {name}"}
Step 4: Run It
messages = [
{"role": "system", "content": "You are a helpful AI agent. Use tools when needed."},
{"role": "user", "content": "What was the population of Tokyo in 2023, and what's 15% of it?"}
]
result = agent_loop(messages, tools)
print(result)
The agent will:
2. Calculate 15% of the result
3. Combine both into a natural answer
Step 5: Add Memory
A session with memory:
class Agent:
def __init__(self, system_prompt):
self.messages = [
{"role": "system", "content": system_prompt}
]
self.tools = []
def add_tool(self, tool_def, handler):
self.tools.append(tool_def)
self.handlers[tool_def["function"]["name"]] = handler
def run(self, user_input):
self.messages.append({"role": "user", "content": user_input})
return agent_loop(self.messages, self.tools)
def get_history(self):
return self.messages
Now the agent remembers context across turns — a real conversation.
Beyond the Basics
This simple agent can be extended with:
Production Considerations
For a production agent, you'd want:
Verdict
Building an AI agent is simpler than you think. The core loop is ~20 lines. Everything else is tool definitions and prompt engineering.
The real skill isn't in writing the agent — it's in designing good tools and prompts that the agent can use effectively. That's where the 80/20 leverage is.
Try it: Copy the code above, add a couple of tools, and see what your agent can do.