or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

agents.mdchains.mddocument-loaders.mdembeddings.mdexperimental.mdindex.mdmemory.mdoutput-parsers.mdretrievers.mdtools.mdutilities.md
tile.json

output-parsers.mddocs/

0

# Output Parsers

1

2

Components for extracting and structuring data from language model outputs, including JSON parsing, list extraction, and custom formats. Output parsers transform raw LLM text into structured, usable data.

3

4

## Capabilities

5

6

### Base Output Parser

7

8

Foundation class for all output parsers with standardized interfaces.

9

10

```typescript { .api }

11

/**

12

* Base output parser class - all parsers inherit from this

13

*/

14

abstract class BaseOutputParser<T = unknown> extends Runnable<string, T> {

15

/** Parse string output into structured format */

16

abstract parse(text: string): Promise<T>;

17

18

/** Get format instructions for the LLM */

19

abstract getFormatInstructions(): string;

20

21

/** Parse with prompt value input */

22

parseWithPrompt(text: string, prompt: BasePromptValueInterface): Promise<T>;

23

24

/** Invoke the parser (Runnable interface) */

25

invoke(input: string, options?: RunnableConfig): Promise<T>;

26

27

/** Stream parsing results */

28

stream(input: string, options?: RunnableConfig): AsyncGenerator<T>;

29

30

/** Parse result with error handling */

31

parseResult(result: Generation[]): Promise<T>;

32

33

/** Get parser type identifier */

34

_type(): string;

35

}

36

37

/**

38

* Transform output parser that applies a transformation function

39

*/

40

class TransformOutputParser<T, U> extends BaseOutputParser<U> {

41

constructor(fields: {

42

parser: BaseOutputParser<T>;

43

transform: (value: T) => U | Promise<U>;

44

});

45

46

/** Base parser to transform output from */

47

parser: BaseOutputParser<T>;

48

49

/** Transformation function */

50

transform: (value: T) => U | Promise<U>;

51

52

parse(text: string): Promise<U>;

53

getFormatInstructions(): string;

54

}

55

```

56

57

### Structured Output Parsers

58

59

Parsers for extracting structured data with schema validation.

60

61

```typescript { .api }

62

/**

63

* Structured output parser with schema validation

64

*/

65

class StructuredOutputParser<T> extends BaseOutputParser<T> {

66

constructor(schema: ZodSchema<T>);

67

68

/** Zod schema for validation */

69

schema: ZodSchema<T>;

70

71

parse(text: string): Promise<T>;

72

73

getFormatInstructions(): string;

74

75

/** Create from Zod schema */

76

static fromZodSchema<T>(schema: ZodSchema<T>): StructuredOutputParser<T>;

77

78

/** Create from field names and descriptions */

79

static fromNamesAndDescriptions<T>(schemas: Record<string, string>): StructuredOutputParser<T>;

80

}

81

82

/**

83

* Asymmetric structured parser for different input/output schemas

84

*/

85

class AsymmetricStructuredOutputParser<T, U = T> extends BaseOutputParser<U> {

86

constructor(fields: {

87

inputSchema: ZodSchema<T>;

88

outputSchema: ZodSchema<U>;

89

outputTransformer?: (input: T) => U;

90

});

91

92

/** Input validation schema */

93

inputSchema: ZodSchema<T>;

94

95

/** Output validation schema */

96

outputSchema: ZodSchema<U>;

97

98

/** Optional transformation function */

99

outputTransformer?: (input: T) => U;

100

101

parse(text: string): Promise<U>;

102

getFormatInstructions(): string;

103

}

104

105

/**

106

* JSON markdown structured parser for code blocks

107

*/

108

class JsonMarkdownStructuredOutputParser<T> extends BaseOutputParser<T> {

109

constructor(schema: ZodSchema<T>);

110

111

/** Zod schema for validation */

112

schema: ZodSchema<T>;

113

114

parse(text: string): Promise<T>;

115

getFormatInstructions(): string;

116

117

static fromZodSchema<T>(schema: ZodSchema<T>): JsonMarkdownStructuredOutputParser<T>;

118

}

119

```

120

121

**Usage Examples:**

122

123

