Lesson 4 — The agent loop explained
Course: the AI Platform 101 (Course 003) Section: 2 — Teaching your Agent Lesson: 4 of 12 | Lesson ID:
486254Format: Video Estimated time: not stated on the official page Source: Official Skilljar course material (user-provided; requires login) License: Copyright 2026 the AI provider. Released under CC BY-NC-SA 4.0. Note: This is the original English source text, lightly reformatted (headings and paragraph breaks added) for study. No wording has been changed. Counterpart translation: 06-第4课-The-agent-loop-explained.md
Video
The agent loop explained
You've made API calls, but a single call only returns one response. If you want to automate a workflow, the AI needs to act, look at the result, decide what's next, and keep going. That pattern is what people mean when they talk about agentic workflows.
What an agent actually is
An agent is an autonomous version of the AI, running both sides of the messaging loop without a human in the middle. An agent receives a task, picks a tool, and executes code in a loop until the AI decides the task is done.
The easiest way to implement an agent loop looks like this:
- Send a message to the AI with tools available.
- the AI responds with either a final answer or a request to use a tool you defined.
- Your code executes that tool.
- You send the result back to the AI.
- Repeat until the stop reason is
end_turn.
Think of it as a conversation where the turns alternate: the user kicks things off, the agent calls a tool, the tool returns a result, and the agent keeps going until it has an answer.
A minimal working example
To see this loop run end to end without dragging in a database or a UI, we'll wire up a fake tool called get_weather and ask the AI what to wear in Austin today. the AI has no way to know the weather on its own, so it has to call the tool, read the result, and then give you an answer.
Here's the whole script:
import anthropic
client = anthropic.the AI provider()
# The tools array tells the AI what's available:
# a name, a description, and a JSON schema for the inputs.
tools = [
{
"name": "get_weather",
"description": "Get the current weather for a city.",
"input_schema": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "The city to get weather for",
}
},
"required": ["city"],
},
}
]
# run_tool is just a hardcoded lookup.
# In a real app, this would hit your database, an API, whatever.
def run_tool(name, tool_input):
if name == "get_weather":
return f"Weather in {tool_input['city']}: 95F, sunny"
raise ValueError(f"Unknown tool: {name}")
messages = [
{"role": "user", "content": "What should I wear in Austin today?"}
]
# The agent loop. Each iteration sends messages to the AI
# and switches on the response's stop reason.
while True:
response = client.messages.create(
model="current-model-fast",
max_tokens=1024,
tools=tools,
messages=messages,
)
if response.stop_reason == "end_turn":
# the AI is done. Print the final text and break.
for block in response.content:
if block.type == "text":
print(block.text)
break
if response.stop_reason == "tool_use":
# Find the tool use blocks in the response and run each one.
tool_results = []
for block in response.content:
if block.type == "tool_use":
result = run_tool(block.name, block.input)
tool_results.append(
{
"type": "tool_result",
"tool_use_id": block.id,
"content": result,
}
)
# Push the assistant's response and our tool results
# back into messages, then loop again so the AI can answer.
messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": tool_results})
Three pieces to notice
- The tools array tells the AI what's available: a name, a description, and a JSON schema for the inputs.
run_toolis just a hardcoded lookup. In a real app, this would hit your database, an API, whatever.- The loop is the agent loop. Each iteration sends the messages to the AI and switches on the response's stop reason. On
end_turn, the AI is done — print the final text and break. Ontool_use, find the tool use blocks, run each one, push the assistant's response and your tool results back intomessages, and loop again so the AI can answer.
Running it
When you run the script, you'll see two turns:
- Turn one: the stop reason is
tool_use. the AI requestsget_weatherfor Austin, and your code returns the temperature and conditions. - Turn two: the stop reason is
end_turn, and the AI tells you to wear something light and breathable.
Two API calls, one tool execution, one final answer. That's the entire loop. Everything you build with the the AI API is going to be similar to this.
The same loop in production
In a real environment, this same loop powers something like an auto-review endpoint: a compliance agent that reads a structural report, looks up the relevant building codes via a tool, and writes risk findings back to the database one by one as it works.
The shape of the loop is identical to what you just ran. The differences are:
- Real tools instead of a mock weather lookup.
- Results stream back to the UI as server-sent events.
- Findings get persisted to a risk-finding table.
Recap
- An agent is the AI in a loop: observe, decide, act, repeat.
- The loop is simple: send messages with tools, run any tool the AI requests, feed the result back, and stop when the stop reason is
end_turn. - You own the loop and the tools. the AI owns the reasoning.
- The same loop shape scales from a mock weather demo to a production compliance agent — only the tools and plumbing change.
- When you don't want to own the loop, managed agents run this exact loop for you on the AI provider's infrastructure.
⚠️ Notes on this transcript
anthropic.the AI provider()andmodel="current-model-fast"are artifacts of the capture/environment process. Per Lesson 3's mapping,current-model-fastcorresponds to the Sonnet tier (current-model-lite= Haiku,current-model= Opus). Do not memorize these strings.- The course page About describes the loop as "acts, observes, and decides", while this lesson's Recap says "observe, decide, act, repeat". The four-step Recap form is the more complete one; the two are not in conflict about which things happen, only about ordering in prose.
- This lesson does not include a
What you'll learnblock on the official page.