Structured Output v1.0.0+
Force models to return strictly validated JSON data using Zod schemas or manual JSON definitions across all supported providers.
Table of contents
- Using Zod (Recommended)
- Manual JSON Schemas
- JSON Mode
- Provider Support
- Nested Schemas
- When a Response Doesn’t Match
- 🛡️ Automating Schema Correction (Middleware) v1.15.0+
Ensure the AI returns data exactly matching a specific structure. NodeLLM supports strict schema validation using Zod (recommended) or manual JSON schemas.
This feature abstracts the provider-specific implementations (like OpenAI’s json_schema, Gemini’s responseJsonSchema, or Anthropic’s tool-use workarounds) into a single, unified API.
See it in action: The Brand Perception Checker demonstrates utilizing rigorous Zod schemas to extract consistent semantic profiles across multiple providers simultaneously.
Using Zod (Recommended)
The easiest way to define schemas is with Zod.
import { NodeLLM } from "@node-llm/core";
import { z } from "zod"; // Zod 4
// Define a schema using Zod
const personSchema = z.object({
name: z.string().describe("Person's full name"),
age: z.number().describe("Person's age in years"),
hobbies: z.array(z.string()).describe("List of hobbies")
});
const chat = NodeLLM.chat("gpt-5-mini");
// Use .withSchema() to enforce the structure
const response = await chat
.withSchema(personSchema)
.ask("Generate a person named Alice who likes hiking and coding");
// Streaming is also supported!
// for await (const chunk of chat.withSchema(personSchema).stream("...")) { ... }
// The response is strictly validated and parsed
const person = response.data;
console.log(person.name); // "Alice"
console.log(person.age); // e.g. 25
console.log(person.hobbies); // ["hiking", "coding"]
Zod 4 and Zod 3
NodeLLM accepts both Zod 4 and Zod 3 schemas. Use Zod 4 for new code: add it to your app (npm install zod) and import z from "zod", as above. Zod 4 schemas need Zod 4.2 or later, imported from "zod" rather than "zod/mini".
Zod 3 schemas still work, including ones built with the z that @node-llm/core exports, which stays Zod 3 so existing code keeps working. Zod 3 support is deprecated, though, and may be removed in a future major version, when the exported z would become Zod 4.
Manual JSON Schemas
You can also provide a raw JSON schema object if you prefer not to use Zod.
Note for OpenAI: By default, NodeLLM uses OpenAI’s “Strict Mode” (which sets strict: true and additionalProperties: false in the schema).
To turn it off, build the schema with strict: false and pass it to withSchema():
import { Schema } from "@node-llm/core";
chat.withSchema(Schema.fromJson("person", schema, { strict: false }));
Schema.fromZod(name, zodSchema, { strict: false }) does the same for a Zod schema.
// OpenAI 100% Strict Mode enabled automatically
const schema = {
type: "object",
properties: {
name: { type: "string" },
age: { type: "integer" }
},
required: ["name", "age"],
additionalProperties: false // Required for strict mode in OpenAI
};
const response = await chat.withSchema(schema).ask("Generate a person");
console.log(response.data); // { name: "...", age: ... }
JSON Mode
If you just need valid JSON but don’t want to enforce a rigid schema, you can enable JSON mode. This instructs the model to return valid JSON but gives it more freedom with the structure.
chat.withRequestOptions({
responseFormat: { type: "json_object" }
});
const response = await chat.ask("Generate a JSON object with a greeting");
console.log(response.data); // { greeting: "..." } or whatever keys it chose
Provider Support
| Provider | Method Used | Notes |
|---|---|---|
| OpenAI | response_format: { type: "json_schema" } | Fully supported with strict adherence. |
| Gemini | responseJsonSchema | Supported natively. |
| Anthropic | output_config.format (structured outputs) | On Claude Fable and Mythos 5, Opus 5 and 4.8, Sonnet 5, Haiku 5 and 4.5 (and Opus 4.5 and 4.1), the answer is held to the schema. Constraints Anthropic doesn’t take, such as min, max and lengths, are left out of what is sent and still checked by Zod. Older models, and schemas with records or self-references, get the schema in the system prompt with an instruction to respond only with matching JSON. |
Nested Schemas
Complex nested schemas are fully supported via Zod.
const companySchema = z.object({
name: z.string(),
employees: z.array(
z.object({
name: z.string(),
role: z.enum(["developer", "designer", "manager"]),
skills: z.array(z.string())
})
),
metadata: z.object({
founded: z.number(),
industry: z.string()
})
});
const response = await chat.withSchema(companySchema).ask("Generate a small tech startup");
When a Response Doesn’t Match
response.data throws Zod’s ZodError when the response doesn’t match the schema. Its message is one line that names each field, the values the schema allows and the value the model sent, so it can go straight into a log or an error screen:
Response did not match the "verdict" schema: status: Invalid option: expected one of "passed"|"failed" (got "blocked")
The same parts are on error.problems, one per field: path (such as steps[2].status), message, expected (an enum’s or literal’s allowed values) and received (undefined when the model left the field out). response.isValid, response.validationError and response.safeData check without throwing.
Lenient Enums
To accept a response with an unknown enum value instead of failing, say so in the schema with Zod’s .catch(). The model is still sent the allowed values.
const verdict = z.object({
// An unknown status becomes "unknown"
status: z.enum(["passed", "failed", "unknown"]).catch("unknown"),
// An unknown priority is left out
priority: z.enum(["low", "high"]).optional().catch(undefined)
});
To have the model fix its answer instead, add the self-correction middleware below: it re-asks with this message.
🛡️ Automating Schema Correction (Middleware) v1.15.0+
Even with strict schemas, non-OpenAI models (like Claude, Gemini, or local models) can occasionally hallucinate invalid JSON or skip required fields.
You can use the Schema Self-Correction Middleware to handle this automatically. If validation fails, NodeLLM will catch the error, send it back to the LLM as feedback, and retry the request up to maxRetries times.
Usage
import { NodeLLM, SchemaSelfCorrection, z } from "@node-llm/core";
const schema = z.object({ age: z.number() });
const chat = NodeLLM.chat("claude-sonnet-5", {
// Add the self-correction middleware
middlewares: [
SchemaSelfCorrection({ maxRetries: 2 })
]
}).withSchema(schema); // withSchema() types response.data from the schema
// If Claude returns { "age": "30" } (string), the middleware
// will automatically re-prompt: "Error: Expected number, received string at 'age'. Please fix."
const response = await chat.ask("Get age");
console.log(response.data.age); // Guaranteed to be a number or throws after max retries
Why use this?
- Reliability: Turn every provider into a “Strict Output” provider.
- Clean Logic: No more manual
try/catchand retry loops in your application code. - Feedback Loop: Providing the exact Zod error to the LLM is more effective than generic “Fix this” prompts.