Structured Output#
Turn a Pydantic v2 model into the response_format request field, and a chat
response back into a validated instance. SAIA enforces the schema on the server.
ChatService.completions_structured combines both steps;
StructuredOutputError reports an answer that is unusable.
- saia_python.response_format_for(response_model: type[BaseModel]) dict[source]#
Build the
response_formatrequest field for a Pydantic model.strictis left unset: SAIA’s backends enforce the schema either way, whereas OpenAI’s strict mode would reject a plain Pydantic schema (it requiresadditionalProperties: falseon every object).- Parameters:
response_model – A Pydantic v2 model class.
- Returns:
{"type": "json_schema", "json_schema": {"name": ..., "schema": ...}}with the model’s JSON Schema, named after the class (characters outsidea-z A-Z 0-9 _ -, such as a generic’s brackets, become_).
- saia_python.parse_structured(response: dict, response_model: type[ModelT]) ModelT[source]#
Validate a chat response’s answer into
response_model.Reads the first choice’s
content— the JSON string the model wrote — and validates it withresponse_model.model_validate_json. Works on any OpenAI-style ChatCompletion dict, such as the onecompletions()returns.- Parameters:
response – A chat completion response dict.
response_model – The Pydantic v2 model class to validate into.
- Returns:
The validated
response_modelinstance.- Raises:
StructuredOutputError – When there is no usable answer: no choices; no content (a reasoning model that ran out of tokens while thinking returns
content: Nonewithfinish_reason: "length"); an answer cut off atmax_tokens; or one that fails validation, with thepydantic.ValidationErrorchained as the cause.