About this notebook
Companion to Module 1: What is an agent?. Every cell below was executed with the offline backend, so you can reproduce these outputs exactly with no API key. Download the notebook (.ipynb)
This notebook builds the smallest thing that deserves the name agent: a loop in which a model chooses an action, your code carries it out, and the result goes back to the model. Along the way you will
- call a model once, and see exactly what is sent over the wire;
- turn two Python functions into tools the model can ask for;
- write a workflow, where your code fixes the path, for contrast;
- write the agent loop from scratch, in about 25 lines;
- break it on purpose: a failing tool, and a model that never stops;
- run the same task through
agentlab.Agent, the class the rest of the course extends.
Which model answers here?
The first cell picks a backend. With no
MODELset it uses the offline policy model: a small set of deterministic rules that read the request (the messages and the tool schemas) and answer the way a tool-calling model would. It is not a language model, and nothing in this notebook should be read as evidence of how a real model behaves. It lets the loop run with no API key and gives the same output every time. SetMODEL(for exampleMODEL=anthropic/claude-sonnet-5-5withANTHROPIC_API_KEY) and re-run to get a real model; the agent code does not change.
from agentlab.nbsetup import setup
nb = setup("01_agent_loop", packs=["loop"])
llm = nb.llmLLM backend
offline policy model (deterministic, rule-based, no API key used)
1. One model call
A chat model is a function from a list of messages to one new message. agentlab wraps the
list in an LlmRequest: instructions become system messages and contents holds the
conversation.
from agentlab import LlmRequest, Message
request = LlmRequest(
instructions=["You are a concise assistant."],
contents=[Message(role="user", content="What is the weather in Paris right now?")],
)
response = await llm.generate(request)
print(response.text)[offline model] I received 1 system and 1 conversation message(s); the latest asks about "the weather in Paris right now". Set MODEL to get a real answer.
The model has no way to know today’s weather: it can only produce text. A real model would either say so or, worse, make up a plausible temperature. To answer it needs an action.
Before adding one, look at what actually goes over the wire. build_messages converts the
request into the chat-completions format that every major provider accepts (LiteLLM, used
later, translates it for providers with a different native format).
import json
from agentlab.llm.base import build_messages
print(json.dumps(build_messages(request), indent=2))[
{
"role": "system",
"content": "You are a concise assistant."
},
{
"role": "user",
"content": "What is the weather in Paris right now?"
}
]
Two things to remember from this printout. First, the request is all the model sees: there is no hidden memory on the provider’s side, so anything the model should know must be in this list. Second, the list only grows when your code appends to it, and appending is exactly what the agent loop will do.
2. Tools: functions the model can ask for
A tool is an ordinary function plus a description the model can read. The model never runs
the function; it returns a structured request (“call get_weather with city="Paris"”),
and your code decides whether and how to run it.
from agentlab import tool
WEATHER = {"paris": (24, "sunny"), "tokyo": (27, "humid"), "oslo": (9, "light rain")}
def get_weather(city: str) -> str:
"""Current weather for a city.
Args:
city: City name, for example "Paris".
"""
celsius, sky = WEATHER[city.strip().lower()] # KeyError for an unknown city, on purpose
return f"{city.strip().title()}: {celsius}C, {sky}"
def celsius_to_fahrenheit(celsius: float) -> float:
"""Convert a temperature from Celsius to Fahrenheit.
Args:
celsius: Temperature in degrees Celsius.
"""
return round(celsius * 9 / 5 + 32, 1)
tools = [tool(get_weather), tool(celsius_to_fahrenheit)]
print(json.dumps(tools[0].tool_definition, indent=2)){
"type": "function",
"function": {
"name": "get_weather",
"description": "Current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name, for example \"Paris\"."
}
},
"required": [
"city"
]
}
}
}
The definition is generated from the signature and the docstring: the name, a one-line description, and a JSON Schema for the arguments. That schema is the model’s only view of the tool, so a vague docstring is a bug. Module 3 builds this converter from scratch.
3. A workflow: your code decides the path
The simplest way to answer “what is the weather in Oslo, in Fahrenheit?” needs no model at all: call the two functions in a fixed order.
import re
def weather_in_fahrenheit(city: str) -> str:
"""A workflow: the same three steps, in the same order, for every input."""
report = get_weather(city) # 1. look up
celsius = float(re.search(r"(-?\d+)C", report).group(1)) # 2. parse
return f"{city}: {celsius_to_fahrenheit(celsius)}F" # 3. convert, format
print(weather_in_fahrenheit("Oslo"))Oslo: 48.2F
This is predictable, cheap, and easy to test, and for a task with a known shape it is the right design. Its limit is that the shape is frozen in code. “Is it warmer in Paris or Tokyo?” needs two lookups and a comparison, and the workflow above cannot do it until someone writes a new function. The difference between the two designs is who chooses the next step:
| workflow | agent | |
|---|---|---|
| next step chosen by | your code | the model, at run time |
| new kinds of request | need new code | may work unchanged |
| cost and latency | fixed and small | varies with the number of steps |
| failure mode | rejects what it was not built for | may wander, loop, or misuse a tool |
4. The agent loop, from scratch
The loop has three moves, repeated until the model answers in plain text or the step budget runs out:
+--------------------------------------------------------------+
| |
v |
[ request = instructions + every message so far + tool schemas ] |
| |
| THINK model returns text, or one or more tool calls |
v |
text only? ---- yes ----> return it as the answer |
| |
no |
| ACT run each requested tool (errors are results too) |
v |
[ append the calls and their results to the messages ] -------------+
OBSERVE: the next request contains themfrom agentlab import ToolResult
SYSTEM = "You are a helpful assistant. Use the tools when they help, then answer briefly."
async def run_loop(question, tools, model=llm, max_steps=6, verbose=True):
by_name = {t.name: t for t in tools}
contents = [Message(role="user", content=question)]
for step in range(1, max_steps + 1):
request = LlmRequest(instructions=[SYSTEM], contents=contents,
tools=tools, tool_choice="auto")
response = await model.generate(request) # THINK
contents.extend(response.content)
if not response.tool_calls: # plain text: the answer
return response.text, contents
for call in response.tool_calls: # ACT
try:
output = await by_name[call.name](None, **call.arguments)
result = ToolResult(tool_call_id=call.tool_call_id, name=call.name,
status="success", content=[output])
except Exception as exc: # errors are observations
message = f"{type(exc).__name__}: {exc}"
result = ToolResult(tool_call_id=call.tool_call_id, name=call.name,
status="error", content=[message])
contents.append(result) # OBSERVE
if verbose:
print(f"step {step}: {call.name}({call.arguments}) "
f"-> {result.status}: {result.content[0]}")
return None, contents # budget spent, no answer
answer, transcript = await run_loop("What is the weather in Oslo in Fahrenheit?", tools)
print("\nanswer:", answer)step 1: get_weather({'city': 'Oslo'}) -> success: Oslo: 9C, light rain
step 2: celsius_to_fahrenheit({'celsius': 9.0}) -> success: 48.2
answer: It is 48.2F in Oslo right now (Oslo: 9C, light rain).
Two steps, and neither was written down anywhere: the model asked for the weather, read
9C in the result, and then asked for the conversion. Here is the conversation the model
saw on its last step, in wire format. Each tool message answers one tool_calls entry,
matched by tool_call_id.
from agentlab.display import show_messages
show_messages(build_messages(LlmRequest(instructions=[SYSTEM], contents=transcript))) system: You are a helpful assistant. Use the tools when they help, then answer briefly.
user: What is the weather in Oslo in Fahrenheit?
assistant: get_weather({"city": "Oslo"})
tool: Oslo: 9C, light rain
assistant: celsius_to_fahrenheit({"celsius": 9.0})
tool: 48.2
assistant: It is 48.2F in Oslo right now (Oslo: 9C, light rain).
The same loop handles a request the workflow could not. Both lookups are independent, so the model asks for them in a single step (a parallel tool call) and compares the results on the next one.
answer, transcript = await run_loop("Is it warmer in Paris or Tokyo?", tools)
print("\nanswer:", answer)step 1: get_weather({'city': 'Paris'}) -> success: Paris: 24C, sunny
step 1: get_weather({'city': 'Tokyo'}) -> success: Tokyo: 27C, humid
answer: Tokyo is warmer (Paris 24C, Tokyo 27C).
5. Breaking the loop on purpose
A tool that fails
get_weather raises KeyError for a city it does not know. The loop catches the exception
and hands the error message back as the tool’s result, so the model can react to it. A
crash would end the run; an observation gives the model a chance to retry, change its
arguments, or explain the failure.
answer, transcript = await run_loop("What is the weather in Atlantis in Fahrenheit?", tools)
print("\nanswer:", answer)step 1: get_weather({'city': 'Atlantis'}) -> error: KeyError: 'atlantis'
step 2: get_weather({'city': 'Atlantis'}) -> error: KeyError: 'atlantis'
answer: I could not complete this: the tool `get_weather` failed with: KeyError: 'atlantis'
The model retried once, saw the same error, and gave up with an honest message. Retrying
blindly with identical arguments is a weak strategy, and a good error message helps: compare
KeyError: 'atlantis' with “unknown city ‘Atlantis’; known cities: Oslo, Paris, Tokyo”.
Module 3 returns to writing tools whose errors help the model recover.
A model that never stops
Nothing forces a model to stop calling tools. To stage that failure exactly we swap in a
ScriptedLLM, which replays a fixed list of responses; here it repeats the same call
forever. The only thing that ends the run is max_steps.
from agentlab.llm.scripted import ScriptedLLM, ToolCallSpec
same_call = ToolCallSpec("get_weather", {"city": "Paris"})
runaway = nb.track(ScriptedLLM([same_call], repeat_last=True))
answer, transcript = await run_loop("What is the weather in Paris?", tools,
model=runaway, max_steps=8, verbose=False)
print("answer:", answer)
print("tool calls made:", sum(isinstance(x, ToolResult) for x in transcript))answer: None tool calls made: 8
A step budget is the bluntest possible guard, and every agent needs one. It also bounds the
cost, which grows faster than the number of steps: each request resends the whole
conversation so far, so the input to step
import matplotlib.pyplot as plt
import numpy as np
from agentlab.llm.base import tool_definitions
from agentlab.llm.pricing import estimate_messages_tokens
per_call = np.array([estimate_messages_tokens(build_messages(req), tool_definitions(req))
for req, _ in runaway.calls])
steps = np.arange(1, len(per_call) + 1)
fig, ax = plt.subplots(figsize=(6.4, 3.2))
ax.bar(steps, per_call, color="#2c5f9e", label="input tokens of this request")
ax.plot(steps, per_call.cumsum(), color="#b5523b", marker="o",
label="total input tokens so far")
ax.set_xlabel("step")
ax.set_ylabel("tokens (estimated)")
ax.set_xticks(steps)
ax.legend(frameon=False, loc="upper left")
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
plt.show()
Estimated input tokens for the runaway loop. Each request is a little longer than the last, so the total grows roughly quadratically with the number of steps.
The bars grow linearly and the running total grows quadratically. With a real model, a long run with large tool outputs gets expensive and slow, and the model’s accuracy drops as the context fills with stale material. Managing what goes into that list is context engineering, the subject of Module 6.
6. The same loop, packaged
agentlab.Agent is this loop with the parts a real system needs: every message, call and
result is recorded as an Event in an ExecutionContext, the stop rule is a method you can
override, and there are hooks for confirmation, memory and guardrails. Module 4 builds it
piece by piece; for now, check that it does the same thing.
from agentlab import Agent
from agentlab.display import show_trajectory
agent = Agent(model=llm, tools=tools, instructions=SYSTEM, max_steps=6)
result = await agent.run("What is the weather in Tokyo in Fahrenheit?")
show_trajectory(result)[user] What is the weather in Tokyo in Fahrenheit?
[agent -> get_weather] {"city": "Tokyo"}
[get_weather ok] Tokyo: 27C, humid
[agent -> celsius_to_fahrenheit] {"celsius": 27.0}
[celsius_to_fahrenheit ok] 80.6
[agent] It is 80.6F in Tokyo right now (Tokyo: 27C, humid).
--- status: complete, steps: 3
Try this
- Add a third tool,
get_forecast(city, days), and ask about tomorrow. Which part of the loop had to change? (None of it should.)- Make
get_weatherraiseValueError("unknown city 'X'; known cities: ...")instead of a bareKeyError, then re-run the Atlantis cell with a live model and compare.- Give
run_loopa second guard that stops when the model repeats the exact same call twice in a row. Is that always a mistake? (Think of polling a job until it finishes.)
Finally, what did this notebook cost? Offline, nothing: the table estimates tokens and prices them at a round reference rate, to show what the same calls would cost against a hosted model.
nb.usage()| model calls | input tokens | output tokens | cost |
|---|---|---|---|
| 20 (fake: 12, scripted: 8) | ≈ 4,994 | ≈ 175 | ≈ USD 0.0057 (reference price) |