Write an AI Agent Loop in 60 Lines of Python, No Framework
The problem: a single LLM call cannot look anything up
In lesson 1 the model answered from whatever it learned in training. Ask it about the weather in Kyoto next week and it has two choices: guess, or say it does not know. Neither helps a traveller.
What you want is a model that can say "I need the forecast for Kyoto", have your code fetch it, read the result, and then answer. And if the answer needs two lookups, or three, it should keep going until it has what it needs.
That repeat until done pattern is the agent loop. Agent frameworks wrap it in classes and callbacks, but the loop itself is short. In this lesson you will write it in about 60 lines of plain Python, run it, and see exactly where it can go wrong. The LLM Fundamentals course explains the loop as a concept; here you build it.
The loop in one sentence
Send the conversation and a list of tools to the model; if the reply asks for tools, run them, add the results to the conversation, and send it again; if the reply asks for nothing, that reply is the answer.
That is the whole idea. Everything else in this course (memory, planning, safety, testing) is about making this loop behave well.
flowchart TD S["messages = system + user"] --> L{"step <= max_steps?"} L -->|no| STOP["Stopped: reached the step limit"] L -->|yes| CALL["Call the model with tools=TOOLS"] CALL --> AP["Append the assistant turn"] AP --> TC{"Any tool_calls?"} TC -->|no| DONE["Return msg.content: the answer"] TC -->|yes| RUN["Run every requested tool"] RUN --> TM["Append tool message<br/>with matching tool_call_id"] TM --> L
Diagram: run_agent as a flowchart: call, append, run tools, send results back, stop at no tool calls or max_steps.
The full agent
Save this as agent_loop.py next to the llm.py file from lesson 1:
python# file: agent_loop.py import json from llm import client, MODEL # Made-up data for the course. Not real forecasts. FAKE_WEATHER = { "lisbon": {"forecast": "sunny", "high_c": 22, "low_c": 14}, "kyoto": {"forecast": "light rain", "high_c": 17, "low_c": 9}, "oslo": {"forecast": "cloudy", "high_c": 6, "low_c": -1}, } def get_weather(city: str) -> dict: data = FAKE_WEATHER.get(city.strip().lower()) if data is None: return {"error": f"No forecast for {city}. Known cities: Lisbon, Kyoto, Oslo."} return {"city": city, **data} TOOLS = [{ "type": "function", "function": { "name": "get_weather", "description": "Get the 3 day weather forecast for a city.", "parameters": { "type": "object", "properties": {"city": {"type": "string", "description": "City name, e.g. Lisbon"}}, "required": ["city"], }, }, }] FUNCTIONS = {"get_weather": get_weather} def run_agent(user_text: str, max_steps: int = 5) -> str: messages = [ {"role": "system", "content": "You are a trip helper. Use tools for facts. Be brief."}, {"role": "user", "content": user_text}, ] for step in range(1, max_steps + 1): response = client.chat.completions.create( model=MODEL, messages=messages, tools=TOOLS, temperature=0 ) msg = response.choices[0].message messages.append(msg) # the assistant turn, including any tool calls if not msg.tool_calls: # no tool requested: this is the final answer return msg.content for call in msg.tool_calls: # run every requested tool args = json.loads(call.function.arguments or "{}") result = FUNCTIONS[call.function.name](**args) print(f" step {step}: {call.function.name}({args}) -> {result}") messages.append({ "role": "tool", "tool_call_id": call.id, "content": json.dumps(result), }) return "Stopped: reached the step limit before finishing." if __name__ == "__main__": print(run_agent("Should I pack an umbrella for Kyoto?"))
Run it with python agent_loop.py. With qwen2.5:1.5b on Ollama, the tested run printed one tool call, get_weather({'city': 'Kyoto'}), followed by an answer based on the result. The rest of this lesson walks through the code from top to bottom.
Part 1: a normal Python function
get_weather is ordinary Python. It reads from a dictionary of made-up forecasts. In a real agent it could call a weather API, query a database or read a file. The model never sees this code. It only sees the description you give it.
Notice that an unknown city returns a dictionary with an error key instead of raising an exception. That choice matters: an exception would crash the loop, while an error result is something the model can read and react to. Lesson 4 is built around that idea.
Part 2: describing the tool
TOOLS is the part the model does see. Each entry has a type of function and a function object with:
name: what the model writes when it wants this tooldescription: plain language that tells the model when to use itparameters: a JSON Schema describing the arguments
This format follows the chat completions function calling format in the OpenAI API, and Ollama accepts the same format on its compatible endpoint. Lesson 3 goes deeper into the schema.
FUNCTIONS maps each tool name to the Python function that implements it. When the model asks for get_weather, the loop looks up the real function by that name.
Part 3: the messages list
pythonmessages = [ {"role": "system", "content": "You are a trip helper. Use tools for facts. Be brief."}, {"role": "user", "content": user_text}, ]
This is the same list you built in lesson 1. The system message gives one rule that matters a lot for agents: use tools for facts. Without it, small models in particular often answer from memory instead of calling the tool.
Part 4: the loop and its exit
pythonfor step in range(1, max_steps + 1):
A for loop with a limit, not while True. If the model keeps calling tools forever (it happens, especially when a tool keeps failing), the loop still ends. The function then returns a clear message instead of hanging. Lesson 11 replaces this simple limit with full budgets for steps, tokens and cost.
Inside the loop, the call looks like lesson 1 with one addition: tools=TOOLS. Then comes the most important line:
pythonmessages.append(msg)
The assistant's reply goes into the history before anything else happens, even when it contains no text. If the model asked for a tool, that request is part of the conversation. The API needs to see it on the next call, otherwise the tool results that follow would answer a question nobody asked.
Part 5: deciding whether the agent is done
pythonif not msg.tool_calls: return msg.content
The model signals that it is finished by not asking for any tool. There is no special "done" token you have to invent. If tool_calls is empty or missing, content holds the final answer.
Part 6: running the tools
pythonfor call in msg.tool_calls: args = json.loads(call.function.arguments or "{}") result = FUNCTIONS[call.function.name](**args)
Each tool call has:
call.id: a unique id for this requestcall.function.name: which toolcall.function.arguments: the arguments as a JSON string, not a dictionary
You parse the string with json.loads, find the Python function by name, and call it with the arguments as keyword arguments.
The model can ask for several tools in one reply, so the code loops over all of them. You will see that happen in lesson 3 when comparing two cities.
Part 7: sending the results back
pythonmessages.append({ "role": "tool", "tool_call_id": call.id, "content": json.dumps(result), })
A tool message carries the result. Its tool_call_id must match the id of the request it answers. Content must be a string, so the result dictionary is turned into JSON text.
Then the loop goes around again. The model now sees: the system rules, the user question, its own request for the forecast, and the forecast. With that, it can answer.
What the conversation looks like after one tool call
By the time the model writes its answer, the messages list holds four entries:
| # | Role | Content |
|---|---|---|
| 1 | system | You are a trip helper... |
| 2 | user | Should I pack an umbrella for Kyoto? |
| 3 | assistant | (no text) tool call get_weather with {"city": "Kyoto"} |
| 4 | tool | {"city": "Kyoto", "forecast": "light rain", ...} |
The fifth message, the final answer, comes back from the API. Printing this list is the single best debugging habit you can build. Lesson 15 turns it into proper tracing.
Animation: One pass of the loop: the model asks for get_weather, your code runs it, the result goes back, and a reply with no tool calls ends the loop.
An honest look at the output
In the tested run the tool call was correct, and the result said "light rain". Yet the small model's answer said an umbrella seemed unlikely to be needed. The loop worked perfectly; the model's reasoning about the result did not.
This is worth seeing early. The agent loop guarantees that facts reach the model. It does not guarantee the model uses them well. Things that help, all covered later in the course:
- clearer tool results, for example adding
"rain_chance": 0.7instead of only a text summary (lesson 4 does this) - a larger model, which is a one line change in
llm.py - tests that catch wrong answers automatically (lesson 14)
Run the script a few times. With temperature=0 the result is usually the same, but small changes in the question can change the answer.
Why no framework
Anthropic's guide "Building effective agents" recommends that developers start by using LLM APIs directly, because many patterns take only a few lines of code, and frameworks can hide the prompts and responses that you need to see when debugging. The 60 lines above are the whole mechanism. When something goes wrong, you can print messages and see exactly what the model saw.
Frameworks do add value later: streaming helpers, integrations, hosted tracing. But you will use them better once you know what they do underneath.
Common mistakes in agent loops
- Not appending the assistant message before the tool messages. The API expects each tool result to follow the assistant turn that requested it.
- Mismatched ids. Every
tool_call_idmust match acall.idfrom the previous assistant turn. - Passing a dict as tool content. Content should be a string. Use
json.dumps. - No step limit. A
while Trueloop with a confused model can run until you notice the bill. - Letting a tool exception crash the loop. Catch it and return an error result instead (lesson 4).
What to try next
- Ask "What's the weather in Paris?" and watch the error result come back. Does the model explain that Paris is not available?
- Ask "Should I pack a coat for Oslo or Lisbon?" and count how many tool calls happen.
- Set
max_steps=1and see what happens when the agent is not allowed to finish. - Print
messagesat the end ofrun_agentto see the full conversation.
Next, you will look closely at the tool definition itself: how to write the JSON Schema, how arguments come back, and how to generate schemas from Python functions so you do not write them by hand.
Sources
Write the loop that runs tools until the model answers
An agent is a loop: ask the model, run any tool it asks for, send the result back, and stop when it answers without tool calls.
Write run_loop(model, tools, messages, max_steps=5).
- model(messages) returns a dict: {"content": str or None, "tool_calls": list}. Each tool call is {"id": str, "name": str, "arguments": a JSON string}.
- tools maps a tool name to a Python function.
Each step: call model, append {"role": "assistant", "content": ..., "tool_calls": ...} to messages. If there are no tool calls, return the content. Otherwise run every call with the parsed arguments and append {"role": "tool", "tool_call_id": id, "content": str(result)} for each one.
If the model is still asking for tools after max_steps calls, return None. A loop with no limit can run forever.
The worked solution unlocks after your first attempt.
Check what you learned
Answer all 3 questions. You need at least 2 right to pass.
1. How does the model signal that the agent loop is finished?
2. What must a tool result message include so the model can match it to its request?
3. Why does the loop use for step in range(max_steps) instead of while True?