entry
No. 18
date

updated
filed under
debugging, agents, tool use
checked against
7 sources

MaxTurnsExceeded in OpenAI Agents SDK: When to Raise max_turns

The OpenAI Agents SDK raises MaxTurnsExceeded when a run makes more model calls than max_turns allows without producing a final output. The message is short: agents.exceptions.MaxTurnsExceeded: Max turns (10) exceeded, where the number is the limit in force. The default is 10. Before you raise it, check whether the agent was making progress. If the last few turns repeat the same tool call, a bigger limit only makes the failure slower and more expensive. Fix the loop first, then set a limit that fits the task on purpose.

This post covers what a turn is, how to read the exception to find the loop, the common causes, and four fixes: a fallback answer through error_handlers, stopping on a tool, resuming with a fresh budget, and setting the limit for nested agents. Every snippet was run on Python 3.13 with openai-agents 0.25.0 and a scripted fake model, so none of it needs an API key.

What counts as a turn

The Running agents docs describe the loop. The runner calls the model for the current agent. If the output is a final output, the loop ends. If the model asks for a handoff, the runner switches agents and runs the loop again. If it asks for tools, the runner runs them, appends the results and runs the loop again. A final output, in the docs' words, is text "with the desired type" and "there are no tool calls."

max_turns caps how many times that loop calls a model. We checked three cases with the fake model:

  • One model call is one turn. An agent that called a tool three times and then answered needed max_turns=4. With max_turns=3 it raised Max turns (3) exceeded after three model calls.
  • Parallel tool calls share a turn. A response that asked for two tool calls at once, followed by an answer, finished within max_turns=2.
  • A handoff costs a turn. A triage agent that handed off to a billing agent, which then answered, raised at max_turns=1 and finished at 2. The count carries across agents; it is not reset by a handoff.

In openai-agents 0.25.0, DEFAULT_MAX_TURNS = 10 in run_config.py, and every Runner method takes max_turns. The docs say to "Pass max_turns=None to disable this turn limit." With streaming, the exception surfaces from stream_events(), which the SDK's docstring says will raise "A MaxTurnsExceeded exception if the agent exceeds the max_turns limit."

Read the exception to find the loop

MaxTurnsExceeded is a subclass of AgentsException, which carries a run_data attribute of type RunErrorDetails. It holds the run's input, the new_items it produced, the raw_responses from each model call and the last_agent that was running. That is enough to see what the agent was doing when it ran out:

from collections import Counter

from agents import Agent, MaxTurnsExceeded, Runner, function_tool


@function_tool
def search_orders(customer_id: str) -> str:
    """Search a customer's orders."""
    return "no orders found"


def summarize_loop(error: MaxTurnsExceeded) -> None:
    """Print which tool calls repeated before the turn limit."""
    data = error.run_data
    calls = Counter(
        (item.raw_item.name, item.raw_item.arguments)
        for item in data.new_items
        if item.type == "tool_call_item"
    )
    print(f"{error} | last agent: {data.last_agent.name} | model calls: {len(data.raw_responses)}")
    for (name, args), n in calls.most_common(3):
        print(f"  {n}x {name}({args})")


agent = Agent(name="Support", tools=[search_orders])
try:
    Runner.run_sync(agent, "Why was I charged twice?")
except MaxTurnsExceeded as e:
    summarize_loop(e)

With a fake model that asks for search_orders on every turn, the output names the loop at once:

Max turns (10) exceeded | last agent: Support | model calls: 10
  10x search_orders({"customer_id": "c1"})

One call repeated ten times with the same arguments is a loop. Ten different calls that each return something new is a task that needs more turns. That distinction decides the fix. In a trace, the same pattern shows as repeated tool spans (agent observability tracing).