```typescript

124

import { StructuredOutputParser } from "langchain/output_parsers";

125

import { z } from "zod";

126

127

// Define schema for person data

128

const personSchema = z.object({

129

name: z.string().describe("The person's full name"),

130

age: z.number().describe("The person's age"),

131

occupation: z.string().describe("The person's job"),

132

interests: z.array(z.string()).describe("List of hobbies and interests"),

133

});

134

135

// Create parser from schema

136

const parser = StructuredOutputParser.fromZodSchema(personSchema);

137

138

// Get format instructions for the prompt

139

const formatInstructions = parser.getFormatInstructions();

140

console.log(formatInstructions);

141

// Outputs: Respond with a JSON object containing the following fields:

142

// - name: The person's full name

143

// - age: The person's age

144

// - occupation: The person's job

145

// - interests: List of hobbies and interests

146

147

// Parse LLM output

148

const llmOutput = `{

149

"name": "Alice Johnson",

150

"age": 28,

151

"occupation": "Software Engineer",

152

"interests": ["reading", "hiking", "programming"]

153

}`;

154

155

const parsed = await parser.parse(llmOutput);

156

console.log(parsed);

157

// Result: { name: "Alice Johnson", age: 28, occupation: "Software Engineer", interests: [...] }

158

```

159

160

### List Output Parsers

161

162

Parsers specialized for extracting lists and arrays from text.

163

164

```typescript { .api }

165

/**

166

* Generic list output parser

167

*/

168

class ListOutputParser extends BaseOutputParser<string[]> {

169

constructor(fields?: { lengthLimit?: number });

170

171

/** Maximum number of items to parse */

172

lengthLimit?: number;

173

174

parse(text: string): Promise<string[]>;

175

getFormatInstructions(): string;

176

}

177

178

/**

179

* Comma-separated list parser

180

*/

181

class CommaSeparatedListOutputParser extends ListOutputParser {

182

constructor();

183

184

parse(text: string): Promise<string[]>;

185

getFormatInstructions(): string;

186

}

187

188

/**

189

* Custom list parser with configurable separator

190

*/

191

class CustomListOutputParser extends ListOutputParser {

192

constructor(fields?: {

193

separator?: string;

194

lengthLimit?: number;

195

});

196

197

/** Separator string for list items */

198

separator: string;

199

200

parse(text: string): Promise<string[]>;

201

getFormatInstructions(): string;

202

}

203

```

204

205

**Usage Examples:**

206

207

```typescript

208

import {

209

CommaSeparatedListOutputParser,

210

CustomListOutputParser

211

} from "langchain/output_parsers";

212

213

// Comma-separated list parser

214

const commaParser = new CommaSeparatedListOutputParser();

215

216

const commaList = await commaParser.parse("apple, banana, orange, grape");

217

console.log(commaList); // ["apple", "banana", "orange", "grape"]

218

219

// Custom separator parser

220

const pipeParser = new CustomListOutputParser({ separator: " | " });

221

222

const pipeList = await pipeParser.parse("red | blue | green | yellow");

223

console.log(pipeList); // ["red", "blue", "green", "yellow"]

224

225

// Get format instructions

226

console.log(commaParser.getFormatInstructions());

227

// "Your response should be a list of comma separated values, eg: `foo, bar, baz`"

228

```

229

230

### Regex and Pattern Parsers

231

232

Parsers that use regular expressions for extraction.

233

234

```typescript { .api }

235

/**

236

* Regex-based output parser

237

*/

238

class RegexParser extends BaseOutputParser<Record<string, string>> {

239

constructor(

240

regex: string | RegExp,

241

outputKeys: string[],

242

defaultOutputKey?: string

243

);

244

245

/** Regular expression pattern */

246

regex: RegExp;

247

248

/** Names of capture groups */

249

outputKeys: string[];

250

251

/** Default key if no matches */

252

defaultOutputKey?: string;

253

254

parse(text: string): Promise<Record<string, string>>;

255

getFormatInstructions(): string;

256

}

257

258

/**

259

* Datetime parser for extracting dates and times

260

*/

261

class DatetimeOutputParser extends BaseOutputParser<Date> {

262

constructor(format?: string);

263

264

/** Date format string */

265

format?: string;

266

267

parse(text: string): Promise<Date>;

268

getFormatInstructions(): string;

269

}

270

```

271

272

**Usage Example:**

273

274

```typescript

275

import { RegexParser, DatetimeOutputParser } from "langchain/output_parsers";

276

277

// Extract structured data with regex

278

const regexParser = new RegexParser(

279

/Name: (.*)\nAge: (\d+)\nCity: (.*)/,

280

["name", "age", "city"]

281

);

282

283

const regexOutput = `Name: Bob Smith

