Pydantic AI raises UnexpectedModelBehavior with the message Exceeded maximum output retries (1) when a run uses up its output retry budget, which defaults to 1. Three things spend that budget: output that fails validation against output_type, a ModelRetry raised by an output validator, and a response with no usable output. Before 1.92.0 (May 8, 2026) the same error read Exceeded maximum retries (1) for output validation. Agents run in tool mode by default, Ollama and vLLM included, so a small local model that answers in plain text instead of calling the final_result tool gets one reminder and then the run fails. Switch to NativeOutput on self-hosted Ollama or vLLM, or PromptedOutput on any model including Ollama Cloud, before raising retries={'output': N}. Raising only ToolOutput(max_retries=N) does not help in that case, because a plain-text reply is charged to the run-level budget. Start by wrapping the failing run in capture_run_messages() and reading the retry cause on the last feedback part.
pydantic_ai.exceptions.UnexpectedModelBehavior: Exceeded maximum output retries (1) means your agent run spent its output retry budget, which defaults to 1, and Pydantic AI stopped instead of asking the model a third time. The budget is spent by any mix of three things: output that fails validation against output_type, a ModelRetry raised in an output validator, and a response with no usable output at all. On a small model behind Ollama or vLLM the third is the one to suspect first: the agent is in tool mode by default, the model replies in prose instead of calling the output tool, gets one reminder, and the run ends. Change the output mode to NativeOutput or PromptedOutput before you touch the retry count.
Before 1.92.0, released May 8, 2026, the same error read Exceeded maximum retries (1) for output validation. Pydantic AI's issue tracker has dozens of reports carrying one wording or the other, and the error stays a plain UnexpectedModelBehavior with nothing appended: a maintainer agreed on October 31, 2026 to add a hint pointing at the output modes, and that issue is still open.
Everything below was read from the pydantic-ai-slim source at tag v2.75.0 (uploaded to PyPI on November 25, 2026, the latest release), at v1.107.11 for the 1.x maintenance line, and at older tags for the wording history. Nothing here comes from a test run. For where this agent framework fits among the alternatives, see the AI agents pillar.
What Exceeded maximum output retries means
Pydantic AI keeps two retry budgets per run: one for function tools and one for output. Both default to 1. The output budget counts how many times the framework has sent the model back to fix its final answer, and the error fires when one more correction would exceed it.
Three events spend a unit of the output budget:
The message is raised from four places at 2.75.0. One is the text path in consume_output_retry, which handles missing output and validator retries against the run-level budget. Two are in _run_output_tool_call, the output-tool path, where the number in parentheses is that output tool's own limit: when the tool exhausts its retries, the inner Tool 'final_result' exceeded max retries count of N error is replaced with the bare output message, and the inner error's own cause (the validation failure or ModelRetry) is chained instead. The fourth is new in 2.75.0 and belongs to RunContext.submit_output(), which lets a tool submit the final output; a rejected submission from inside a tool also uses one output retry.
What it is not
Several neighbouring failures look similar and need different fixes:
- A function tool ran out of retries. That reads
Tool 'my_tool' exceeded max retries count of 1. Consider raising the retry limit...and is fixed with@agent.tool(retries=N)orretries={'tools': N}. - The answer was cut off. If the last response has
finish_reason'length'and ends in a tool call whose arguments do not parse as JSON, the run raisesIncompleteToolCallin place of the budget message. Cut-off JSON fromNativeOutputorPromptedOutputraisesOutputTokenLimitExceededinstead of retrying. Both subclassUnexpectedModelBehaviorbut carry different messages, and the fix is a largermax_tokens, not more retries. - The provider sent nothing. A stream that ends before its first event raises
ModelEmptyResponseErrorwithout spending the output budget.
| What happened | What the model is told | What e.__cause__ holds |
|---|---|---|
The final answer did not validate against output_type | The validation errors, fenced in <pyai:validation_errors> | The validation failure behind the last attempt |
Your output validator or output function raised ModelRetry | Your ModelRetry message, fenced in <pyai:retry_feedback> | The ModelRetry on the output-tool path; on the text path, a ToolRetryError chained to it |
| The response had no usable output (for example text when an output tool was expected) | "Please include your response in a tool call." | The retry raised for the missing output |
Find which failure you have before changing anything
The three triggers need three different fixes, so read the run before you edit the agent. capture_run_messages() records every request and response, and the exception chains the last rejected attempt as its cause:
from pydantic_ai import ModelResponse, UnexpectedModelBehavior, capture_run_messages
from pydantic_ai.messages import is_retry
with capture_run_messages() as messages:
try:
result = agent.run_sync(prompt)
except UnexpectedModelBehavior as e:
print(e) # Exceeded maximum output retries (1)
print(repr(e.__cause__)) # what the last rejected attempt raised
for message in messages:
if isinstance(message, ModelResponse):
print('model:', message.finish_reason, [type(p).__name__ for p in message.parts])
for part in message.parts:
if is_retry(part):
cause = part.retry.cause if part.retry else None
print('retry:', type(part).__name__, cause, part.content)
raiseRead the output against this table:
Since 2.70.0 the exception also carries e.conversation, the failed run's conversation, which is the thing to persist if you want to replay the failure later. Store it where the rest of your sensitive data lives, because it contains the model's raw answers.
Two server-side checks belong in this step on local stacks. On Ollama, a prompt longer than num_ctx is truncated from the front without an error, which can drop the instructions that told the model about the output tool; the Ollama num_ctx truncation guide covers how to spot it. On vLLM with a reasoning parser, a tool call can end up in reasoning_content, and Pydantic AI then sees a response with no tool call; see empty tool_calls with reasoning_content in vLLM.
| What you see | Diagnosis | Fix |
|---|---|---|
Responses with only TextPart, then retry cause no_output | The model answered in prose instead of calling the output tool | Change the output mode |
Retry cause validation_error | The model produced output, but it does not match the schema | Simplify the schema, switch to NativeOutput, then raise the budget |
Retry cause model_retry | Your own validator rejected the answer | Check the validator's rule and message, then the budget |
finish_reason 'length' on the last response | Token limit, not validation | Raise max_tokens |
An empty or thinking-only final response, then no_output | The model had nothing to say | Allow None if that is a legitimate answer |
Small local models answer in text: switch the output mode
Pydantic AI's default structured output mode is 'tool', set in the base model profile. At 2.75.0 neither the Ollama nor the vLLM provider profile changes it. So an agent with output_type=ClaimSummary on a local model registers a final_result tool and waits for the model to call it. Pydantic AI's own troubleshooting page names small and local models answering in text as the typical cause of this error. When that happens, the framework replies "Please include your response in a tool call.", and with a budget of 1 the second text reply ends the run.
Retrying the same request does not teach a model to call tools. Changing what you ask for does. The per-server profile details (strict tool definitions, thinking fields, which token limit is sent) are covered in the Pydantic AI vs LangGraph comparison; here only the output mode matters.
from pydantic import BaseModel
from pydantic_ai import Agent, NativeOutput
from pydantic_ai.models.ollama import OllamaModel
from pydantic_ai.providers.ollama import OllamaProvider
class ClaimSummary(BaseModel):
policy_number: str
incident_date: str
covered: bool
model = OllamaModel('qwen3', provider=OllamaProvider(base_url='http://localhost:11434/v1'))
agent = Agent(model, output_type=NativeOutput(ClaimSummary))from pydantic_ai import Agent, NativeOutput
from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.providers.vllm import VLLMProvider
model = OpenAIChatModel(
'Qwen/Qwen3.8-27B',
provider=VLLMProvider(base_url='http://localhost:8000/v1'),
)
agent = Agent(model, output_type=NativeOutput(ClaimSummary))from pydantic_ai import Agent, PromptedOutput agent = Agent(model, output_type=PromptedOutput(ClaimSummary))
All three still validate the result against your type, and a failed validation still spends the output budget.
Which to try first follows from where the schema is enforced. On a server that constrains decoding, NativeOutput moves the problem from the model's judgment to the grammar, so a prose reply stops being a possible output. PromptedOutput leaves the model free to write anything, but there is no tool call to miss: the text itself is parsed as the result, so a bad answer comes back as a validation_error you can read instead of a no_output reminder the model ignores. Keep ToolOutput when the same model already calls your function tools reliably, because the output tool is then one more tool it handles the same way.
Self-hosted Ollama: NativeOutput
NativeOutput sends your schema as the provider's JSON schema parameter instead of as a tool. Pydantic AI's Ollama model docstring says self-hosted Ollama 0.5.0 and later enforces that schema through llama.cpp grammar decoding, so the model's output is constrained to valid JSON for your type rather than asked for politely: This needs pydantic-ai-slim[openai], since the Ollama model rides the OpenAI-compatible client. OllamaProvider falls back to the OLLAMA_BASE_URL environment variable when base_url is omitted, and raises UserError if neither is set.
vLLM: NativeOutput through VLLMProvider
vLLM is reached through OpenAIChatModel with VLLMProvider. Its profile supports JSON schema output, and Pydantic AI also writes the schema into the instructions for vLLM, because guided decoding masks tokens without telling the model what structure it is filling: Use the model name your vLLM server actually serves. Whether vLLM enforces the schema it receives is a server question, with its own failure modes (HTTP 200 with free text, reasoning parsers bypassing the grammar); vLLM structured output not working walks through them. If you stay in tool mode on vLLM instead, the server needs --enable-auto-tool-choice and a --tool-call-parser for the model family.
Any model, including Ollama Cloud: PromptedOutput
PromptedOutput puts the schema in the instructions and turns on JSON mode where the API supports it. The Pydantic AI documentation calls it often the least reliable of the three, because nothing forces the model to match the schema, but it is the one mode every model can attempt: It is the right choice on Ollama Cloud. At 2.75.0, OllamaModel turns off JSON schema support when the host is ollama.com or a subdomain, or when the model name ends in -cloud, because Cloud accepts json_schema without enforcing it. NativeOutput there raises UserError: Native structured output is not supported by this model. The source notes that ToolOutput and PromptedOutput both work on Cloud.
| Output mode | How the schema reaches the model | Self-hosted Ollama 0.5.0+ | vLLM | Ollama Cloud |
|---|---|---|---|---|
ToolOutput (default) | As a final_result tool the model must call | Depends on the model's tool calling | Needs auto tool choice and a parser | Works |
NativeOutput | Provider JSON schema parameter, constrained decoding | Enforced by grammar | Enforced by guided decoding, schema also in instructions | Raises UserError |
PromptedOutput | In the instructions, JSON mode where supported | Works, not enforced | Works, not enforced | Works |
When an empty answer is valid: allow None
Some runs legitimately have nothing to return: no matching record, no clause of the requested type in the document. If your output_type allows None, an empty, blank or thinking-only final response becomes a valid None result instead of a no_output retry:
from pydantic_ai import Agent agent = Agent(model, output_type=str | None) # an empty or thinking-only final response now ends the run with result.output == None
The behaviour is narrower with explicit markers. With ToolOutput(ClaimSummary | None) or NativeOutput([ClaimSummary, None]), an empty response is not accepted: the model has to choose the None branch on purpose. Output validators still run on None, so a validator that assumes a populated object will raise before your code sees the result.
Allowing None moves a failure from loud to quiet. An agent that returns None for a document that did contain the answer has failed without an exception, and that needs its own check downstream; detecting silent AI agent failures covers how to catch it.
Raising the budget, and the per-tool trap
Once the mode is right, a budget of 1 can still be too tight for a hard schema or a strict validator. At 2.75.0, retries accepts an integer or an AgentRetries dictionary with the keys 'tools' and 'output'. A bare integer sets both; any key you leave out of a dictionary stays at 1.
from pydantic_ai import Agent, ToolOutput
# agent-wide: output budget 3, tool budget stays at the default 1
agent = Agent(model, output_type=ClaimSummary, retries={'output': 3})
# one run only
result = agent.run_sync(prompt, retries={'output': 5})
# per output tool: invalid final_result calls get 3 retries;
# plain-text replies are still charged to the run-level budget
agent = Agent(
model,
output_type=ToolOutput(ClaimSummary, max_retries=3),
retries={'output': 3},
)The documentation's precedence order, highest first: a per-tool limit such as ToolOutput(max_retries=N), a per-toolset limit, agent.override(retries=...), agent.run(retries=...), a run spec's retries, Agent(retries=...), and the built-in default of 1. The run and override layers never override a per-tool or per-toolset limit.
from pydantic_ai import ModelRetry, RunContext
@agent.output_validator
def check_policy_number(ctx: RunContext, output: ClaimSummary) -> ClaimSummary:
if not output.policy_number.startswith('POL-'):
# each ModelRetry here uses one unit of the output budget
raise ModelRetry(f'policy_number must start with POL-, got {output.policy_number!r}')
return outputWhy ToolOutput(max_retries) alone does not stop the error
The per-tool limit governs invalid calls to the output tool. It does not govern the case where the model never calls the tool. In the 2.75.0 source, a response with no tool calls, when output tools exist and plain text is not an allowed output, builds the "Please include your response in a tool call." feedback and charges it against the run-level output budget, not the output tool's max_retries. So ToolOutput(ClaimSummary, max_retries=5) with no retries argument still fails on the second prose reply with Exceeded maximum output retries (1). There is a second interaction in the same code. Failures on the output-tool path also increment the run's output counter, and the text path compares that same counter with the run-level budget. Reading the source, one invalid final_result call followed by one prose reply exhausts a budget of 1. That is why the third form above sets both values.
Spending the budget on purpose: output validators
An output validator lets you reject answers that pass the schema but break a business rule, and each rejection spends one unit of the same budget: Inside the validator, ctx.retry is the run-wide counter and ctx.max_retries is the run-level output budget; on the output-tool path, a different ToolOutput(max_retries=N) decides when the run actually stops. Make the ModelRetry message specific enough that the model can act on it: it is sent back verbatim. And set a ceiling on purpose. A validator that rejects the same answer five times on a 7B model is telling you the task needs a different model or a different decomposition, not a sixth try. Recovering from agent tool failures covers rerouting to a larger model and replanning once retries are spent. LangGraph stops a runaway agent with a different ceiling, the graph's recursion limit; Recursion limit of 25 reached in LangGraph covers that error.
Which version you are on: 1.x vs 2.x wording and keywords
The message and the keyword for the budget both changed during 1.x, so the string in your traceback tells you which API you have:
On 1.x the two forms look like this:
# 1.107.11 (and 2.x): the dict form
agent = Agent(model, output_type=ClaimSummary, retries={'output': 3})
# 1.x before 1.98.0: the keyword that 2.x removed
agent = Agent(model, output_type=ClaimSummary, output_retries=3)On 2.x, Agent(output_retries=3) raises a TypeError: the constructor has no such parameter and no catch-all keyword arguments. On 1.98.0 through 1.107.11 it works and emits a PydanticAIDeprecationWarning that names the dictionary form. If you are still on 1.x, write retries={'output': N} now on 1.107.11, and the line survives the upgrade. The project's version policy promises security fixes for 1.x for at least six months after 2.0 went stable on June 23, 2026.
| Version | Message | How to set the output budget |
|---|---|---|
| 0.4.3 and earlier | Exceeded maximum retries (N) for result validation | Upgrade before tuning anything |
| 0.4.4 to 1.91.0 | Exceeded maximum retries (N) for output validation | Agent(output_retries=N) |
| 1.92.0 to 1.107.11 | Exceeded maximum output retries (N) | output_retries=N, with a deprecation warning from 1.98.0; retries={'output': N} from 1.98.0 |
| 2.0.0 to 2.75.0 | Exceeded maximum output retries (N) | retries={'output': N} only |
Keeping the failing responses inside your perimeter
This error is specific to the stack regulated teams run in their own network: small open models on Ollama or vLLM, behind an agent framework. The diagnosis has the same constraint as the workload. A validation error quotes the model's output, and the model's output was produced from your documents, so the retry messages, the exception string and e.conversation are all copies of client data.
For tracing, Agent.instrument_all() uses the global OpenTelemetry providers, and the Pydantic AI documentation shows it exporting over OTLP to a local collector without any hosted backend; with the Logfire SDK, logfire.configure(send_to_logfire=False) plus OTEL_EXPORTER_OTLP_ENDPOINT does the same. Each retried tool call gets its own span with ERROR status and its retry cause (plus the feedback, when content is included), which turns "the agent failed" into a count of how often each cause fires. The OpenTelemetry GenAI semantic conventions guide covers which of the emitted attributes are stable.
Two advisories decide whether include_content=False actually keeps that content out of your spans. GHSA-3gh4-cghq-f8v4, published August 12, 2026, left retry prompt content unredacted; it is fixed in 2.27.1 and 1.107.4. GHSA-4x9p-g9wm-8q7f, published September 17, 2026, left exception and error strings unredacted; it is fixed in 2.44.0 and 1.107.6. Neither concerns output retries directly, but both leak exactly what this error produces. The newest pydantic-ai advisories, published November 25, 2026, are fixed in 2.74.0 and 1.107.11, so take 2.74.0 or later on 2.x and 1.107.11 on 1.x as the floor. If you are building this kind of agent on infrastructure you control, our on-premise AI development work starts from exactly these defaults.
What to do this week
Wrap the failing run in capture_run_messages() and print the retry cause on the last feedback part. If it says no_output after prose replies, change output_type to NativeOutput(YourModel) on self-hosted Ollama or vLLM, or PromptedOutput(YourModel) on Ollama Cloud, and rerun the same prompt. Only if the cause is validation_error or model_retry after that change, set retries={'output': 3} and watch the retry spans for a week before raising it further.
FAQ
Quick answers to the questions this post tends to raise.