Common causes

  • A tool result the model can't act on. Here search_orders returns "no orders found" and nothing about what to try next, so the model searches again. Say what went wrong and what to do, such as "No orders for customer c1. Ask the user for the email on the account." Why your agent calls the wrong tool and agent tool retries cover error text that helps the model change course.
  • Forced tool use that never resets. ModelSettings(tool_choice="required") makes the model call a tool on every turn. The Agents docs note that the SDK resets tool_choice to "auto" after a tool call to avoid this, and Agent.reset_tool_choice (default True) controls it. Setting it to False with a forced tool choice can leave the agent no way to answer.
  • A structured output the model can't produce. In GitHub issue 1414, an agent with output_type set, running gpt-oss:20b through Ollama, ended with MaxTurnsExceeded: Max turns (10) exceeded, and the same script without output_type completed. A maintainer concluded that "an Agent's non-text outputType does not work with the gpt-oss model" and suggested the default text output for now. If a run only loops with output_type, test the model's structured output on its own first.
  • Handoffs that bounce. Two agents that each hand off to the other spend a turn per handoff. Check last_agent and the handoff items in new_items, and test routing directly as in multi agent evaluation.
  • A task with no finish line. "Research this" can go on forever. Say what done looks like, as covered in debugging agents that never stop.

Fix 1: Return a fallback answer with error_handlers

When a run can legitimately run out of turns, you may want the caller to get an answer instead of an exception. The docs say every Runner entry point accepts error_handlers, "a dict keyed by error kind," for returning "a controlled final output instead of ending the run with the corresponding error." The max_turns handler receives a RunErrorHandlerInput with the error and the run data:

from agents import Agent, RunErrorHandlerInput, RunErrorHandlerResult, Runner


def on_max_turns(data: RunErrorHandlerInput[None]) -> RunErrorHandlerResult:
    calls = [i for i in data.run_data.new_items if i.type == "tool_call_item"]
    print(f"{data.error} after {len(calls)} tool calls by {data.run_data.last_agent.name}")
    return RunErrorHandlerResult(
        final_output="I couldn't finish within the step limit. A support agent will follow up.",
        include_in_history=False,
    )


agent = Agent(name="Support", tools=[search_orders])
result = Runner.run_sync(
    agent,
    "Why was I charged twice?",
    max_turns=4,
    error_handlers={"max_turns": on_max_turns},
)
print(result.final_output)

With the looping fake model this printed Max turns (4) exceeded after 4 tool calls by Support and returned the fallback as result.final_output, with no exception. include_in_history defaults to True, which the docs say appends the fallback to the conversation history and persists it to the configured session. Set it to False when the fallback is for the caller only. Log the run data in the handler, or the fallback hides every loop.

Fix 2: Stop on the tool that produces the answer

Some agents loop because the tool already gives the answer and the model keeps going. tool_use_behavior ends the run on a tool call. The docs list "stop_on_first_tool", which uses the first tool's output "as the final response, without further LLM processing," and StopAtTools, which "Stops if any specified tool is called":

from agents import Agent, Runner, StopAtTools, function_tool


@function_tool
def lookup_order(order_id: str) -> str:
    """Look up one order."""
    return "order 42: charged twice, refund pending"


agent = Agent(
    name="Support",
    tools=[lookup_order],
    tool_use_behavior=StopAtTools(stop_at_tool_names=["lookup_order"]),
)
result = Runner.run_sync(agent, "What happened with order 42?")
print(result.final_output)  # order 42: charged twice, refund pending

The fake model that calls lookup_order on every turn was called once. Use this only when the tool's output is fit to show as is.

Fix 3: Resume with a fresh budget

If the run was making progress, you don't have to start over. Rebuild the history from run_data and run again from the last agent with a new limit:

from agents import ItemHelpers, MaxTurnsExceeded, Runner

try:
    result = Runner.run_sync(agent, "Why was I charged twice?", max_turns=3)
except MaxTurnsExceeded as e:
    data = e.run_data
    history = ItemHelpers.input_to_new_input_list(data.input) + [
        item.to_input_item() for item in data.new_items
    ]
    result = Runner.run_sync(data.last_agent, history, max_turns=5)
print(result.final_output)

With a fake model scripted to search five times and then answer, the first run stopped after three calls, the history held seven items (the question plus three call and result pairs), and the second run finished on its third call with the answer. This is the same pattern as result.to_input_list() in the docs' manual conversation example. Put a cap on how many times you resume, or you have rebuilt max_turns=None by hand. If you use a session or server-managed conversation instead of client-side history, follow the docs' warning not to mix the two, since that "can duplicate context."

