Introduction
In the previous article, we learned how to use Output Parsers to convert AI responses into structured data.
Our workflow looked like this:
Prompt
↓
LLM
↓
Output Parser
↓
JavaScript Object
This approach works well and supports almost every language model.
However, modern AI providers like OpenAI and Google Gemini now support native structured output.
Instead of asking the model to generate JSON and then parsing it afterward, the model itself understands the schema and returns structured data directly.
LangChain exposes this feature through the withStructuredOutput() method.
In this article, you'll learn:
- What Structured Output is
- Why it is useful
- How
withStructuredOutput()works - Zod Schema integration
- Nested Objects
- Arrays
- Enums
- Optional Fields
- Validation
- OpenAI examples
- Gemini examples
- Best practices
Let's get started.
What is Structured Output?
Structured Output allows the language model to return data that follows a predefined schema.
Instead of returning plain text like:
Node.js was created by Ryan Dahl in 2009.
The model can return:
{
"name": "Node.js",
"creator": "Ryan Dahl",
"year": 2009
}
This structured data is much easier to work with in real applications.
Why Do We Need Structured Output?
Suppose you're building a resume parser.
Without structured output:
John Doe has 5 years of experience...
Your application must manually extract:
- Name
- Experience
- Skills
This can be error-prone.
With structured output:
{
"name": "John Doe",
"experience": 5,
"skills": ["React", "Node.js"]
}
The data is immediately usable.
Output Parser vs Structured Output
In the previous article, our workflow looked like this:
User
↓
Prompt
↓
LLM
↓
Output Parser
↓
JavaScript Object
With native structured output:
User
↓
Prompt
↓
LLM + Schema
↓
JavaScript Object
The parser is no longer required because the model understands the schema directly.
Project Setup
Install the required packages:
npm install langchain @langchain/openai @langchain/google-genai zod dotenv
Project Structure
structured-output/
├── index.js
├── .env
├── package.json
Configure Environment Variables
OPENAI_API_KEY=your_openai_api_key
GOOGLE_API_KEY=your_google_api_key
Import Required Modules
import "dotenv/config";
import { z } from "zod";
import { ChatOpenAI } from "@langchain/openai";
import { ChatGoogleGenerativeAI } from "@langchain/google-genai";
Initialize OpenAI
const model = new ChatOpenAI({
model: "gpt-4.1-mini",
});
Your First Structured Output
First, define a schema using Zod.
const employeeSchema = z.object({
name: z.string(),
role: z.string(),
experience: z.number(),
});
Now configure the model.
const structuredModel =
model.withStructuredOutput(
employeeSchema
);
Invoke it.
const response =
await structuredModel.invoke(
"Generate a frontend developer profile."
);
console.log(response);
Output:
{
name: "John Doe",
role: "Frontend Developer",
experience: 5
}
Notice that no output parser is required.
Gemini Example
const model =
new ChatGoogleGenerativeAI({
model: "gemini-2.5-flash",
});
const structuredModel =
model.withStructuredOutput(
employeeSchema
);
const response =
await structuredModel.invoke(
"Generate backend developer details."
);
console.log(response);
The API remains almost identical.
Understanding Zod Schemas
Zod defines the expected structure of the response.
const schema = z.object({
name: z.string(),
age: z.number(),
});
The model now knows:
namemust be a string.agemust be a number.
Nested Objects
Real applications often return nested data.
const employeeSchema = z.object({
name: z.string(),
address: z.object({
city: z.string(),
country: z.string(),
}),
});
Expected response:
{
"name": "John",
"address": {
"city": "Hyderabad",
"country": "India"
}
}
Arrays
const schema = z.object({
name: z.string(),
skills: z.array(z.string()),
});
Output:
{
"name": "John",
"skills": [
"React",
"Node.js",
"TypeScript"
]
}
Arrays of Objects
const schema = z.object({
projects: z.array(
z.object({
title: z.string(),
duration: z.number(),
})
),
});
Output:
{
"projects": [
{
"title": "CRM",
"duration": 8
},
{
"title": "LMS",
"duration": 12
}
]
}
Enum Fields
Enums restrict values to predefined options.
const schema = z.object({
role: z.enum([
"Frontend",
"Backend",
"Full Stack",
]),
});
This prevents unexpected role values.
Optional Fields
Some fields may not always be available.
const schema = z.object({
name: z.string(),
phone: z.string().optional(),
});
The phone field can be omitted without causing validation issues.
Nullable Fields
Sometimes a field exists but may have no value.
const schema = z.object({
salary: z.number().nullable(),
});
Example output:
{
"salary": null
}
Combining Different Types
const employeeSchema = z.object({
name: z.string(),
age: z.number(),
role: z.enum([
"Frontend",
"Backend",
]),
skills: z.array(z.string()),
phone: z.string().optional(),
});
This resembles the kind of schema used in production applications.
Error Handling
Always wrap model calls in try...catch.
try {
const response =
await structuredModel.invoke(
"Generate employee details."
);
console.log(response);
} catch (error) {
console.error(error);
}
This helps your application handle API or validation errors gracefully.
Real-World Example 1 – Resume Parser
Schema:
const resumeSchema = z.object({
name: z.string(),
experience: z.number(),
skills: z.array(z.string()),
});
The model can return structured resume information that can be stored in a database or displayed in a dashboard.
Real-World Example 2 – Blog Metadata Generator
const blogSchema = z.object({
title: z.string(),
description: z.string(),
tags: z.array(z.string()),
});
Useful for generating SEO-friendly metadata automatically.
Real-World Example 3 – Invoice Extractor
const invoiceSchema = z.object({
invoiceNumber: z.string(),
amount: z.number(),
vendor: z.string(),
});
This allows AI to extract invoice details into a predictable format.
StructuredOutputParser vs withStructuredOutput()
StructuredOutputParser
- Uses prompt instructions
- Works with many models
- More manual setup
- Good fallback option
withStructuredOutput()
- Uses native model capabilities
- Requires provider support
- Simpler API
- Preferred when available
Best Practices
- Use
withStructuredOutput()when your chosen model supports it. - Keep schemas focused on the data you actually need.
- Prefer enums for fields with limited values.
- Use nested objects only when they reflect your domain model.
- Handle errors gracefully in production code.
Common Beginner Mistakes
- Forgetting to define a schema before calling
withStructuredOutput(). - Expecting unsupported models to provide native structured output.
- Creating overly complex schemas too early.
- Not wrapping API calls in
try...catch. - Mixing
StructuredOutputParserandwithStructuredOutput()without understanding when to use each.
Final Thoughts
Native structured output is one of the biggest improvements in modern LangChain.js. Instead of relying on prompt instructions and manual parsing, you can define a Zod schema and let supported models return validated JavaScript objects directly.
For applications that need consistent, machine-readable data—such as dashboards, APIs, resume analyzers, and document processing—withStructuredOutput() leads to cleaner code and a better developer experience.
As you continue through this series, you'll see how these structured responses fit naturally into larger LangChain workflows.
Happy Coding! 🚀