Sub topic 2
What an AI agent is and how it differs from a chatbot
This chapter assumes you know basic marketing metrics (impressions, clicks, conversions, spend), can read short Python programs, and have a general idea of what a large language model (LLM) is. It also assumes you are comfortable with JSON. The chapter defines an agent, compares it with a chatbot, and names the parts every agent in this tutorial will have. Later chapters cover each part in detail.
A working definition
An AI agent is a program that uses a language model to decide what to do next, takes actions through tools, reads the results, and repeats until a stop condition is met. The model supplies judgment. The surrounding program supplies the actions, the memory and the limits.
Three properties separate an agent from a plain model call:
- Tools. The agent can act outside the conversation. Examples are querying an ad platform, running a calculation, or fetching a web page.
- A loop. The agent can take several steps. The result of one step shapes the next.
- A stop condition. The agent ends when it has a final answer or when a limit, such as a maximum number of steps, is reached.
The word "agent" is used loosely in the industry. Here it means this narrow, concrete pattern: model, tools, loop, stop condition.
Chatbot versus agent
A chatbot takes your message, sends it to a model, and returns the model's text. The model works only from what is in the conversation and from what it learned in training. It cannot look anything up and cannot run anything.
Suppose you ask each system: "What was our cost per acquisition last month?"
- A chatbot has no access to your data. At best it says so. At worst it invents a plausible number.
- An agent calls a tool that fetches last month's rows, calls a second tool that computes cost per acquisition (CPA), and reports the result.
| Aspect | Chatbot | Agent |
|---|---|---|
| Model calls per request | One | One or more, in a loop |
| Access to your data | Only what you paste in | Through tools you provide |
| Can take actions | No | Yes, within the tools it is given |
| Source of numbers | Model memory or your paste | Tool output |
| Main risk | Invented facts | Wrong actions, runaway cost, invented facts in the final text |
| Stops when | The reply is complete | A final answer, an error, or a step limit |
An agent is not simply a smarter chatbot. It is a larger system with more ways to fail, and the extra capability is worth it only when a task needs data or actions the model cannot supply on its own.
The parts of an agent
Every agent in this tutorial has the same five parts.
- The model. It reads the task and the history so far, then chooses the next step. That step is either a request to use a tool or a final answer.
- The tools. These are ordinary functions that the model can request by name with arguments. They do the work that must be exact, such as fetching data or doing arithmetic.
- The history. This is the list of messages: the task, each tool request, and each tool result. The model sees the full history on every call. It has no other memory.
- The controller. This is the code that calls the model, runs the requested tool, appends the result to the history and checks the stop condition. The model never executes anything itself. Your code does.
- The limits. These are the maximum steps, the allowed tools and the data the agent may reach.
The controller is the part people tend to forget. The model only produces text. When that text says "call the tool campaign_metrics", it is your controller that decides whether to do it.
A runnable comparison
The next program contrasts the two designs. It uses a scripted stand-in for the model so it runs without any API key. The stand-in behaves the way a real model would in this situation: it asks for a tool first, then writes an answer from the tool's result. The message format, a dictionary with either tool and args or final, is the same one used in the agent loop chapter.
import json
DATA = [
{"campaign": "spring", "spend": 150.0},
{"campaign": "summer", "spend": 60.0},
]
def total_spend():
"""A tool: exact arithmetic on real rows."""
return round(sum(r["spend"] for r in DATA), 2)
TOOLS = {"total_spend": total_spend}
def chatbot_model(messages):
# A chatbot call: one reply, no data access.
return {"final": "I do not have access to your campaign data."}
def scripted_agent_model(messages):
# Stand-in for a real model: ask for a tool first, then answer.
if len(messages) == 1:
return {"tool": "total_spend", "args": {}}
result = json.loads(messages[-1]["content"])["tool_result"]
return {"final": "Total spend was " + str(result) + "."}
def chat(question, call_model):
return call_model([{"role": "user", "content": question}])["final"]
def agent(question, call_model, tools, max_steps=5):
messages = [{"role": "user", "content": question}]
for _ in range(max_steps):
reply = call_model(messages)
if "final" in reply:
return reply["final"]
result = tools[reply["tool"]](**reply["args"])
messages.append({"role": "assistant", "content": json.dumps(reply)})
messages.append({"role": "user", "content": json.dumps({"tool_result": result})})
raise RuntimeError("step limit reached without a final answer")
question = "What was our total spend?"
print("Chatbot:", chat(question, chatbot_model))
print("Agent: ", agent(question, scripted_agent_model, TOOLS))Running it prints:
Chatbot: I do not have access to your campaign data.
Agent: Total spend was 210.0.Notice where the number 210.0 comes from. The tool computed it from the rows. The model only wrote the sentence around it. This division of labor, with code producing numbers and the model producing language, is the main design idea of this tutorial.
What an agent adds and what it does not fix
Giving a model tools fixes one problem: it no longer has to guess data it cannot see. It does not fix the others.
- The final text can still be wrong. The model may misread a tool result, round a number differently, or add a claim that no tool supported. The chapters on grounding and verification address this.
- The model can choose badly. It may call the wrong tool, pass the wrong date range, or call a tool when it should have stopped. The tool descriptions and the prompt affect these choices.
- Errors compound. In a loop, a wrong early step feeds every later step. A single bad filter on a date range can corrupt the whole report.
- Cost and time grow with steps. Each loop iteration is another model call that sends the whole history. A ten-step run costs far more than ten times a single call as the history grows.
Deciding whether a task needs an agent
Use the simplest design that works. A useful way to decide is to ask what the task needs.
- The model has everything it needs in the prompt. Use a single model call. Example: rewrite this paragraph in a plainer tone.
- The steps are fixed and known in advance. Use a fixed pipeline: fetch, calculate, then draft. Your code orders the steps and the model only fills in the language. This is cheaper and easier to test than an agent.
- The next step depends on what the last step found. Use an agent. Example: "Find out why conversions fell last week." The agent may first check spend, then break results down by channel, then inspect one campaign that stands out. You cannot write that sequence in advance.
Common mistakes at this stage
- Treating the model as the calculator. If a number matters, a tool should compute it. The metrics chapter covers this.
- Assuming the model remembers earlier runs. Each run starts with an empty history unless your code supplies one.
- Letting the loop run without a limit. Without a step limit, a confused model can call tools indefinitely and run up costs. The loop in this chapter raises an error when the limit is reached.
- Trusting the final text because the tools were correct. Correct tool results do not guarantee a correct summary of them.
Summary
An agent is a model plus tools plus a loop plus a stop condition, with a controller in your code that does the actual running. Compared with a chatbot, it can reach real data and take actions, which makes it useful for open-ended research. It also brings new failure modes: wrong tool choices, compounding errors, cost growth and, if write tools are added, real-world side effects. The next chapters look at where the model itself goes wrong, then at the tools and loop in detail.
Exercise
A teammate says, "We built an agent: it sends our weekly spend table to a model, and the model writes a summary paragraph." Using the definition in this chapter, is this an agent? What single change would turn it into an agent for the question "Why did conversions drop last week?"
Show answer
As described, it is not an agent. It is a fixed pipeline with one model call, with no tools, no loop and no stop condition, and the model never chooses what to do next. To make it an agent, give the model tools such as one to fetch conversions by channel and one to compute metrics, and run it in a controller loop with a step limit. The model can then decide which breakdown to inspect next based on what each tool returns.
Exercise
In the runnable example, the agent answers "Total spend was 210.0." Which component produced the number 210.0, which component produced the sentence, and what would happen if the scripted model kept requesting total_spend forever?
Show answer
The tool total_spend produced the number by summing the rows. The model produced the sentence around it. If the model kept requesting the tool, the loop would run max_steps times (5 by default) and then raise RuntimeError("step limit reached without a final answer"), instead of running indefinitely.