75 mins lesson duration•12 mins read
Lesson 12: Building a Simple Agent
Hands-on: assemble a minimal agent with tools, memory, and stop conditions — then meet the frameworks that do it for you.
Anatomy of a Real Agent
Every production agent has four parts:
- Model — the reasoning brain.
- Tools — what it can do (search, code, APIs).
- Memory / state — conversation history, files, results so far.
- Control loop — decide → act → observe → repeat, with stop conditions.
Minimal Agent Pseudocode
def run_agent(task, tools, max_steps=8):
messages = [system_prompt(tools), user(task)]
for step in range(max_steps):
reply = model.call(messages)
if reply.is_final_answer:
return reply.text
result = execute(reply.tool_call) # your code, not the model!
messages.append(tool_result(result))
return "Stopped: max steps reached"
The Three Control-Flow Patterns
| Pattern | What It Does | Use When |
|---|---|---|
| Single loop | One agent loops until done | One clear job |
| Router | A planner picks a specialist sub-agent | Mixed tasks (chat, code, data) |
| Multi-agent | Several agents talk to each other | Complex pipelines (research → write → review) |
Memory: Short-Term vs. Long-Term
- Short-term: messages inside the context window (trim/summarize old turns).
- Long-term: a vector database of past facts/decisions the agent retrieves (agent memory / RAG).
Frameworks (Choose by Need)
| Framework | Vibe | Best For |
|---|---|---|
| LangGraph | Graph-based state machines | Production, controllable agents |
| OpenAI Agents SDK | Simple, function-calling native | Fast start with OpenAI models |
| CrewAI | Role-based 'crews' | Multi-agent teams |
| Claude Agent SDK | Tool use + computer use | Claude ecosystem, browser agents |
| Roll your own | ~100 lines loop | Learning + minimal deps |
Rule of thumb: start by writing the loop yourself once (you'll learn everything); then use a framework for production.
Debugging Agents
- Log every step: input tokens, tool calls, observations, costs.
- Reproduce with temperature 0 and fixed seeds when possible.
- Watch for loops (same action twice) — add a dedupe: "already tried, don't repeat".
- Budget tokens: cap max steps and track spend per run.
A Simple Agent Example (Concept)
System: "You are a research assistant with tools: search_web, read_url,
summarize. Plan your steps. Stop when you have a 5-bullet answer."
User: "What are the top 3 AI trends of 2026?"
1. Thought: search the web for AI trends 2026
2. Action: search_web("AI trends 2026")
3. Observation: [10 results]
4. Thought: read the top 3 articles
5. Action: read_url(result[0].url) … (repeat)
6. Thought: I have enough — write the answer
7. Final Answer: 5 bullets with sources
Key Takeaways
- An agent = model + tools + memory + a control loop with stop conditions.
- Your code executes tools; the model only proposes calls.
- Start with a hand-written loop, then adopt a framework for production.
- Log everything and cap steps — agents fail by looping and overspending.
Next up: Advanced LLM topics — RAG, embeddings, and evaluation.
Interactive Lesson Code Snippet
# A minimal autonomous agent: search + summarize tools with a control loop
def search(query):
return f"Top result for '{query}': https://example.com/{query.replace(' ', '-')}"
def summarize(text):
words = text.split()
return " ".join(words[:8]) + "..." if len(words) > 8 else text
def run_agent(task):
print(f"Task: {task}\n")
print("1. Thought: I'll search the web first.")
obs = search(task)
print(f" Action: search('{task}')")
print(f" Observation: {obs}")
print("2. Thought: Now I'll summarize what I found.")
summary = summarize(obs)
print(" Action: summarize(observation)")
print(f" Observation: {summary}")
print("3. Final Answer: Done - returning the summary to the user.")
return summary
result = run_agent("latest AI news")
print(f"\nAgent returned: {result}")Language: python
Lesson Code (Python)
# A minimal autonomous agent: search + summarize tools with a control loop
def search(query):
return f"Top result for '{query}': https://example.com/{query.replace(' ', '-')}"
def summarize(text):
words = text.split()
return " ".join(words[:8]) + "..." if len(words) > 8 else text
def run_agent(task):
print(f"Task: {task}\n")
print("1. Thought: I'll search the web first.")
obs = search(task)
print(f" Action: search('{task}')")
print(f" Observation: {obs}")
print("2. Thought: Now I'll summarize what I found.")
summary = summarize(obs)
print(" Action: summarize(observation)")
print(f" Observation: {summary}")
print("3. Final Answer: Done - returning the summary to the user.")
return summary
result = run_agent("latest AI news")
print(f"\nAgent returned: {result}")Console Output
Task: latest AI news
1. Thought: I'll search the web first.
Action: search('latest AI news')
Observation: Top result for 'latest AI news': https://example.com/latest-AI-news
2. Thought: Now I'll summarize what I found.
Action: summarize(observation)
Observation: Top result for 'latest AI news': https://example.com/latest-AI-news
3. Final Answer: Done - returning the summary to the user.
Agent returned: Top result for 'latest AI news': https://example.com/latest-AI-newsCode Visualization Tips
- Draw the agent anatomy diagram: Model, Tools, Memory, Control loop as four connected boxes.
- Map the three control-flow patterns (single loop, router, multi-agent) as different graphs.
- Add a 'budget meter' to your agent sketch — step counter and token counter ticking up.
Professional Tips & Tricks
- Prototype with the cheapest model; swap in the smart one only when the loop is stable.
- Add a 'final answer' tool — forcing explicit completion prevents vague early exits.
- Test agents on 5–10 canned tasks with recorded transcripts before letting them loose.
Python Code Judge & Practice Arena
LeetCode StyleRun real Python 3.12 WebAssembly code directly in your browser against automated test suites.
Solved:0 / 1
0 / 30 XP
Problem 1 of 1
Design an Agent Spec
Hard+30 XP
Spec the four parts (model, tools, memory, control loop) for a 'meeting note taker' agent that records action items from a transcript and emails them.
main.pyPython 3.12 (WASM)
1
2
3
4
5
6
7
8
9
10
11
12
Press Run Code to test or Submit to verify test cases
Up next · Continue learning
RAG — Retrieval-Augmented Generation
RAG grounds LLM answers in your own data: index, retrieve, augment, generate. The professional standard for trustworthy AI.
11 mins read60 mins
Start next lesson