Run in Colab
Step through this example interactively
Helpers overview
pydantic_format(MyModel, name=None, strict=None): Generate a response schema from a Pydantic v2 model; optionally override the schema name or set itsstrictflag.json_schema_format(schema, name="response", strict=None): Wrap a JSON Schema dict describing the response keys, enums, and structure.regex_format(pattern): Constrain short outputs (yes/no, IDs, emails) with a regex instead of a full schema.
response_format argument available on perceive, async_perceive, Client.generate, and Client.stream.
Pydantic-backed responses
Use a Pydantic model to define the target shape, then passpydantic_format. After a successful completion, validate the returned JSON with the same model.
Express required keys, allowed values, and extra-field handling in your schema; for example, use
additionalProperties: false to disallow extra fields. Validate the response in your application even when requesting strict output.Raw JSON Schema
If you already have a schema, pass it directly viajson_schema_format.
Regex constraints for short answers
Useregex_format when a compact pattern is enough (e.g., binary decisions, IDs, or numeric ranges).
Structured responses and function tools
These response constraints are separate fromfunction.strict, which is accepted for function tools but does not enforce their argument schema. On models that support function calling, validate generated arguments before executing a tool.
A request cannot declare non-empty tools together with a json_schema response format or regex. Complete the tool loop first, then request a constrained final response without declaring tools.
Streaming with structure
Client.stream and async_perceive(stream=True) support the same response_format. Buffer the text deltas and validate the complete result after successful generation. Individual deltas are not complete JSON.
For raw API streams, check finish_reason and error events before parsing: length means the response may be truncated, and an error or interrupted connection may leave partial output. A terminal event alone does not guarantee a complete schema-valid response.
Schema compilation can add latency the first time you use a new shape. Reuse the same schema object or Pydantic model to benefit from provider-side caching.