Skip to content
Visual explainer 2h 30m to learn 5 steps

Cap ADK agent steps, time and tool calls

Limit steps, elapsed time and tool calls per run, and show a fallback and human handoff using synthetic timeouts and empty results.

By Invicly Tech, , in Google ADK with Python for AI Agents. About 11 minutes to read.

Topic 12 of 29

In short

An agent that can call tools can also loop, stall or wait forever on a slow system. Bounded execution sets hard limits on each run: how many model calls, how many tool calls, how long it may take and how many failures in a row are allowed. When a limit is hit, the agent gives a safe fallback reply and, when needed, hands the case to a person with enough context to continue.

Think of it like this: It is like a parking meter and a fuse box together: time runs out at a fixed point, and a fault trips the fuse before it burns the house down.

Explained simply

A tool-using agent decides its own next step, so it can also decide badly. It might call the same tool again and again, wait forever on a slow system, or keep asking the model for one more try. Each extra step costs money and time while the user waits.

Bounded execution means every run has limits set in code. At most this many model calls. At most this many tool calls. At most this many seconds. Stop after this many failures in a row. These limits do not depend on the model behaving well.

When a limit is reached, the agent must still say something useful. A good fallback is short and honest: I could not check your ticket right now. It never guesses, and it does not show internal error messages.

Some cases need a person. A handoff records what the user asked, what the agent already checked and why it stopped, so a support person can pick it up without asking the user to repeat everything. In this course the handoff is a dry run: you build the record but do not send it to a real system.

Press Play on a diagram to walk through it one step at a time.

LayersLimits from outside in
  1. 1
    Request deadline

    asyncio.timeout around the whole run

  2. 2
    Model call cap

    RunConfig(max_llm_calls=...)

  3. 3
    Tool call budget

    before_tool_callback with a temp: counter

  4. 4
    Per-step timeout

    Tool timeout or @node(timeout=...)

  5. 5
    Failure counter

    Stop after N errors in a row

FlowWhat happens when a limit trips
  1. 1
    Limit hit

    Deadline, cap, budget or failures

  2. 2
    Stop the run

    Catch the error in your API layer

  3. 3
    Safe reply

    Plain message, no guesses

  4. 4
    Handoff record

    Question, IDs tried, error codes

  5. 5
    Log and measure

    Which limit, how often

SequenceA synthetic timeout ending in a handoff
User
API layer
Agent
Ticket tool
  1. 1Is T-1001 fixed?
    User to API layer: Is T-1001 fixed?
  2. 2run_async with 20 s deadline
    API layer to Agent: run_async with 20 s deadline
  3. 3get_ticket_status(T-1001)
    Agent to Ticket tool: get_ticket_status(T-1001)
  4. 4UPSTREAM_TIMEOUT (twice)
    Ticket tool to Agent: UPSTREAM_TIMEOUT (twice)
  5. 5Stops: failure limit reached
    Agent to API layer: Stops: failure limit reached
  6. 6Fallback reply plus handoff reference
    API layer to User: Fallback reply plus handoff reference

In depth

Model call caps with RunConfig

RunConfig, from google.adk.agents, is passed to runner.run_async for each run. Its max_llm_calls field caps the number of model calls in that run. The default is 500, which suits long research agents, not a support bot. Count what a normal answer needs, for example two to four calls, and set the cap with some headroom, such as six or eight. When a run passes the cap, ADK raises LlmCallsLimitExceededError from google.adk.agents.invocation_context. Your API layer should catch it, log which limit fired, and return the fallback. Setting the value to zero or below removes the cap, which the docs advise against in production. Because the cap applies per run, a new user message starts a fresh count.

  • Default 500: lower it
  • Raises LlmCallsLimitExceededError
  • Per run, resets each message
  • Pair with a tool call budget

Deadlines and per-step timeouts

Set two kinds of time limit. A deadline covers the whole run: wrap the async for loop over runner.run_async in asyncio.timeout(seconds), available from Python 3.11. When it fires, the run is cancelled and you get TimeoutError; events already yielded stay in the session, so the trace shows how far it got. Per-step timeouts protect against one slow dependency: inside tools use asyncio.wait_for, and in Workflow nodes use @node(timeout=...) with an optional RetryConfig. A node timeout raises NodeTimeoutError, and it is retried only if you list NodeTimeoutError in the retry exceptions. The timeout applies to each attempt, so the worst case is roughly attempts times timeout plus backoff delays; make sure that fits inside the request deadline.

CompareTime limits at two levels
Whole-run deadline
  • asyncio.timeout around run_async
  • Raises TimeoutError
  • Covers model and tools
  • Set from your API's response target
Per-step timeout
  • wait_for in tools, @node(timeout=...) in workflows
  • Returns UPSTREAM_TIMEOUT or raises NodeTimeoutError
  • Can be retried with RetryConfig
  • Applies to each attempt separately

Stopping on repeated failures

Retries help with brief glitches but make outages worse. Count consecutive tool errors per run in a temp: state key, in an after_tool_callback that looks at the result's status. Reset the count on success. When it reaches a small number, such as two, make further tool calls return a dict like error_code CIRCUIT_OPEN from your before_tool_callback, and let the instruction tell the agent to apologise and offer a handoff. Empty results deserve the same care: a search that returns no_match twice is a signal to stop searching, not to rephrase forever. Test these paths with fakes that always time out or always return empty, so the fallback is proven before a real outage.

Fallback and human handoff

Keep one fallback message per situation, written by people and stored with your copy, not generated by the model under stress. Then build a handoff record: invocation ID, the user's question, ticket and source IDs already checked, the error codes seen and which limit fired. Leave out tokens, internal URLs and unrelated chat history. In this course, a create_handoff tool returns the record with dry_run true and writes nothing; in production a separate, authorised service would create the support case. Tell the user what happens next in plain words. Measure how often each limit fires, because frequent handoffs point to a tool, timeout or instruction that needs fixing.

  • Human-written fallback text
  • Handoff: IDs, errors, limit, invocation ID
  • No secrets or full history
  • Dry run in this course

