By the end of this lesson you will be able to:
- Explain what makes an AI agent different from a chatbot.
- Describe the agent loop: think → act → observe → repeat.
- Name the parts of an agent: model, tools, memory, planning and guardrails.
- Build a simple agent loop in Python with a step limit.
From answering to doing
A chatbot answers one message at a time. An AI agent is given a goal, such as "make me a 2-week revision plan for Class 10 Physics and put it in my calendar". It works out the steps on its own: look up the syllabus, calculate the days, create calendar events, then report back.
Agents combine everything from this course: prompts (Lessons 4–5), tools and function calling (Lesson 11), RAG for knowledge (Lesson 15) and safety (Lessons 3 and 13).
The agent loop
Most agents follow a pattern called ReAct (reason + act). The model thinks about what to do next, acts by calling a tool, observes the result, and repeats until the goal is met. Watch an agent plan a revision schedule:
The parts of an agent
- Model (the brain): an LLM good at reasoning and tool use.
- Tools (the hands): functions it may call: search, calculator, calendar, database, code execution and more.
- Memory: short-term (this task's steps and results) and long-term (preferences and past facts stored in a database or vector store).
- Planning: breaking a goal into steps, sometimes writing the whole plan first, sometimes deciding one step at a time.
- Guardrails: step limits, allowed tools, budgets and human approval for risky actions.
Chatbot
One request → one answer. The user does the steps. Predictable, cheap and easy to test.
Agent
One goal → many model calls and tool calls. The agent does the steps. Powerful, but slower, costlier and harder to control.
Agent frameworks
You can write the loop yourself (you will, below!), but frameworks handle tool schemas, memory, retries and multi-agent setups:
- Microsoft: Semantic Kernel and AutoGen, plus Azure AI Foundry's Agent Service.
- LangChain / LangGraph: popular open-source libraries for chains and graph-shaped agents.
- CrewAI: teams of role-playing agents.
- OpenAI Agents SDK and other provider SDKs.
- Model Context Protocol (MCP): an open standard for connecting agents to tools and data sources, supported by many of these frameworks.
Multi-agent systems
Complex jobs can be split between specialised agents: a planner breaks down the task, a researcher gathers information, a writer drafts, and a reviewer checks. They pass messages to each other. It's powerful, but every agent adds cost, delay and new ways to fail, so start with one.
Agents need strong guardrails
- Step and budget limits: stop after N steps or ₹X of tokens, so a confused agent can't loop forever.
- Least privilege: only the tools the task needs, with read-only access where possible (Lesson 13).
- Human in the loop: require approval before sending, paying, deleting or publishing.
- Logging and tracing: record every thought, tool call and result, so you can debug and audit.
- Evaluate whole tasks: test on complete goals, not just single answers (Lesson 14).
Agents make mistakes confidently and repeatedly. A wrong early observation can derail every later step. Prefer narrow, well-defined agents with clear stop conditions over "do anything" agents.
Hands-on
Your task: fake_llm() stands in for the model. It returns either a tool call or a final answer. Complete the loop: when the reply is a tool call, run the tool and add the observation to history; when it's "finish", print the answer and Finished in N steps.
def search_syllabus(subject):
return {"Physics": ["Light", "Human Eye", "Electricity", "Magnetism", "Energy"]}[subject]
def calculator(expression):
return eval(expression, {"__builtins__": {}}) # demo only: never eval untrusted input in real apps
TOOLS = {"search_syllabus": search_syllabus, "calculator": calculator}
def fake_llm(history):
# A scripted "model" that decides based on what it has observed so far
seen = [h for h in history if h["role"] == "observation"]
if len(seen) == 0:
return {"type": "tool", "name": "search_syllabus", "args": {"subject": "Physics"}}
if len(seen) == 1:
return {"type": "tool", "name": "calculator", "args": {"expression": f"(14 - 4) / {len(seen[0]['content'])}"}}
return {"type": "finish", "answer": f"Study each chapter for {seen[1]['content']:.0f} days, then revise for 4 days."}
history = [{"role": "goal", "content": "2-week Physics revision plan"}]
MAX_STEPS = 5
for step in range(1, MAX_STEPS + 1):
reply = fake_llm(history)
# TODO: if reply["type"] == "tool": run TOOLS[reply["name"]](**reply["args"]),
# print it, and append {"role": "observation", "content": result} to history
# TODO: if reply["type"] == "finish": print the answer, print f"Finished in {step} steps" and break
pass
else:
print("Stopped: hit the step limit")
Show solution
if reply["type"] == "tool":
result = TOOLS[reply["name"]](**reply["args"])
print(f"Step {step}: {reply['name']}({reply['args']}) -> {result}")
history.append({"role": "observation", "content": result})
elif reply["type"] == "finish":
print("Answer:", reply["answer"])
print(f"Finished in {step} steps")
break
Your task: some tools are risky. Complete guard(): if the tool is in NEEDS_APPROVAL and approved is False, return the message "Blocked: <tool> needs approval"; if the tool isn't in ALLOWED at all, return "Blocked: <tool> is not allowed"; otherwise return "OK".
ALLOWED = {"search_syllabus", "calculator", "calendar", "send_message"}
NEEDS_APPROVAL = {"send_message"}
def guard(tool, approved=False):
# TODO: implement the two checks described above
return "OK"
for tool, approved in [("calculator", False), ("send_message", False), ("send_message", True), ("delete_all_files", False)]:
print(f"{tool:18} approved={approved!s:5} -> {guard(tool, approved)}")
Show solution
def guard(tool, approved=False):
if tool not in ALLOWED:
return f"Blocked: {tool} is not allowed"
if tool in NEEDS_APPROVAL and not approved:
return f"Blocked: {tool} needs approval"
return "OK"
Check your understanding
What is the core loop of most AI agents?
- Train → test → deploy
- Prompt → answer → done
- Think → act (use a tool) → observe → repeat
- Embed → store → search
The ReAct-style loop repeats reasoning, tool use and observation until the goal is met.
Why must agents have a maximum number of steps?
- To stop a confused agent looping forever and burning money
- Because models can only make 5 calls
- To make answers longer
- It's required by Hugging Face
Step and budget limits are basic guardrails against runaway loops.
An agent wants to email all parents a fee reminder. What should happen?
- Send immediately, since agents are autonomous
- Pause for a human to review and approve the message
- Retry until it works
- Send to a random sample first without telling anyone
Actions with real-world effects need human approval.
Key takeaways
- Agents pursue goals by looping: think → act → observe.
- They combine a model, tools, memory, planning and guardrails.
- Frameworks (Semantic Kernel, AutoGen, LangGraph, CrewAI) and standards like MCP speed up building.
- Limit steps and permissions, keep humans in the loop and log everything.
Next: fine-tuning, teaching a model new behaviour with your own examples.
Your progress is saved in this browser.
Adapted from Lesson 17 of Microsoft's "Generative AI for Beginners" (MIT License), rewritten and extended by Aiprojects4U. View source