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 precisely, separates agents from two things they are often confused with (a single LLM call and a fixed workflow), and gives criteria for deciding when an agent is worth building.
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.
Later chapters cover prompts, tool calling, and the loop in detail. Here you only need the overall shape.
The working definition
Three properties together make a program an agent:
- The model decides the next step. Your code does not hard-code the sequence of actions. The model picks one based on the goal and what it has seen so far.
- Actions happen through tools. A tool is a function your code exposes, such as a search call, a database query, or a file write. The model requests a tool by name with arguments. Your code runs it.
- Results feed back in. Each tool result is added to the conversation history, so the model's next decision can depend on what actually happened.
The cycle repeats until the model answers without requesting a tool, or until a limit such as a maximum step count stops it.
Three levels of LLM-based programs
The same model can be used in three structurally different ways.
| Pattern | Who chooses the steps | Number of model calls | Typical example |
|---|---|---|---|
| Single LLM call | Nobody. One prompt, one reply. | 1 | Summarize this paragraph |
| Fixed workflow | Your code, in advance | Several, in a set order | Extract fields, validate, then draft an email |
| Agent | The model, at run time | Variable | Investigate why a deployment failed |
Single call
A single call takes input and returns text. It has no tools and no loop. If the task fits in one prompt, such as classification, rewriting, or extraction from provided text, this is the right choice. It is the cheapest, fastest, and easiest to test.
Fixed workflow
A workflow chains several model calls and ordinary code steps in an order you wrote. The model may fill in content at each step, but it never decides which step comes next. Branches exist, but you wrote them: "if the classifier says billing, go to the billing prompt."
Agent
In an agent, the number and order of steps are not known until the run happens. The model might call a search tool three times, then a calculator, then answer. Another run on a similar goal might take a different path.
A minimal agent in code
The following code shows the whole idea in about thirty lines. The first piece is a tool registry. run_tool returns errors as text so the model can read them and recover instead of the program crashing.
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)})The loop asks the model for its next step, runs any requested tool, appends the result to the history, and stops when the model answers without a tool call or when max_steps is reached.
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."To test the loop without a real model, replace the model with a scripted stand-in. This run makes one tool call and then prints the final answer.
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 three code blocks form one program. Run them in order in a single file, and it prints It is 18 C in Oslo.
Notice where the decision lives. In run_agent, nothing says "call get_weather first." The only control flow your code owns is the loop, the stop condition, and the tool dispatch. Which tool runs, and when to stop, comes from the model's reply.
When you need an agent
An agent trades predictability for flexibility. Use that trade only when the task needs flexibility. Check these criteria in order, and stop at the first design that works.
- Can one call do it? If all the needed information is in the prompt and the output is one piece of text, use a single call.
- Can you write the steps down? If you can list the steps before the run, even with a few branches, use a workflow. It is easier to test, cheaper, and faster.
- Does the path depend on intermediate results? If you cannot know the steps until you see what earlier steps return, an agent fits. Debugging an unfamiliar error, researching an open-ended question, or navigating a codebase are typical cases.
- Is a wrong step recoverable? Agents make mistakes. They suit tasks where a mistake can be detected and undone, or where a human approves risky actions.
Costs of choosing an agent
- More model calls. Each loop iteration is another call, and the history grows, so cost and latency rise with the number of steps.
- Less predictable behavior. The same goal can produce different paths. Tests must check outcomes, not exact step sequences.
- More failure modes. The model can pick the wrong tool, pass bad arguments, loop without progress, or stop too early.
- Harder debugging. You need traces of each step to see why a run went wrong.
Edge cases and common mistakes
- Calling a chatbot with a tool an agent. One tool call followed by a fixed next step is a workflow. The defining property is that the model chooses among steps over multiple iterations.
- Leaving out the step limit. Without
max_steps, a confused model can loop and spend money indefinitely. Always bound the loop. - Raising exceptions from tools. In the code above, errors return as text. The model can then retry with different arguments or choose another tool. A crash ends the run with no chance to recover.
- Judging an agent by one run. Because paths vary, one successful run proves little. Chapter material on evaluation covers using sets of test tasks.
- Giving the model more tools than the task needs. Each extra tool is another wrong choice the model can make.
Where this chapter fits
The rest of the tutorial builds on this definition. Tool calling and structured outputs explain how a model's request becomes a function call. The agent loop chapter expands the code above with stop conditions and history management. Guardrails, evaluation, and tracing make an agent safe and measurable enough to run in production.
Exercise
A support tool must read a customer email, classify it as billing, shipping, or other, and then draft a reply using a different prompt for each class. Should you build a single call, a workflow, or an agent? Give the reason.
Show answer
A workflow. The steps (classify, then pick a prompt, then draft) can be written down in advance, and the model never needs to choose the next step. A single call would mix two jobs in one prompt, and an agent would add cost and unpredictability without a benefit.
Exercise
In the run_agent code, what stops the loop in each of the two ways it can end, and what does the function return in each case?
Show answer
If the model's reply has no tool call, the loop returns the reply's content as the final answer. If the loop runs max_steps times without such a reply, it returns the string "Stopped: step limit reached."
Exercise
Change fake_model so that it asks for a city that is not in your tool set, by requesting a tool named "get_time". What does the history contain after the tool step, and why does the program not crash?
Show answer
The tool message contains {"error": "unknown tool: get_time"}. run_tool checks the name against TOOLS and returns the error as JSON text instead of raising, so the loop continues and the model can read the error on its next turn.