284

Age: 35

285

City: New York`;

286

287

const regexResult = await regexParser.parse(regexOutput);

288

console.log(regexResult);

289

// { name: "Bob Smith", age: "35", city: "New York" }

290

291

// Parse datetime

292

const dateParser = new DatetimeOutputParser();

293

const dateResult = await dateParser.parse("The meeting is on 2024-03-15");

294

console.log(dateResult); // Date object for March 15, 2024

295

```

296

297

### Function Call Parsers

298

299

Parsers for OpenAI function calling outputs and tool results.

300

301

```typescript { .api }

302

/**

303

* Parser for OpenAI function outputs

304

*/

305

class OutputFunctionsParser extends BaseOutputParser<Record<string, any>> {

306

constructor(config?: { argsOnly?: boolean });

307

308

/** Return only function arguments */

309

argsOnly: boolean;

310

311

parse(text: string): Promise<Record<string, any>>;

312

parseResult(result: Generation[]): Promise<Record<string, any>>;

313

getFormatInstructions(): string;

314

}

315

316

/**

317

* JSON parser for function outputs

318

*/

319

class JsonOutputFunctionsParser extends BaseOutputParser<Record<string, any>> {

320

constructor(config?: { argsOnly?: boolean });

321

322

/** Return only function arguments */

323

argsOnly: boolean;

324

325

parse(text: string): Promise<Record<string, any>>;

326

parseResult(result: Generation[]): Promise<Record<string, any>>;

327

getFormatInstructions(): string;

328

}

329

330

/**

331

* Parser for specific function key outputs

332

*/

333

class JsonKeyOutputFunctionsParser extends BaseOutputParser<any> {

334

constructor(fields: { keyName: string; argsOnly?: boolean });

335

336

/** Key name to extract */

337

keyName: string;

338

339

/** Return only function arguments */

340

argsOnly: boolean;

341

342

parse(text: string): Promise<any>;

343

parseResult(result: Generation[]): Promise<any>;

344

getFormatInstructions(): string;

345

}

346

347

/**

348

* Parser for tool outputs

349

*/

350

class JsonOutputToolsParser extends BaseOutputParser<Record<string, any>[]> {

351

constructor(config?: { returnSingle?: boolean });

352

353

/** Return single result instead of array */

354

returnSingle: boolean;

355

356

parse(text: string): Promise<Record<string, any>[]>;

357

parseResult(result: Generation[]): Promise<Record<string, any>[]>;

358

getFormatInstructions(): string;

359

}

360

361

/**

362

* Parser for tool key outputs

363

*/

364

class JsonOutputKeyToolsParser extends BaseOutputParser<any> {

365

constructor(fields: {

366

keyName: string;

367

returnSingle?: boolean;

368

});

369

370

/** Key name to extract from tool outputs */

371

keyName: string;

372

373

/** Return single result instead of array */

374

returnSingle: boolean;

375

376

parse(text: string): Promise<any>;

377

parseResult(result: Generation[]): Promise<any>;

378

getFormatInstructions(): string;

379

}

380

```

381

382

### Combining and Error-Handling Parsers

383

384

Parsers for combining multiple parsers and handling errors gracefully.

385

386

```typescript { .api }

387

/**

388

* Parser that combines multiple output parsers

389

*/

390

class CombiningOutputParser extends BaseOutputParser<Record<string, any>> {

391

constructor(

392

parsers: Record<string, BaseOutputParser>,

393

defaultParser?: BaseOutputParser

394

);

395

396

/** Map of parser names to parsers */

397

parsers: Record<string, BaseOutputParser>;

398

399

/** Default parser if no specific parser matches */

400

defaultParser?: BaseOutputParser;

401

402

parse(text: string): Promise<Record<string, any>>;

403

getFormatInstructions(): string;

404

}

405

406

/**

407

* Parser that routes to different parsers based on conditions

408

*/

409

class RouterOutputParser extends BaseOutputParser<any> {

410

constructor(fields: {

411

defaultParser: BaseOutputParser;

412

parsers: BaseOutputParser[];

413

routerChain: RouterChain;

414

});

415

416

/** Default parser to use */

417

defaultParser: BaseOutputParser;

418

419

/** Available parsers to route to */

420

parsers: BaseOutputParser[];

421

422

/** Chain that decides which parser to use */

423

routerChain: RouterChain;

424

425

parse(text: string): Promise<any>;

426

getFormatInstructions(): string;

427

}

428

429

/**

430

* Parser that attempts to fix malformed outputs using an LLM

431

*/

432

class OutputFixingParser<T> extends BaseOutputParser<T> {

433

constructor(fields: {

434

parser: BaseOutputParser<T>;

435

retryChain: LLMChain;

436

});

437

438

/** Original parser to attempt first */

439

parser: BaseOutputParser<T>;

440

441

/** Chain to fix parsing errors */

442

retryChain: LLMChain;

443

444

parse(text: string): Promise<T>;

445

446

/** Parse with completion fallback */

447

parseWithPrompt(text: string, prompt: BasePromptValueInterface): Promise<T>;

448

449

getFormatInstructions(): string;

450

451

static fromLLM<T>(

452

llm: BaseLanguageModelInterface,

453

parser: BaseOutputParser<T>,

454

fields?: Partial<OutputFixingParserInput>

455

): OutputFixingParser<T>;

456

}

457

```

