Sub topic 1
What an AI agent is, and when you need one
An AI agent is a program in which a language model chooses actions, runs them through tools, observes the results, and repeats until a goal is met or a limit is reached. This chapter defines the term, compares agents with simpler designs, and gives criteria for deciding when you need one.
Prerequisites
This chapter assumes you have:
- Programming experience in Python or a similar language.
- Basic familiarity with calling web APIs and handling JSON.
- A working idea of what a large language model (LLM) is and how prompts work.
Three designs, one spectrum
Most LLM features fall into one of three designs.
- Single LLM call. You send a prompt and use the reply. Example: summarize this email.
- Fixed workflow. Your code defines the steps and calls the model at set points. Example: extract fields, validate them, then write a reply.
- Agent. The model decides which step comes next, at run time, based on what it has seen so far.
The key difference is who controls the flow. In a workflow, your code does. In an agent, the model does.
The parts of an agent
Every agent has four parts:
- A model that reads the history and picks the next step.
- Tools, which are functions the model can request, such as a weather lookup or a database query.
- A loop that runs the requested tool and feeds the result back.
- A stop condition, such as a final answer or a maximum number of steps.
The model never runs anything itself. It emits a request, and your program decides whether to execute it.
A minimal agent
The code below is a complete agent. A scripted fake_model stands in for a real model so that the run is deterministic.
import json
def get_weather(city: str) -> str:
# Stand-in for a real API call.
return json.dumps({"city": city, "temp_c": 18})
TOOLS = {"get_weather": get_weather}
def run_tool(name: str, arguments: dict) -> str:
if name not in TOOLS:
return json.dumps({"error": f"unknown tool: {name}"})
try:
return TOOLS[name](**arguments)
except Exception as exc:
return json.dumps({"error": str(exc)})
def run_agent(call_model, user_goal: str, max_steps: int = 8) -> str:
messages = [{"role": "user", "content": user_goal}]
for _ in range(max_steps):
reply = call_model(messages)
messages.append({"role": "assistant", "content": reply.get("content"), "tool_call": reply.get("tool_call")})
call = reply.get("tool_call")
if call is None:
return reply["content"]
result = run_tool(call["name"], call["arguments"])
messages.append({"role": "tool", "name": call["name"], "content": result})
return "Stopped: step limit reached."
def fake_model(messages):
# Scripted stand-in for a real model, useful for testing the loop.
if messages[-1]["role"] == "user":
return {"content": None, "tool_call": {"name": "get_weather", "arguments": {"city": "Oslo"}}}
return {"content": "It is 18 C in Oslo.", "tool_call": None}
print(run_agent(fake_model, "What is the weather in Oslo?"))The run prints It is 18 C in Oslo. after one tool call. Two details matter. run_tool returns errors as text, so the model can read them and recover instead of the program crashing. max_steps guarantees the loop ends even if the model never stops asking for tools.
When you need an agent
Use the simplest design that works.
| Situation | Best fit |
|---|---|
| One transformation of known input | Single call |
| Steps are known in advance and rarely change | Fixed workflow |
| Steps depend on intermediate results and cannot be listed ahead | Agent |
Choose an agent when the path is unpredictable, for example debugging a failing build, where each finding decides the next action. Avoid one when a workflow would do. Agents cost more, respond more slowly, and are harder to test, because the model can take a different path on each run.
Exercise
Exercise
A feature reads a support ticket, classifies it as billing, technical, or other, and drafts a reply template. The steps never change. Should you build an agent, a workflow, or a single call? Why?
Show answer
A fixed workflow, or possibly one structured call. The steps are known in advance, so your code can control the flow. An agent would add cost, latency, and unpredictability without any benefit.
Exercise
In the minimal agent, what two things stop the loop?
Show answer
The model replies without a tool call, which returns its content as the final answer, or the loop reaches max_steps and returns the "Stopped: step limit reached." message.