Generate structured data
Provide a schema to structured-data generation APIs such as generateObject or streamObject.
AI Tools · Function
Creates an AI SDK-compatible JSON schema from a JSON Schema definition, with optional custom validation. Use it for structured-data generation and tool inputs when dynamic schemas or non-Zod validation are needed.
jsonSchema wraps a JSON Schema definition for use by the AI SDK. You can optionally provide a validator that returns either a validated value on success or an error on failure, making the schema usable for structured-data generation and tool inputs.
jsonSchema(schema: JSONSchema7, options?: SchemaOptions): JSONSchema| Name | Type | Description |
|---|---|---|
schema | JSONSchema7 | The JSON schema definition. |
options | SchemaOptions | Additional options for the JSON schema, including an optional validator. |
validate? | (value: unknown) => { success: true; value: OBJECT } | { success: false; error: Error } | Optional function that validates an unknown value and returns either a successful validated value or an error. |
A JSON schema object compatible with the AI SDK.
jsonSchema to adapt a JSON Schema definition into an object the AI SDK understands.schema parameter contains the JSON Schema definition passed to the helper.import { jsonSchema } from 'ai';
const userSchema = jsonSchema({
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'number' },
},
required: ['name', 'age'],
additionalProperties: false,
});
console.log(userSchema);Creates an AI SDK-compatible JSON schema for describing structured data.
Provide a schema to structured-data generation APIs such as generateObject or streamObject.
Define tool input parameters with a raw JSON schema.
Use OpenAPI-derived or otherwise runtime-created schema definitions.
Integrate validation from a library other than Zod through the optional validator.
jsonSchema do?It creates a JSON schema object compatible with the AI SDK. The schema can describe structured data and tool inputs.
Follow-up: When would you choose it instead of Zod? Use it for dynamic definitions such as OpenAPI-generated schemas or when another validation library is preferred.
The required schema argument is a JSONSchema7 definition. An optional options argument supplies additional JSON-schema behavior, including an optional validator.
Follow-up: What type should the validator accept? It should accept an unknown value and return either the success or failure result shape.
The optional validator returns { success: true, value } for valid input or { success: false, error } for invalid input. The function returns an AI SDK-compatible JSON schema object.
Follow-up: Why return the validated value? It lets downstream code use the validator's typed or transformed result after validation.
generateObjectstreamObjecttoolzodSchema