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_format request field for a Pydantic model.

strict is left unset: SAIA’s backends enforce the schema either way, whereas OpenAI’s strict mode would reject a plain Pydantic schema (it requires additionalProperties: false on 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 outside a-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 with response_model.model_validate_json. Works on any OpenAI-style ChatCompletion dict, such as the one completions() returns.

Parameters:
  • response – A chat completion response dict.

  • response_model – The Pydantic v2 model class to validate into.

Returns:

The validated response_model instance.

Raises:

StructuredOutputError – When there is no usable answer: no choices; no content (a reasoning model that ran out of tokens while thinking returns content: None with finish_reason: "length"); an answer cut off at max_tokens; or one that fails validation, with the pydantic.ValidationError chained as the cause.