CH 02 · The Agent Loop Pattern · 06/15
Read as one pageReal code: the OpenAI Agents SDK caps turns
The OpenAI Agents SDK, a Python library for building agents, owns the loop. Runner.run(agent, input) hands the work to AgentRunner, and that class's while True: loop calls the model and runs the tools. The cap is a parameter of the call, max_turns, defaulting to 10 (DEFAULT_MAX_TURNS in run_config.py). Watch what happens on the turn that crosses the line.
current_turn += 1 # [1]
if max_turns is not None and current_turn > max_turns: # [2]
# ... (7 lines: mark the tracing span "Max turns exceeded")
max_turns_error = MaxTurnsExceeded(f"Max turns ({max_turns}) exceeded")
run_error_data = build_run_error_data( # [3]
input=original_input,
new_items=session_items,
raw_responses=model_responses,
last_agent=current_agent,
reasoning_item_id_policy=resolved_reasoning_item_id_policy,
)
handler_result = await resolve_run_error_handler_result( # [4]
error_handlers=error_handlers,
error_kind="max_turns",
error=max_turns_error,
context_wrapper=context_wrapper,
run_data=run_error_data,
)
if handler_result is None:
raise max_turns_error # [5]
# ... (58 lines: check the handler's output and save it to the session)
result = RunResult(
# ... (3 lines: input, new_items, raw_responses)
final_output=validated_output, # [6]
Source: openai/openai-agents-python, src/agents/run.py (MIT)
What to notice
- [1] This runs once per pass, after any pending input is admitted and before
run_single_turncalls the model. A turn here is one model call plus the tool calls it makes (the docstring ofRunner.runsays so), so the call past the limit is never made or paid for. - [2] Pass
max_turns=Noneand there is no cap. Capped is the default; unlimited is a choice you write down. - [3]
build_run_error_datapacks up what the run produced so far: the input, the new items (messages, tool calls, tool outputs), the raw model responses, and the last agent that ran. That bundle is the handler's input, a snapshot of the run so far.Runner.rundoes not return it: the default path raises, and a handler returns its ownfinal_output. - [4] This looks up your function under
"max_turns"in theerror_handlersdict you passed toRunner.run, and calls it with the error and that snapshot. - [5] With no handler, or one that returns
None, the SDK raisesMaxTurnsExceeded. That differs from the section's advice: out of the box, hitting the cap is an exception your code must catch. - [6] With a handler, the skipped lines check its
final_outputagainst the agent's output type and run the output guardrails (checks on an agent's final answer). If both accept it, the SDK returns a normalRunResult. If the agent expects structured output and the handler's value does not match,validate_handler_final_outputraisesUserError, the SDK's error for bad caller input. A guardrail trip still raisesOutputGuardrailTripwireTriggered.
The shape guards against a runaway bill (the cap is on unless you remove it) and a silent stop (failure is loud unless you write the fallback).
Read it yourself: in docs/running_agents.md, read "Error handlers" for a sample on_max_turns. Then search run_internal/run_loop.py for MaxTurnsExceeded(: the streaming runner repeats this check but does not raise there without a handler. What does it do instead, and where does the error reach the caller? (Hint: _check_errors in result.py.)
Finished this idea?
Your learning progress stays in this browser.