The agent loop
Follow one request through every model call and tool call. The model proposes each call, the runtime runs it, and the loop ends on an answer or a stop condition you set.
Chapter 4Custom agentsLesson 1 of 8ShowHide
Chapter 4 of 7 in Google Cloud Professional Agentic Architect
- The agent loopYou're here
Prerequisites: What makes something an agent
Why the loop matters
You are building a support agent on Google Cloud, and a user asks: "Where is order A1234, and can I still change the delivery address?" No single tool answers that. The agent has to look up the order, use what it finds to look up the shipment, and only then reply. Each of those moves is a trip around the agent loop.
Many of the hardest production problems with agents are properties of that loop: an agent that repeats the same search, a slow tool that stalls every turn, a wrong tool chosen because its description was vague, or a bill that grows with each turn. You cannot debug what you cannot trace, so this lesson follows one request through every step. Along the way you make two design choices: how to describe each tool so the model picks the right one, and where the loop must stop.
One request, step by step
An agent built for starts with a set of : for each tool, a name, a description and a schema of its parameters. Then the loop runs:
- The model is called. It reads the instruction, the declarations and the conversation so far.
- It proposes a call or answers. If it needs data, it returns a function
call, the name of a declared tool plus arguments, such as
get_order_status(order_id="A1234"), and its turn ends there. If it has enough, it returns a final answer instead. - The runtime executes the call. Your code, or an agent framework such as Google's Agent Development Kit (ADK), runs the real function and gets a result.
- The result is appended. The runtime adds the call and its result to the conversation and calls the model again, back to step 1.
The model never runs a tool. In the words of Google's function-calling guide: "The model doesn't execute the function itself. Extract the name and args and execute in your application." That split matters later: whoever executes the call holds the credentials, so permissions belong to the runtime's identity, not to "the model".
Name the four steps of one trip around the agent loop.
Step through it
The simulation runs that order question, and a simpler return-policy question, one step at a time. Each model call row is a proposal; each runtime row is an execution. Start with clear tool descriptions and press Step until the agent answers, counting the model calls. Then switch to vague descriptions and run it again. Finally, set the cap low enough that it fires.
What you should see:
- Two dependent tool calls take three model calls. The shipment lookup needs the tracking id from the order lookup, so one model call proposes each tool call, and one more reads the last result and answers. (Independent calls can be proposed together in one model call, as parallel calls.) Count model calls, not tool calls, when you size a cap.
- Tokens grow every turn. Each model call re-reads the instruction, the declarations and the whole history. Each model row shows how much context it read: the third call reads far more than the first, though it does the same kind of work.
- Vague descriptions cost turns, or the whole run. With tools named
fetch,queryandlookup, the model guesses. For the return policy it finds the right tool on the third try; for the order it keeps callinglookup, which turns out to be the help search, gets the same article back, and never converges. Only the cap ends it. When a run ends, the panel shows which real tool sat behind each vague name.
Tool descriptions are prompts
The declaration is the only thing the model knows about a tool. ADK builds it
from a Python function's name, docstring, parameters and type hints, and its
documentation calls the docstring critical: say what the tool does, when to use
it, what each parameter means and what it returns. Name tools by action and
object (get_order_status, not fetch), and say when not to use one ("not for
a specific order"). A vague declaration is a prompt that invites wrong guesses,
and no model, however large, can know what an undocumented tool does.
def get_order_status(order_id: str) -> dict:
"""Returns the status and tracking id of one customer order.
Use when the user gives an order id. Not for general policy questions.
Args:
order_id: The order id, for example "A1234".
Returns:
{"status": "success", "order_status": ..., "tracking_id": ...}
or {"status": "error", "error_message": ...}.
"""
...Where does an ADK agent's model learn what a Python function tool does and when to call it?
Every loop needs a stop condition
A loop ends in one of three ways:
- A final answer. The model returns text with no function call. This is the normal ending.
- A cap. The runtime refuses to call the model again past a limit, often
called the loop's . Here, as in
ADK, the cap counts model calls; tool executions are not counted. In ADK, pass
RunConfig(max_llm_calls=...)torunner.run_async(); the documented default is 500 model calls per run, a safety net rather than a design. ADK does not stop quietly at the cap: it raises an error (LlmCallsLimitExceededErrorin Python), so catch it and give the user a fallback or an escalation. - An escalation. Your design hands the task to a person or another agent instead of continuing, for example after the same tool fails twice.
from google.adk.agents.run_config import RunConfig
# runner: the ADK Runner for your agent (see the ADK lesson); the ids name the user and session (see Sessions, state and Memory Bank).
# The longest legitimate path is about 4 model calls; allow headroom, not 500.
config = RunConfig(max_llm_calls=8)
async for event in runner.run_async(
user_id=user_id, session_id=session_id, new_message=message, run_config=config
):
...When no stop condition fires in time, the symptom is distinctive: the same tool called again and again with near-identical arguments, the same result coming back, latency and token use climbing on every turn, and no answer. In a trace, the record of every model and tool call in a run (Observing and troubleshooting agents reads them), it shows as the same call repeated with the same result.
Size a cap from the task's longest legitimate path, plus headroom. Set it too high and a stuck agent burns hundreds of calls before it stops; set it too low and you cut healthy runs short, as a cap of 2 does to the two-lookup order question in the simulation. A cap limits the damage; it does not fix the cause. When an agent hits its cap, look at why it was not converging: usually a vague tool, a tool that returns errors the model cannot act on, or an instruction that never says when the task is done.
Sources
Show 6 sourcesHide sources
| Source | Publisher | What it supports |
|---|---|---|
| Function calling (opens in a new tab) | Google, Gemini API documentation | declarations; the model does not execute the function, your application does; multiple turns; parallel and compositional calls |
| Custom tools (opens in a new tab) | Google, Agent Development Kit documentation | how agents use tools; defining effective tool functions: names, docstrings, return values |
| Function tools (opens in a new tab) | Google, Agent Development Kit documentation | the schema is generated from the function's name, docstring, parameters and type hints |
| Runtime configuration (opens in a new tab) | Google, Agent Development Kit documentation | max_llm_calls, default 500 per run |
| Runtime event loop (opens in a new tab) | Google, Agent Development Kit documentation | the Runner orchestrates agents, tools and callbacks |
| ReAct: Synergizing Reasoning and Acting in Language Models (opens in a new tab) | Yao et al. (2022) |
Suggested videos
Show 2 videosHide videos
Function calling with the Gemini API (opens YouTube in a new tab)
Shows the model proposing a function call and the app executing it and returning the result: one turn of the agent loop.
Note: At the Gemini API level: no ADK runner or stop conditions.
AI agents explained: Build your first agent in 8 minutes (opens YouTube in a new tab)
Explains the reason-act-observe loop and shows a loop with a validation check, matching the lesson's 'loop ends on an answer or a stop condition'.
Review
In function calling, who executes the tool?
Check yourself
A colleague says: 'Once we declare get_invoice, Gemini will call our billing API whenever it needs an invoice.' What actually happens when the model decides it needs one?