Core LangChain.js abstractions and schemas for building applications with Large Language Models
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Structured output parsing for converting LLM responses into typed data structures. Output parsers transform raw text or message outputs into usable formats.
Abstract base class for all output parsers.
/**
* Abstract base class for parsing LLM outputs
* @template T - Type of parsed output
*/
abstract class BaseOutputParser<T = unknown> extends Runnable<string | BaseMessage, T> {
/** Parse text string to structured output */
abstract parse(text: string): Promise<T>;
/** Parse from chat result */
parseResult(result: ChatResult): Promise<T>;
/** Parse with prompt value context */
parseResultWithPrompt(result: ChatResult, prompt: BasePromptValue): Promise<T>;
/** Get format instructions for the LLM */
getFormatInstructions(): string;
/** Get parser type for serialization */
_type(): string;
}Simple parser that extracts string content from messages or text.
/**
* Parser that extracts string content
*/
class StringOutputParser extends BaseOutputParser<string> {
/** Parse text to string (identity function) */
async parse(text: string): Promise<string>;
/** Extract text content from chat result */
parseResult(result: ChatResult): Promise<string>;
/** No special format instructions needed */
getFormatInstructions(): string;
}Usage Examples:
import { StringOutputParser } from "@langchain/core/output_parsers";
const parser = new StringOutputParser();
// Parse plain text
const result1 = await parser.parse("Hello, world!"); // "Hello, world!"
// Use in a chain
import { ChatPromptTemplate } from "@langchain/core/prompts";
const prompt = ChatPromptTemplate.fromTemplate("Tell me a joke about {topic}");
const chain = prompt.pipe(model).pipe(parser);
const joke = await chain.invoke({ topic: "programming" }); // Returns stringParser for JSON-formatted responses with schema validation.
/**
* Parser for JSON responses with optional schema validation
* @template T - Type of parsed JSON object
*/
class JSONOutputParser<T = Record<string, unknown>> extends BaseOutputParser<T> {
/** Optional Zod schema for validation */
schema?: z.ZodSchema<T>;
constructor(schema?: z.ZodSchema<T>);
/** Parse JSON string to object */
async parse(text: string): Promise<T>;
/** Get JSON format instructions */
getFormatInstructions(): string;
}Usage Examples:
import { JSONOutputParser } from "@langchain/core/output_parsers";
import { z } from "zod";
// Without schema
const jsonParser = new JSONOutputParser();
const result = await jsonParser.parse('{"name": "John", "age": 30}');
// With schema validation
const schema = z.object({
name: z.string(),
age: z.number(),
email: z.string().email()
});
const validatingParser = new JSONOutputParser(schema);
const validResult = await validatingParser.parse('{"name": "John", "age": 30, "email": "john@example.com"}');
// Get format instructions
console.log(validatingParser.getFormatInstructions());
// "Respond with a valid JSON object..."Parser using Zod schemas for structured data extraction.
/**
* Parser using Zod schemas for structured output
* @template T - Zod schema type
*/
class StructuredOutputParser<T extends z.ZodSchema> extends BaseOutputParser<z.infer<T>> {
/** Zod schema for validation */
schema: T;
constructor(schema: T);
/** Parse and validate against schema */
async parse(text: string): Promise<z.infer<T>>;
/** Get format instructions based on schema */
getFormatInstructions(): string;
/** Create from Zod schema */
static fromZodSchema<T extends z.ZodSchema>(schema: T): StructuredOutputParser<T>;
/** Create from names and descriptions */
static fromNamesAndDescriptions<T extends Record<string, string>>(schemas: T): StructuredOutputParser<z.ZodSchema>;
}Usage Examples:
import { StructuredOutputParser } from "@langchain/core/output_parsers";
import { z } from "zod";
// Define schema
const personSchema = z.object({
name: z.string().describe("Person's full name"),
age: z.number().describe("Person's age in years"),
occupation: z.string().describe("Person's job title"),
skills: z.array(z.string()).describe("List of skills")
});
const parser = StructuredOutputParser.fromZodSchema(personSchema);
// Use in prompt
const prompt = ChatPromptTemplate.fromTemplate(`
Extract information about the person from this text: {text}
{format_instructions}
`);
const chain = prompt.pipe(model).pipe(parser);
const person = await chain.invoke({
text: "John Smith is a 30-year-old software engineer who knows Python, JavaScript, and TypeScript.",
format_instructions: parser.getFormatInstructions()
});
console.log(person);
// { name: "John Smith", age: 30, occupation: "software engineer", skills: ["Python", "JavaScript", "TypeScript"] }Parser for comma-separated values.
/**
* Parser for comma-separated lists
*/
class CommaSeparatedListOutputParser extends BaseOutputParser<string[]> {
/** Parse comma-separated string to array */
async parse(text: string): Promise<string[]>;
/** Get format instructions */
getFormatInstructions(): string;
}Usage Examples:
import { CommaSeparatedListOutputParser } from "@langchain/core/output_parsers";
const parser = new CommaSeparatedListOutputParser();
const result = await parser.parse("apple, banana, orange, grape");
console.log(result); // ["apple", "banana", "orange", "grape"]
// Use in chain
const prompt = ChatPromptTemplate.fromTemplate(`
List 5 {category} items:
{format_instructions}
`);
const chain = prompt.pipe(model).pipe(parser);
const fruits = await chain.invoke({
category: "fruits",
format_instructions: parser.getFormatInstructions()
}); // Returns string[]Parser using regular expressions for pattern extraction.
/**
* Parser using regex patterns for extraction
*/
class RegexParser extends BaseOutputParser<Record<string, string>> {
/** Regex pattern with named groups */
regex: RegExp;
/** Output keys from regex groups */
outputKeys: string[];
/** Default value if no match */
defaultOutputKey?: string;
constructor(regex: RegExp, outputKeys: string[], defaultOutputKey?: string);
/** Parse using regex pattern */
async parse(text: string): Promise<Record<string, string>>;
}Usage Examples:
import { RegexParser } from "@langchain/core/output_parsers";
// Extract name and age from text
const parser = new RegexParser(
/Name:\s*(?<name>.*?)\s*Age:\s*(?<age>\d+)/i,
["name", "age"]
);
const result = await parser.parse("Name: John Smith Age: 30");
console.log(result); // { name: "John Smith", age: "30" }Parser for handling complex nested structures.
/**
* Parser that combines multiple parsers
*/
class CombiningOutputParser extends BaseOutputParser<Record<string, unknown>> {
/** Map of parser names to parsers */
parsers: Record<string, BaseOutputParser>;
constructor(parsers: Record<string, BaseOutputParser>);
/** Parse using all constituent parsers */
async parse(text: string): Promise<Record<string, unknown>>;
}/**
* Exception thrown when parsing fails
*/
class OutputParserException extends Error {
/** The text that failed to parse */
observation: string;
/** The LLM output that caused the error */
llmOutput?: string;
/** Flag indicating this is a parser error */
sendToLLM: boolean;
constructor(message: string, observation: string, llmOutput?: string, sendToLLM?: boolean);
}interface BaseOutputParserInput {
/** Optional schema for validation */
schema?: z.ZodSchema;
}
type OutputParserLike<T = unknown> = BaseOutputParser<T> | ((text: string) => T | Promise<T>);
interface ParseResult<T> {
/** Parsed output */
output: T;
/** Whether parsing was successful */
success: boolean;
/** Any error that occurred */
error?: Error;
}