Fix 4: Set the limit on purpose, including nested agents

When the runs that hit the limit are healthy, measure a normal run's turns (len(result.raw_responses)), add room for a few retries and pass that as max_turns. Ten is low for agents that browse or edit code and high for a single lookup.

Agents used as tools need their own limit. (If you are still deciding between a tool-agent and a handoff, see handoffs vs agents as tools.) In GitHub issue 497, a user asked how to set max_turns for agents passed through as_tool(), and the maintainer's workaround was to wrap the sub-agent in a @function_tool that calls Runner.run(..., max_turns=50). In 0.25.0, as_tool takes max_turns directly, and the Tools docs list it among the runtime options it supports. Passing None there falls back to the default of 10 in the source, so it does not disable the limit.

The nested limit fails quietly. In our run, a researcher sub-agent that looped hit its own limit after 10 calls, or 25 with as_tool(max_turns=25), and the orchestrator got the tool output "An error occurred while running the tool." and carried on to its own answer. No exception reached the caller. as_tool also takes a failure_error_function, the same hook the Tools docs describe for function tools, so the parent can see why the tool failed:

from agents import RunContextWrapper


def explain_failure(ctx: RunContextWrapper, error: Exception) -> str:
    return f"research failed: {error}. Answer with what you have or ask the user to narrow the question."


research = researcher.as_tool(
    tool_name="research",
    tool_description="Research a question.",
    max_turns=25,
    failure_error_function=explain_failure,
)
orchestrator = Agent(name="Orchestrator", tools=[research])

The orchestrator then received "research failed: Max turns (25) exceeded. Answer with what you have or ask the user to narrow the question."

Checklist

  • Read the number in the error. 10 is the default.
  • Count repeated tool calls in e.run_data.new_items before raising the limit.
  • Make tool results say what to try next.
  • Leave reset_tool_choice on when you force tool use.
  • Test output_type with your model on its own if loops only happen with it.
  • Use error_handlers={"max_turns": ...} for a fallback, and log the run data.
  • Use StopAtTools when a tool's output is the answer.
  • Resume from run_data with a cap on resumes.
  • Set max_turns and failure_error_function on as_tool for sub-agents.
  • Save every limit hit as an eval case, as in the agent evals starter guide.

FAQ

What is the default max_turns in the OpenAI Agents SDK?

  1. In openai-agents 0.25.0, DEFAULT_MAX_TURNS = 10. Pass max_turns to Runner.run, run_sync or run_streamed to change it, or None to disable it.

Does a handoff or a tool call count as a turn?

A turn is one model call. Parallel tool calls in one response share a turn, and a handoff followed by an answer needs two.

How do I get the conversation after MaxTurnsExceeded?

Read e.run_data. It has the original input, the new_items produced so far, the raw_responses and the last_agent. Convert new_items with to_input_item() to continue the run.

How do I return a message instead of raising MaxTurnsExceeded?

Pass error_handlers={"max_turns": handler} to the runner. The handler returns a RunErrorHandlerResult whose final_output becomes the run's result.

How is this different from LangGraph's GraphRecursionError?

Both cap a runaway loop, but LangGraph counts super-steps, not model calls, and its defaults are far higher. See LangGraph GraphRecursionError.

Sources

Stuck on a different message? The error index lists every agent error covered here, by tool.

Next in the notebook

  1. No. 2AI Agent Calling the Wrong Tool? 7 Causes and How to Fix Them

    A debugging checklist for tool-calling agents: overlapping tools, vague descriptions, ambiguous parameters, noisy output and bad errors, with a fix for each.

  2. No. 7Agent Infinite Loop: How to Debug Agents That Never Stop

    Why AI agents get stuck in infinite loops, and how to stop them: turn caps, token budgets, repeated-call detection, better tool errors and clear stop rules.

  3. No. 11Agent Observability Tracing: What to Log on Every Step

    Trace an AI agent with OpenTelemetry: one span per run, model call and tool call, which gen_ai attributes to record, and how to keep prompts out of traces.