A schema is a promise with exceptions
Structured outputs make the model's answer follow a JSON Schema. Anthropic's documentation says this guarantees a response that matches your schema in most cases, and then lists where it doesn't: a refusal, whose message takes precedence over the schema, and a response cut off at the token limit.
A third case never reaches the model. The provider can fail before it answers: a timeout, an overload, a rate limit. Our code has to tell these four situations apart, because each one needs a different next step.
- providers, tried in order
- 2
- outcomes for an answer: done, refused, incomplete, invalid
- 4
- retries by the Anthropic SDK before the second provider is tried
- 2
- timeout for each provider call
- 120 s
The code is the AI client behind our lead triage. The triage is built and tested and still switched off until its evals pass, but the client is the part every AI feature on the site shares.
One request, one schema
Each feature describes a request as a Prompt: a stable system prompt, the user turn, and a Pydantic model for the output. The triage's model has a summary, a category from a fixed list, a fit score from 0 to 100, up to five questions and a draft reply.
class TriageOutput(BaseModel):
summary: str = Field(description="Two or three sentences: who they are, what they want.")
category: TriageCategory # an enum: product_build, spam, ...
fit_score: int = Field(ge=0, le=100, description="0-100, per the rubric in the instructions.")
missing_questions: list[str] = Field(description="Up to five questions to answer before scoping.")
draft_reply: str = Field(description="Plain-text reply email. Empty for spam.")
OUTPUT_SCHEMA = transform_schema(TriageOutput) # the SDK's strict JSON SchemaThe score has bounds, ge=0, le=100. Anthropic's strict mode doesn't accept numeric bounds, so the SDK helper turns them into text in the schema, which the docs describe. That means the model is told the range but isn't forced into it. We validate every answer against the original Pydantic model, so a score of 140 is caught on our side.
The same schema goes to both providers: as output_config.format for Anthropic, and as a strict response_format for OpenRouter. OpenRouter's documentation says enforcement varies by provider and some treat a schema as a strong hint. So we also send require_parameters, which routes the request only to endpoints that support structured outputs.

Read the stop reason before the content
The order of the checks matters. A refusal comes back as a normal response, not an error, with stop_reason: "refusal", and you are billed for the tokens it generated. Its text may not match your schema at all. A response cut off at the limit has stop_reason: "max_tokens" and can stop in the middle of a value.
# The stop reason comes before the content: a refusal or a cut-off answer is not the output.
if response.stop_reason == "refusal":
answer.outcome = Outcome.refused
answer.detail = response.stop_details.category if response.stop_details else None
return answer
if response.stop_reason != "end_turn":
answer.outcome, answer.detail = Outcome.incomplete, response.stop_reason
return answer
text = next((block.text for block in response.content if block.type == "text"), "")
answer.output = parse(prompt, text) # model_validate_json: the original Pydantic model
if answer.output is None:
answer.outcome = Outcome.invalidOnly a response that ends its turn gets parsed. Anything else becomes an outcome of its own, with the reason attached, and the caller decides what to do with it. OpenRouter's answer goes through the same three steps, using its own signals: a refusal field, a content filter, or a finish reason other than stop.
| What came back | Outcome | What happens next |
|---|---|---|
| The model refused | refused | Stored as failed, with the refusal's category. No retry. |
| It stopped early (for example max_tokens) | incomplete | Stored as failed, with the stop reason. |
| Text that doesn't match the schema | invalid | Stored as failed: the triage came back in an unexpected shape. |
| An error, a timeout or an overload | error | The next provider is tried. If all fail and any could recover, the job goes back to the queue. |
| A valid answer | done | Stored with the provider, model, tokens and estimated cost. |
Why not retry a refusal
The same request would get the same answer. A person reads the failed triage in the admin and answers the brief.
A second provider, only when the first fails
The client tries the providers that have a key, in order: Anthropic's API first, then OpenRouter. An error moves on to the next provider. An answer doesn't, and that includes a refusal. If we sent every refused request to another provider, we would be shopping for a model that agrees to answer, and the second provider's classifier would be the only one that mattered.
for provider in self.providers:
try:
return await provider.ask(prompt) # any answer, a refusal included, ends the loop
except AiError as exc:
errors.append(exc) # unreachable, overloaded, rate-limited, bad key
raise AiError("; ".join(str(e) for e in errors), ...,
retryable=any(e.retryable for e in errors))An error is retryable when it is a connection problem, a timeout, or a status of 408, 409, 429 or 500 and up. If every provider failed and at least one error could recover, the worker puts the job back in the queue with a delay. If none could, for example a bad key, the lead's triage is saved as failed and the job stops.
Refusals have a second, separate layer. For the models that support it, we send fallbacks: "default" with Anthropic's beta header, and Anthropic's API retries a declined request on the model it recommends, as its documentation describes (as of November 2, 2026). The answer records which model replied, so we can see when that happened. For refusal categories with no recommended model, the refusal stays.
Test the answers you hope never come
A happy path takes one test. The bad answers are where the code earns its place, so the tests feed the client:
- a refusal with a category, a response cut at
max_tokens, a score of 140 and text that isn't JSON, each expected to become a failed triage with a clear message; - the same unusable answers from OpenRouter;
- an Anthropic failure followed by an OpenRouter answer, and an Anthropic answer that stays final even when OpenRouter has a key;
- every provider failing, and an error hidden behind an HTTP 200, which counts as a failure.
The tests use a fake transport, so they run without a key. Real answers are the job of the evals, which we run before any AI feature is switched on.
An answer, even a refusal, is final; only an error moves on.
If you build on an LLM
Check the stop reason first, validate with the schema you wrote and not only the one you sent, and treat a refusal as an answer. Those three habits keep one bad response from becoming a bad record.
We build AI agents this way, with the failure paths tested before the happy one. If you have one in mind, see what fits or send us a brief. A person reads it.