Learn it in 5 short steps

About 30m each. Track them with a timer in your plan.

  1. 1
    Set a maximum number of calls~30m
  2. 2
    Add a deadline per run~30m
  3. 3
    Stop on repeated tool failures~30m
  4. 4
    Fall back to a safe reply~30m
  5. 5
    Hand off to a human with context~30m

Key points

  • RunConfig max_llm_calls caps model calls per run; the default is 500, far too high for a support bot, so set it low.
  • When the cap is exceeded ADK raises LlmCallsLimitExceededError, which your server should turn into a fallback reply.
  • Wrap the event loop in asyncio.timeout to set a deadline for the whole run; events already produced stay in the session.
  • In a Workflow, @node(timeout=..., retry_config=RetryConfig(...)) limits each step and raises NodeTimeoutError when time runs out.
  • A human handoff is a record with the user's question, the IDs looked up and the errors seen, created as a dry run in this course.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
import asyncio
from google.adk.agents import RunConfig
from google.adk.agents.invocation_context import LlmCallsLimitExceededError
FALLBACK = "I could not finish checking that. I have passed it to our support team."
async def answer(runner, user_id, session_id, message) -> str:
    final = None
    try:
        async with asyncio.timeout(20):
            async for event in runner.run_async(user_id=user_id, session_id=session_id,
                    new_message=message, run_config=RunConfig(max_llm_calls=6)):
                if event.is_final_response() and event.content:
                    final = event.content.parts[0].text
    except (TimeoutError, LlmCallsLimitExceededError):
        pass  # log which limit fired here
    return final or FALLBACK

A 20-second deadline and a cap of six model calls, with one fallback for both. Needs Python 3.11 or later for asyncio.timeout.

A workflow step with timeout and retry

The ticket lookup node gets two attempts of three seconds each. NodeTimeoutError is listed, so a timeout is retried once; if both attempts time out, the error reaches your API layer, which returns the fallback. jitter=0 makes the delay fixed, which is handy in tests.

python
from google.adk import Context
from google.adk.workflow import NodeTimeoutError, RetryConfig, node

@node(
    timeout=3.0,
    retry_config=RetryConfig(
        max_attempts=2,
        initial_delay=0.5,
        jitter=0,
        exceptions=[NodeTimeoutError],
    ),
)
async def lookup_ticket(node_input: dict, ctx: Context) -> dict:
    return await ticket_store.get(node_input["ticket_id"])

A dry-run handoff tool

The agent calls create_handoff when a limit fires or the user asks for a person. It returns a record and writes nothing. The invocation ID comes from ToolContext, not from the model.

python
from google.adk.tools import ToolContext

def create_handoff(summary: str, ticket_ids: list[str], reason: str,
                   tool_context: ToolContext) -> dict:
    """Prepare a handoff to a human agent. reason: timeout, budget, no_match or user_request."""
    record = {
        "invocation_id": tool_context.invocation_id,
        "summary": summary[:500],
        "ticket_ids": ticket_ids[:5],
        "reason": reason,
    }
    return {"status": "ok", "dry_run": True, "handoff": record}

Quick reference

  • RunConfig(max_llm_calls=6): default is 500, too high for support bots.
  • Over the cap: LlmCallsLimitExceededError from google.adk.agents.invocation_context.
  • Whole-run deadline: async with asyncio.timeout(20) around run_async (Python 3.11+).
  • Workflow step: @node(timeout=3.0, retry_config=RetryConfig(...)).
  • NodeTimeoutError is retried only if listed in RetryConfig exceptions.
  • Count tool failures in temp: state; stop after two in a row.
  • Fallback text is human-written; never show internal errors.
  • Handoff = question, IDs checked, error codes, limit fired, invocation ID.

Common mistakes

  • Leaving max_llm_calls at the default of 500, so a looping agent burns tokens for minutes before anything stops it.
  • Returning a fallback without recording why, so nobody can tell whether timeouts or budgets are the real problem.
  • A handoff that only says the user needs help, forcing the person to ask every question again.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What is the default value of RunConfig max_llm_calls?

Question 2

2A workflow node has timeout=3.0 and RetryConfig(max_attempts=2) without NodeTimeoutError in exceptions. What happens when the first attempt times out?

Question 3

3After asyncio.timeout cancels a run, what remains in the session?

Question 4

4Which item should not go into a handoff record?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Pick limits for the support assistant: max model calls, max tool calls, deadline and failure limit. Justify each in one line.

  2. Exercise 2medium

    Make a fake ticket store that always sleeps 10 seconds, run the agent with a 2-second tool timeout and a 20-second deadline, and confirm the user gets the fallback with a handoff.

  3. Exercise 3hard

    Write a pytest test that proves max_llm_calls stops a looping agent: use a scripted fake model that always requests the same tool, and assert the API layer returns the fallback.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Does ADK have a built-in tool call limit?
The documented run-level cap is max_llm_calls for model calls. For tool calls, count them yourself in a before_tool_callback, as shown in the contract tests topic.
How do I cancel a run in Python?
Cancel the asyncio task or wrap the loop in asyncio.timeout. The ADK cancellation page currently documents the TypeScript abort signal; in Python, standard asyncio cancellation stops the run and keeps the events already produced.
Should the agent retry after a timeout?
Once, at most, for a step that is safe to repeat, such as a read-only lookup. After that, stop and fall back, so a slow system does not get even more traffic.

Go deeper

ShareXLinkedInWhatsApp