Validate the Answer and Ask Again
Sending a schema with a request asks a language model for JSON in a given shape. Whether the reply really has that shape depends on the endpoint, and even a reply in the right shape can break a rule the schema has no way to state. So a program checks every structured answer itself. When the answer does not fit, it gives the model one more chance with the error it found, and when no valid answer arrives, it fails in a way the calling code can handle.
Enforced, only requested, or rejected
Many providers and local servers accept the same Chat Completions request, but they do not all treat the response_format field the same way. When the request carries a JSON Schema, an endpoint does one of three things with it.
- It constrains generation. With
{"type": "json_schema", ...}and"strict": true, endpoints that support it limit which tokens the model may choose, so the finished text always fits the schema. Groq calls this constrained decoding; vLLM and Ollama also enforce a schema sent this way. OpenAI accepts only a subset of JSON Schema in strict mode, and sends back an error for a schema that uses anything outside it. - It only asks. The request tells the model what to write, but nothing holds it to the shape. JSON mode (
{"type": "json_object"}) promises valid JSON and nothing about its fields. A schema sent withoutstrictis best effort:strictdefaults tofalse, and Groq documents that such a reply may have wrong field types or missing or extra fields. Some endpoints offer only JSON mode. - It rejects the request. The endpoint answers with HTTP status 400 and no reply at all; the openai client raises
openai.BadRequestError. Anthropic's OpenAI compatibility layer, for example, accepts only a strictjson_schemaand returns 400 forjson_object.
| The endpoint | What can come back | What the code must still do |
|---|---|---|
| constrains generation to the schema | JSON in the shape of the schema, or a refusal, or a reply cut off at its cap | check for a refusal or a cut-off, then check the rules the schema cannot state |
| only asks the model to follow it | JSON in the right shape, JSON in the wrong shape, broken JSON, even blank text | validate every field before using any of it |
| rejects the request | no reply: an HTTP 400 error | change the request, for example to the response format the endpoint accepts |
Two facts make validation necessary in all three cases. First, an endpoint does not always say what it ignores: many compatible endpoints drop fields they do not support without any error, so a request that looks enforced may only be requested. The program cannot tell from its own code which kind of endpoint it reached, and the endpoint is a setting that can change. Second, even enforcement covers only the shape. OpenAI's own guide says an application still needs to handle refusals, incomplete responses and API errors, and to validate the business rules the schema does not express.
So the program treats the reply text as a claim and checks it with the same Pydantic model that produced the schema. The client's helper client.chat.completions.parse() does this check for you, but it always sends a strict json_schema. That has two consequences. On an endpoint that ignores the schema, the reply may not fit, and the helper raises Pydantic's ValidationError. On an endpoint that offers only JSON mode, the request cannot be made with the helper at all. The path that works on every endpoint has two steps: get the reply with client.chat.completions.create(), then pass its text to the model class's model_validate_json(), as the next section shows.
True or false?
If a request includes a JSON Schema, the reply is guaranteed to match it.
False. Only an endpoint that constrains generation, with strict mode on a model that supports it, guarantees the shape. JSON mode and best-effort modes can return valid JSON in the wrong shape.
An endpoint can ignore a field it does not support and still answer with status 200.
True. Many compatible endpoints silently ignore unsupported fields. The request succeeds, and only validating the reply shows that the schema had no effect.
With enforced structured output, the program has nothing left to check.
False. Refusals, cut-off replies and rules beyond the schema remain, and OpenAI notes that structured outputs can still contain mistakes.
What a validation error reports
Validation compares the reply with the model class field by field. Take a program that sorts customer messages into tickets. Each ticket has a category and a priority from fixed sets of values, and a short summary:
from typing import Literal
from pydantic import BaseModel, ValidationError
class Ticket(BaseModel):
category: Literal["refund", "delivery", "other"]
priority: Literal["low", "normal", "high"]
summary: str
text = '{"category": "refund", "priority": "urgent"}'
try:
ticket = Ticket.model_validate_json(text)
except ValidationError as error:
print(error.error_count())
print(error)The reply is valid JSON, but it breaks the model twice: "urgent" is not one of the allowed priorities, and there is no summary. Pydantic does not stop at the first problem. It raises a single ValidationError that holds every error it found, so error_count() returns 2, and printing the error gives a readable report:
2 validation errors for Ticket
priority
Input should be 'low', 'normal' or 'high' [type=literal_error, input_value='urgent', input_type=str]
summary
Field required [type=missing, input_value={'category': 'refund', 'priority': 'urgent'}, input_type=dict]Under each error the printed report also adds a line with a link to that error type's documentation, left out above. Each error answers two questions: which field failed (the line with the field name) and why (the message, with the bad input). The same information is available as data through error.errors(), a list with one dictionary per error:
| Key | What it holds | For the priority above |
|---|---|---|
| loc | where the error is: the field, then the path inside it for a nested model or a list | ('priority',) |
| msg | a human-readable explanation | Input should be 'low', 'normal' or 'high' |
| type | a computer-readable name of the error | literal_error |
| input | the value that was given | 'urgent' |
Broken JSON is reported the same way, as a ValidationError of type json_invalid, so one except ValidationError catches both a reply that is not JSON and a reply in the wrong shape. Pydantic does convert some values in its default lax mode (the string "123" becomes the integer 123 for an int field), but a Literal is matched exactly: "High" is not "high".
True or false?
When two fields are wrong, the ValidationError reports both of them.
True. Pydantic raises one exception that holds every error it found, each with its field and its reason.
For a field declared as Literal["low", "normal", "high"], Pydantic turns "High" into "high".
False. A Literal is matched exactly. Lax conversion applies to types such as int, not to a fixed set of allowed values.
Asking again with the error
A validation error is precise enough for the model to act on. The program can send the failed answer back with the error and ask for a corrected one. The model sees only the messages of the current request, so the new request carries the whole conversation again, with two messages added at the end: the failed answer as an assistant message, so the model sees what it wrote, and the error as a new user message that says what to fix.
| Role | Content |
|---|---|
| system | Sort the customer message into a ticket. Reply with JSON with category, priority and summary. |
| user | My parcel never arrived and I want my money back. |
| assistant | {"category": "refund", "priority": "urgent"} |
| user | Your answer did not fit the schema: 2 validation errors for Ticket ... Reply again with JSON that fixes these errors. |
The function below makes at most two attempts: the first, and one more with the error. It asks for JSON mode, a response format most compatible endpoints accept; on an endpoint that constrains generation, the strict json_schema form goes in its place, and the rest stays the same. Before it validates anything, it makes sure there is something to validate: a reply that ended normally, with the finish reason stop, and text that is not blank.
class NoValidTicket(Exception):
"""No reply fitted the ticket model within the allowed attempts."""
def get_ticket(client, model, messages, max_attempts=2):
messages = list(messages)
last_error = None
for _ in range(max_attempts):
response = client.chat.completions.create(
model=model,
messages=messages,
response_format={"type": "json_object"},
)
choice = response.choices[0]
text = choice.message.content
if choice.finish_reason != "stop" or not text or not text.strip():
raise NoValidTicket(f"nothing to validate (finish reason: {choice.finish_reason})")
try:
return Ticket.model_validate_json(text)
except ValidationError as error:
last_error = error
messages.append({"role": "assistant", "content": text})
messages.append({
"role": "user",
"content": f"Your answer did not fit the schema:\n{error}\n"
"Reply again with JSON that fixes these errors.",
})
raise NoValidTicket(f"no valid ticket after {max_attempts} attempts:\n{last_error}")The number of attempts is limited for three reasons. Every attempt is a full new call, billed for its input and output tokens, and the input grows with each failed answer and error added to it. Every attempt also adds the time of a whole reply to what someone is waiting for. And a model that fails twice in the same way usually fails again: the cause is more often an unclear prompt or a schema the model cannot follow than bad luck. No official source names a right number; one extra attempt fixes the occasional slip, and a failure that repeats is better shown than hidden behind more calls.
This kind of retry is separate from the retries the openai client makes on its own. The client resends a request after a lost connection or a status such as 408, 409, 429 or a 5xx server error, twice by default. A reply in the wrong shape arrives with status 200, so the client never retries it: only the program's own validation sees that it is wrong.
True or false?
The openai client automatically retries a reply whose JSON does not fit the schema.
False. The client retries connection errors and statuses such as 408, 409, 429 and 5xx. A wrong-shaped reply is a successful response, so only the program's validation catches it.
A second attempt that includes the failed answer and the error costs more input tokens than the first attempt.
True. The request carries the whole conversation again, plus the failed answer and the error text, and all of it is billed as input.
Rules the schema cannot express
A schema describes shape: which fields exist, their types, which values are allowed. The schema Pydantic generates from a plain model cannot say that one field depends on another (JSON Schema has keywords such as if and then for that, but OpenAI's strict mode does not accept them), and no schema can say that a value must match something outside the reply. Suppose a ticket also has an order_id, and a refund needs one. A reply with "category": "refund" and "order_id": null fits the schema perfectly, and it is still wrong. A valid answer is not yet a correct one.
Pydantic runs such rules as validators, in your code, after it has checked the types. A model validator in the default after mode receives the finished object, raises ValueError when a rule fails, and returns the object when it holds:
from typing import Literal
from pydantic import BaseModel, model_validator
class Ticket(BaseModel):
category: Literal["refund", "delivery", "other"]
priority: Literal["low", "normal", "high"]
order_id: str | None
summary: str
@model_validator(mode="after")
def refund_needs_order(self):
if self.category == "refund" and self.order_id is None:
raise ValueError("a refund ticket needs an order_id")
return selfPydantic catches the ValueError and reports it inside the usual ValidationError, with the type value_error and the message Value error, a refund ticket needs an order_id. Because it is the same exception, the same loop that asks again for a wrong priority asks again for a broken rule, and the model reads the rule's message as the reason. Write the message for that reader: it says what is wrong and what a correct answer contains.
Two details matter when writing such a rule. Raise ValueError, not ValidationError itself: Pydantic builds the ValidationError from it. And avoid assert for these rules, because Python skips assert statements when it runs with the -O option, so the rule would silently stop being checked.
Some rules need data from outside the reply, such as whether the order_id really appears in the customer's message, since a model can produce an id that looks right and exists nowhere. Such a check can be a plain if on the parsed object, after validation, with the same choice afterwards: ask again with a clear reason, or fail.
True or false?
A reply that passes validation against the schema can still be wrong for the application.
True. The schema checks shape and allowed values. Rules such as a refund needing an order id are checked in code, after parsing.
A Pydantic validator signals a broken rule by raising ValidationError.
False. It raises ValueError (or AssertionError or PydanticCustomError), and Pydantic wraps it into the ValidationError it raises.
Failing clearly
Sometimes no valid answer arrives: the attempts run out, the reply was cut off at its cap, the model refused, or the text is blank (one provider's JSON mode can return content made only of spaces, with the finish reason stop). At that point the program could guess, for example fill in "normal" for the priority it did not get, or return the fields that did validate. Both hide the failure. The calling code would act on a ticket that nobody produced, and nothing would show that it happened.
An explicit failure is a specific exception, such as NoValidTicket above, raised in place of a result. Its message carries the last validation error or the finish reason, so whoever reads the log sees why. The calling code decides what a failure means for it: put the message in a queue for a person, show a short apology, try again later. The openai client works the same way: .parse() raises LengthFinishReasonError for a cut-off reply and never returns a half-filled object.
- Reply text
- Anything to check? finish reason, blank text
- Fits the schema? types, allowed values
- Holds the rules? validators, checks
- Ticket
- Ask again with the errorOne more attempt
The failed answer and the error are added to the conversation and the whole request is sent again, while attempts remain.
- Explicit failureA failure the caller can handle
A specific exception with the reason in its message, in place of a guessed or partial result.
- Reply text to Anything to check?
- Anything to check? to Fits the schema?: yes
- Fits the schema? to Holds the rules?: yes
- Holds the rules? to Ticket: yes
- Anything to check? to Explicit failure: no
- Fits the schema? to Ask again with the error: no
- Holds the rules? to Ask again with the error: no
- Ask again with the error to Explicit failure: no attempts left
True or false?
When the priority field fails twice, filling in a sensible default value is a safe way to keep the program running.
False. A default hides the failure: the calling code acts on a value no one produced. An explicit exception lets it decide what to do.
A specific exception type lets the calling code tell a missing answer apart from other errors.
True. The caller can catch that one type and handle it, for example by passing the message to a person, while other errors keep their own handling.