458

459

### HTTP Response Parser

460

461

Parser for processing HTTP response data.

462

463

```typescript { .api }

464

/**

465

* Parser for HTTP response content

466

*/

467

class HttpResponseOutputParser extends BaseOutputParser<Uint8Array> {

468

constructor(fields?: {

469

outputParser?: BaseOutputParser;

470

contentType?: string;

471

});

472

473

/** Optional parser for response content */

474

outputParser?: BaseOutputParser;

475

476

/** Expected content type */

477

contentType?: string;

478

479

parse(text: string): Promise<Uint8Array>;

480

parseResult(result: Generation[]): Promise<Uint8Array>;

481

getFormatInstructions(): string;

482

}

483

```

484

485

### Expression Parsers

486

487

Parsers for mathematical and logical expressions.

488

489

```typescript { .api }

490

/**

491

* Parser for mathematical expressions

492

*/

493

class MathExpressionParser extends BaseOutputParser<number> {

494

constructor();

495

496

parse(text: string): Promise<number>;

497

getFormatInstructions(): string;

498

}

499

500

/**

501

* Parser for boolean expressions

502

*/

503

class BooleanExpressionParser extends BaseOutputParser<boolean> {

504

constructor();

505

506

parse(text: string): Promise<boolean>;

507

getFormatInstructions(): string;

508

}

509

```

510

511

## Types

512

513

### Base Parser Types

514

515

```typescript { .api }

516

interface BaseOutputParserInput {

517

/** Additional parsing options */

518

options?: Record<string, any>;

519

}

520

521

interface TransformOutputParserInput<T, U> {

522

/** Base parser to transform */

523

parser: BaseOutputParser<T>;

524

/** Transformation function */

525

transform: (value: T) => U | Promise<U>;

526

}

527

```

528

529

### Structured Parser Types

530

531

```typescript { .api }

532

interface StructuredOutputParserInput<T> {

533

/** Zod schema for validation */

534

schema: ZodSchema<T>;

535

}

536

537

interface AsymmetricStructuredOutputParserInput<T, U> {

538

/** Input validation schema */

539

inputSchema: ZodSchema<T>;

540

/** Output validation schema */

541

outputSchema: ZodSchema<U>;

542

/** Optional transformation function */

543

outputTransformer?: (input: T) => U;

544

}

545

```

546

547

### List Parser Types

548

549

```typescript { .api }

550

interface ListOutputParserInput {

551

/** Maximum number of items to parse */

552

lengthLimit?: number;

553

}

554

555

interface CustomListOutputParserInput extends ListOutputParserInput {

556

/** Separator string for list items */

557

separator?: string;

558

}

559

```

560

561

### Function Call Parser Types

562

563

```typescript { .api }

564

interface OutputFunctionsParserInput {

565

/** Return only function arguments */

566

argsOnly?: boolean;

567

}

568

569

interface JsonKeyOutputFunctionsParserInput {

570

/** Key name to extract */

571

keyName: string;

572

/** Return only function arguments */

573

argsOnly?: boolean;

574

}

575

576

interface JsonOutputToolsParserInput {

577

/** Return single result instead of array */

578

returnSingle?: boolean;

579

}

580

581

interface JsonOutputKeyToolsParserInput {

582

/** Key name to extract from tool outputs */

583

keyName: string;

584

/** Return single result instead of array */

585

returnSingle?: boolean;

586

}

587

```

588

589

### Combining Parser Types

590

591

