0
# Output Parsing
1
2
Structured output parsing for converting LLM responses into typed data structures. Output parsers transform raw text or message outputs into usable formats.
3
4
## Capabilities
5
6
### Base Output Parser
7
8
Abstract base class for all output parsers.
9
10
```typescript { .api }
11
/**
12
* Abstract base class for parsing LLM outputs
13
* @template T - Type of parsed output
14
*/
15
abstract class BaseOutputParser<T = unknown> extends Runnable<string | BaseMessage, T> {
16
/** Parse text string to structured output */
17
abstract parse(text: string): Promise<T>;
18
19
/** Parse from chat result */
20
parseResult(result: ChatResult): Promise<T>;
21
22
/** Parse with prompt value context */
23
parseResultWithPrompt(result: ChatResult, prompt: BasePromptValue): Promise<T>;
24
25
/** Get format instructions for the LLM */
26
getFormatInstructions(): string;
27
28
/** Get parser type for serialization */
29
_type(): string;
30
}
31
```
32
33
### String Output Parser
34
35
Simple parser that extracts string content from messages or text.
36
37
```typescript { .api }
38
/**
39
* Parser that extracts string content
40
*/
41
class StringOutputParser extends BaseOutputParser<string> {
42
/** Parse text to string (identity function) */
43
async parse(text: string): Promise<string>;
44
45
/** Extract text content from chat result */
46
parseResult(result: ChatResult): Promise<string>;
47
48
/** No special format instructions needed */
49
getFormatInstructions(): string;
50
}
51
```
52
53
**Usage Examples:**
54
55
```typescript
56
import { StringOutputParser } from "@langchain/core/output_parsers";
57
58
const parser = new StringOutputParser();
59
60
// Parse plain text
61
const result1 = await parser.parse("Hello, world!"); // "Hello, world!"
62
63
// Use in a chain
64
import { ChatPromptTemplate } from "@langchain/core/prompts";
65
66
const prompt = ChatPromptTemplate.fromTemplate("Tell me a joke about {topic}");
67
const chain = prompt.pipe(model).pipe(parser);
68
69
const joke = await chain.invoke({ topic: "programming" }); // Returns string
70
```
71
72
### JSON Output Parser
73
74
Parser for JSON-formatted responses with schema validation.
75
76
```typescript { .api }
77
/**
78
* Parser for JSON responses with optional schema validation
79
* @template T - Type of parsed JSON object
80
*/
81
class JSONOutputParser<T = Record<string, unknown>> extends BaseOutputParser<T> {
82
/** Optional Zod schema for validation */
83
schema?: z.ZodSchema<T>;
84
85
constructor(schema?: z.ZodSchema<T>);
86
87
/** Parse JSON string to object */
88
async parse(text: string): Promise<T>;
89
90
/** Get JSON format instructions */
91
getFormatInstructions(): string;
92
}
93
```
94
95
**Usage Examples:**
96
97
```typescript
98
import { JSONOutputParser } from "@langchain/core/output_parsers";
99
import { z } from "zod";
100
101
// Without schema
102
const jsonParser = new JSONOutputParser();
103
const result = await jsonParser.parse('{"name": "John", "age": 30}');
104
105
// With schema validation
106
const schema = z.object({
107
name: z.string(),
108
age: z.number(),
109
email: z.string().email()
110
});
111
112
const validatingParser = new JSONOutputParser(schema);
113
const validResult = await validatingParser.parse('{"name": "John", "age": 30, "email": "john@example.com"}');
114
115
// Get format instructions
116
console.log(validatingParser.getFormatInstructions());
117
// "Respond with a valid JSON object..."
118
```
119
120
### Structured Output Parser
121
122
Parser using Zod schemas for structured data extraction.
123
124
```typescript { .api }
125
/**
126
* Parser using Zod schemas for structured output
127
* @template T - Zod schema type
128
*/
129
class StructuredOutputParser<T extends z.ZodSchema> extends BaseOutputParser<z.infer<T>> {
130
/** Zod schema for validation */
131
schema: T;
132
133
constructor(schema: T);
134
135
/** Parse and validate against schema */
136
async parse(text: string): Promise<z.infer<T>>;
137
138
/** Get format instructions based on schema */
139
getFormatInstructions(): string;
140
141
/** Create from Zod schema */
142
static fromZodSchema<T extends z.ZodSchema>(schema: T): StructuredOutputParser<T>;
143
144
/** Create from names and descriptions */
145
static fromNamesAndDescriptions<T extends Record<string, string>>(schemas: T): StructuredOutputParser<z.ZodSchema>;
146
}
147
```
148
149
**Usage Examples:**
150
151
```typescript
152
import { StructuredOutputParser } from "@langchain/core/output_parsers";
153
import { z } from "zod";
154
155
// Define schema
156
const personSchema = z.object({
157
name: z.string().describe("Person's full name"),
158
age: z.number().describe("Person's age in years"),
159
occupation: z.string().describe("Person's job title"),
160
skills: z.array(z.string()).describe("List of skills")
161
});
162
163
const parser = StructuredOutputParser.fromZodSchema(personSchema);
164
165
// Use in prompt
166
const prompt = ChatPromptTemplate.fromTemplate(`
167
Extract information about the person from this text: {text}
168
169
{format_instructions}
170
`);
171
172
const chain = prompt.pipe(model).pipe(parser);
173
174
const person = await chain.invoke({
175
text: "John Smith is a 30-year-old software engineer who knows Python, JavaScript, and TypeScript.",
176
format_instructions: parser.getFormatInstructions()
177
});
178
179
console.log(person);
180
// { name: "John Smith", age: 30, occupation: "software engineer", skills: ["Python", "JavaScript", "TypeScript"] }
181
```
182
183
### Comma Separated List Parser
184
185
Parser for comma-separated values.
186
187
```typescript { .api }
188
/**
189
* Parser for comma-separated lists
190
*/
191
class CommaSeparatedListOutputParser extends BaseOutputParser<string[]> {
192
/** Parse comma-separated string to array */
193
async parse(text: string): Promise<string[]>;
194
195
/** Get format instructions */
196
getFormatInstructions(): string;
197
}
198
```
199
200
**Usage Examples:**
201
202
```typescript
203
import { CommaSeparatedListOutputParser } from "@langchain/core/output_parsers";
204
205
const parser = new CommaSeparatedListOutputParser();
206
207
const result = await parser.parse("apple, banana, orange, grape");
208
console.log(result); // ["apple", "banana", "orange", "grape"]
209
210
// Use in chain
211
const prompt = ChatPromptTemplate.fromTemplate(`
212
List 5 {category} items:
213
214
{format_instructions}
215
`);
216
217
const chain = prompt.pipe(model).pipe(parser);
218
const fruits = await chain.invoke({
219
category: "fruits",
220
format_instructions: parser.getFormatInstructions()
221
}); // Returns string[]
222
```
223
224
### Regex Parser
225
226
Parser using regular expressions for pattern extraction.
227
228
```typescript { .api }
229
/**
230
* Parser using regex patterns for extraction
231
*/
232
class RegexParser extends BaseOutputParser<Record<string, string>> {
233
/** Regex pattern with named groups */
234
regex: RegExp;
235
/** Output keys from regex groups */
236
outputKeys: string[];
237
/** Default value if no match */
238
defaultOutputKey?: string;
239
240
constructor(regex: RegExp, outputKeys: string[], defaultOutputKey?: string);
241
242
/** Parse using regex pattern */
243
async parse(text: string): Promise<Record<string, string>>;
244
}
245
```
246
247
**Usage Examples:**
248
249
```typescript
250
import { RegexParser } from "@langchain/core/output_parsers";
251
252
// Extract name and age from text
253
const parser = new RegexParser(
254
/Name:\s*(?<name>.*?)\s*Age:\s*(?<age>\d+)/i,
255
["name", "age"]
256
);
257
258
const result = await parser.parse("Name: John Smith Age: 30");
259
console.log(result); // { name: "John Smith", age: "30" }
260
```
261
262
### Combining Parsers
263
264
Parser for handling complex nested structures.
265
266
```typescript { .api }
267
/**
268
* Parser that combines multiple parsers
269
*/
270
class CombiningOutputParser extends BaseOutputParser<Record<string, unknown>> {
271
/** Map of parser names to parsers */
272
parsers: Record<string, BaseOutputParser>;
273
274
constructor(parsers: Record<string, BaseOutputParser>);
275
276
/** Parse using all constituent parsers */
277
async parse(text: string): Promise<Record<string, unknown>>;
278
}
279
```
280
281
## Error Handling
282
283
### Output Parser Exception
284
285
```typescript { .api }
286
/**
287
* Exception thrown when parsing fails
288
*/
289
class OutputParserException extends Error {
290
/** The text that failed to parse */
291
observation: string;
292
/** The LLM output that caused the error */
293
llmOutput?: string;
294
/** Flag indicating this is a parser error */
295
sendToLLM: boolean;
296
297
constructor(message: string, observation: string, llmOutput?: string, sendToLLM?: boolean);
298
}
299
```
300
301
## Types
302
303
```typescript { .api }
304
interface BaseOutputParserInput {
305
/** Optional schema for validation */
306
schema?: z.ZodSchema;
307
}
308
309
type OutputParserLike<T = unknown> = BaseOutputParser<T> | ((text: string) => T | Promise<T>);
310
311
interface ParseResult<T> {
312
/** Parsed output */
313
output: T;
314
/** Whether parsing was successful */
315
success: boolean;
316
/** Any error that occurred */
317
error?: Error;
318
}
319
```