Skip to content
Back to log

Structured LLM output with JSON Schema

Chainabit's Chao · · 7 min read

In short

Define fields and types with JSON Schema, attach the schema to a structured outputs request, and handle cases such as refusals or incomplete responses.

JSON Schema can be used to define the fields and value types expected in an LLM response. OpenAI Structured Outputs constrains a completed, non-refusal model output to the supplied JSON Schema. Required fields and enum values in a supported schema are enforced on the output structure.

According to the JSON Schema organization, the schema itself is also written as JSON. A schema is not a computer program but a declarative format that describes the structure of other data. A schema can express which fields are expected in a person record and how their values are represented.

Defining the output fields

In the JSON Schema organization's person record example, the outermost structure is an object whose type value is object. Under properties, the first_name and last_name fields are defined as string. In the same example, the birthday field is also of type string, and its format value is given as date.

The address field in the example contains another object. This inner object has its own properties section containing the street_address, city, state and country fields. Each of them is of type string.

Anthropic lists object, array, string, integer, number, boolean and null among the basic types supported for structured outputs. In addition, enum and const can be used. Anthropic limits the values in these two features to string, number, boolean or null.

In Anthropic's example below, properties defines the fields, and required lists the names of the required fields. The same example uses additionalProperties: false. Anthropic states that for structured outputs this value must be false on objects.

Field order and requirement

Anthropic's schema defines the notes, name, email and age fields. name and email appear in the required list. The other two fields are not in that list. The type is given as string for notes, name and email, and as integer for age:

{
  "type": "object",
  "properties": {
    "notes": { "type": "string" },
    "name": { "type": "string" },
    "email": { "type": "string" },
    "age": { "type": "integer" }
  },
  "required": ["name", "email"],
  "additionalProperties": false
}

According to Anthropic, when structured outputs are used, object fields keep the order in which they are defined in the schema. There is one exception: required fields come first, followed by optional fields. Each group follows the schema order within itself.

In this example, the output order is name and email first, then notes and age. Anthropic advises marking all fields as required when field order matters to the application, or accounting for this reordering in the parsing logic.

According to Anthropic, because additionalProperties is false, Claude can return only the listed keys. The keys are listed in properties or as the class or schema fields passed to the SDK. If properties is empty or absent, the API accepts the object, but Claude can return only {} for that object.

When keys are not known in advance, Anthropic shows the use of an array in which each element carries a key and a value. In the example, items is defined as an object. The object's properties section contains the key and value fields, both of type string. Both fields are in the required list, and the object's additionalProperties is set to false.

According to Anthropic, map, dictionary or record types do not list their keys. The Python and TypeScript SDKs send them as an object with empty properties. The Java and Ruby SDKs, however, raise an error in this case.

Attaching the schema to a request

In Anthropic's JSON outputs flow, the desired structure is first defined as a JSON Schema or as a type in the language being used. The request then carries the schema in output_config.format with type: "json_schema". According to Anthropic, SDK helpers can configure this setting.

Claude returns JSON matching the schema in the text content block of the response. SDK helpers can parse the response into the defined type. Anthropic gives extracting data from text or images, generating structured reports and formatting API responses as example uses of this flow.

In Anthropic's Python SDK flow, a Pydantic model can be passed to a client.messages.parse() call as output_format. The SDK transforms the model's schema and sends it in output_config.format. It then validates the response and returns the parsed model in parsed_output.

Anthropic also uses the output_config.format field for a JSON Schema taken from a file or from an OpenAPI spec. The same field can be used to pass a schema built in code at runtime into the request. JSON outputs and strict tool use can be used together in the same request.

Turn this insight into action.

Use the mobile app to continue with guided workflows.

OpenAI also offers JSON Schema support in its REST API. In OpenAI's Python library the object schema can be defined with pydantic.BaseModel, and in its JavaScript library with z.object. OpenAI demonstrates this approach in an example of extracting information from unstructured text according to a schema defined in code.

According to OpenAI, the application must handle refusals, incomplete responses and API errors. Validating business rules that the schema does not express is also the application's responsibility. OpenAI also notes that refusals issued for safety reasons can be detected programmatically.

OpenAI defines separate behaviors for Structured Outputs and JSON mode. Both ensure valid JSON is produced, but only Structured Outputs ensures adherence to the supplied schema. OpenAI recommends using Structured Outputs instead of JSON mode whenever possible.

Supported schema features

Anthropic structured outputs support anyOf, allOf, $ref, $defs and definitions, with certain limits, in addition to the basic types. The default property can also be used on all supported types. These rules are shared by JSON outputs and strict tool use.

The string formats Anthropic supports include date-time, time, date, duration, email, hostname, uri, ipv4, ipv6 and uuid. For arrays, minItems support covers only the values 0 and 1. Array constraints other than minItems are not supported.

Anthropic does not support recursive schemas or external $ref usage. It advises using anyOf instead of oneOf. In addition, anyOf is not supported together with keys such as type or properties in the same schema object; descriptive fields such as title and description fall outside this restriction.

Anthropic also does not support allOf with conflicting schemas. For example, schemas inside allOf specifying different type values fall under this. In an allOf structure containing multiple schemas, it is also unsupported for one of the schemas to directly contain $ref, anyOf or allOf.

Numeric minimum, maximum and multipleOf constraints are among the properties the Anthropic API does not support. String minLength and maxLength are in the same group. not and enum values containing complex types are also unsupported. When an unsupported property is used, the API returns an error with details.

Anthropic also distinguishes supported from unsupported regex features. Full and partial matching, character classes and groups are among the supported features. Backreferences to groups, lookahead and lookbehind are not supported. Complex regex patterns may result in an error.

According to Anthropic, most SDK helpers transform schemas that use unsupported features. In this process, unsupported constraints are removed from the schema and added to the field description. additionalProperties: false is added to objects, and string formats are limited to the supported list.

A helper that validates responses also validates the response against the original schema and all of its constraints. In Anthropic's example, the minimum constraint is removed from the schema that is sent and added to the field description. Even so, the validating helper still checks the response against the original constraint.

Limits and exceptions

Anthropic states that when a refusal is issued for safety reasons, the stop_reason value is "refusal". Because the refusal message takes precedence over the schema constraints, the output may not match the schema. A response cut off by reaching the max_tokens limit is a separate case: here the stop_reason value is "max_tokens" and the output may be incomplete.

Anthropic structured outputs do not guarantee letter case in string enum and const values. The returned value may differ from the schema value only in letter case. Anthropic advises comparing enum values in a case-insensitive way.

In Anthropic, citations are not compatible with output_config.format. The citations feature requires interleaving citation blocks with text, which conflicts with JSON schema constraints. The API returns an error when both are enabled together. Message prefilling is also incompatible with JSON outputs.

According to the JSON Schema organization, a schema expresses the surface structure of data, and validation against that structure can be automated. However, because a schema cannot contain arbitrary code, some relationships between data elements cannot be expressed with it. For complex data formats, a separate semantic validation step may be needed in addition to structural validation.

Ready to start?

Download the app and continue from your phone.

End of Entry