```typescript { .api }

592

interface CombiningOutputParserInput {

593

/** Map of parser names to parsers */

594

parsers: Record<string, BaseOutputParser>;

595

/** Default parser if no specific parser matches */

596

defaultParser?: BaseOutputParser;

597

}

598

599

interface RouterOutputParserInput {

600

/** Default parser to use */

601

defaultParser: BaseOutputParser;

602

/** Available parsers to route to */

603

parsers: BaseOutputParser[];

604

/** Chain that decides which parser to use */

605

routerChain: RouterChain;

606

}

607

608

interface OutputFixingParserInput {

609

/** Original parser to attempt first */

610

parser: BaseOutputParser<any>;

611

/** Chain to fix parsing errors */

612

retryChain: LLMChain;

613

}

614

```

615

616

### Regex Parser Types

617

618

```typescript { .api }

619

interface RegexParserInput {

620

/** Regular expression pattern */

621

regex: string | RegExp;

622

/** Names of capture groups */

623

outputKeys: string[];

624

/** Default key if no matches */

625

defaultOutputKey?: string;

626

}

627

628

interface DatetimeOutputParserInput {

629

/** Date format string */

630

format?: string;

631

}

632

```

633

634

### HTTP Parser Types

635

636

```typescript { .api }

637

interface HttpResponseOutputParserInput {

638

/** Optional parser for response content */

639

outputParser?: BaseOutputParser;

640

/** Expected content type */

641

contentType?: string;

642

}

643

```

644

645

## Parser Usage Patterns

646

647

### Chain Integration

648

649

```typescript

650

import { LLMChain } from "langchain/chains";

651

import { StructuredOutputParser } from "langchain/output_parsers";

652

import { PromptTemplate } from "@langchain/core/prompts";

653

import { OpenAI } from "@langchain/openai";

654

import { z } from "zod";

655

656

const llm = new OpenAI({ temperature: 0 });

657

658

// Define output schema

659

const schema = z.object({

660

sentiment: z.enum(["positive", "negative", "neutral"]),

661

confidence: z.number().min(0).max(1),

662

keywords: z.array(z.string()),

663

});

664

665

const parser = StructuredOutputParser.fromZodSchema(schema);

666

667

// Create prompt with format instructions

668

const prompt = PromptTemplate.fromTemplate(`

669

Analyze the sentiment of the following text:

670

{text}

671

672

{format_instructions}

673

`);

674

675

const chain = new LLMChain({

676

llm,

677

prompt,

678

outputParser: parser,

679

});

680

681

const result = await chain.call({

682

text: "I love this new product! It works perfectly.",

683

format_instructions: parser.getFormatInstructions(),

684

});

685

686

console.log(result);

687

// { sentiment: "positive", confidence: 0.95, keywords: ["love", "perfect"] }

688

```

689

690

### Error Recovery

691

692

```typescript

693

import { OutputFixingParser, StructuredOutputParser } from "langchain/output_parsers";

694

import { LLMChain } from "langchain/chains";

695

696

// Create base parser

697

const baseParser = StructuredOutputParser.fromZodSchema(schema);

698

699

// Create fixing parser with retry logic

700

const fixingParser = OutputFixingParser.fromLLM(llm, baseParser);

701

702

// This will attempt to fix malformed JSON automatically

703

const result = await fixingParser.parse(`{

704

"sentiment": "positive",

705

"confidence": 0.95,

706

"keywords": ["love", "perfect" // Missing closing bracket

707

}`);

708

```

709

710

### Custom Parser Implementation

711

712

```typescript

713

class CSVParser extends BaseOutputParser<Array<Record<string, string>>> {

714

constructor(private headers: string[]) {

715

super();

716

}

717

718

async parse(text: string): Promise<Array<Record<string, string>>> {

719

const lines = text.trim().split('\n');

720

const dataLines = lines.slice(1); // Skip header

721

722

return dataLines.map(line => {

723

const values = line.split(',');

724

const record: Record<string, string> = {};

725

726

this.headers.forEach((header, index) => {

727

record[header] = values[index]?.trim() || '';

728

});

729

730

return record;

731

});

732

}

733

734

getFormatInstructions(): string {

735

return `Please format your response as a CSV with headers: ${this.headers.join(', ')}`;

736

}

737

}

738

739

const csvParser = new CSVParser(['name', 'age', 'city']);

740

const csvResult = await csvParser.parse(`name,age,city

741

Alice,25,New York

742

Bob,30,Los Angeles`);

743

```