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

chains.mddocs/

0

# Chains and Document Processing

1

2

Sequences of operations for processing documents, question answering, summarization, and complex multi-step reasoning workflows. Chains orchestrate calls between language models, retrievers, and other components.

3

4

## Capabilities

5

6

### Base Chain Classes

7

8

Foundation classes for creating custom chains and understanding chain behavior.

9

10

```typescript { .api }

11

/**

12

* Base class for all chains

13

*/

14

abstract class BaseChain extends Runnable implements ChainInputs {

15

constructor(fields?: ChainInputs);

16

17

/** Main entry point for chain execution */

18

abstract _call(values: ChainValues, runManager?: CallbackManagerForChainRun): Promise<ChainValues>;

19

20

/** Call the chain with input values */

21

call(values: ChainValues, config?: RunnableConfig): Promise<ChainValues>;

22

23

/** Run the chain (alias for call) */

24

run(input: any, config?: RunnableConfig): Promise<string>;

25

26

/** Invoke the chain with input */

27

invoke(input: ChainInputs, options?: Partial<RunnableConfig>): Promise<ChainValues>;

28

29

/** Stream chain execution */

30

stream(input: ChainInputs, options?: Partial<RunnableConfig>): AsyncGenerator<ChainValues>;

31

32

/** Apply the chain to multiple inputs */

33

apply(inputs: ChainValues[], config?: (RunnableConfig | undefined)[]): Promise<ChainValues[]>;

34

35

/** Get input keys required by the chain */

36

get inputKeys(): string[];

37

38

/** Get output keys produced by the chain */

39

get outputKeys(): string[];

40

}

41

42

/**

43

* Chain for LLM operations

44

*/

45

class LLMChain extends BaseChain {

46

constructor(fields: LLMChainInput);

47

48

/** The language model instance */

49

llm: BaseLanguageModelInterface;

50

51

/** The prompt template */

52

prompt: BasePromptTemplate;

53

54

/** Optional output parser */

55

outputParser?: BaseOutputParser;

56

57

/** Key to use for LLM output */

58

outputKey: string;

59

60

_call(values: ChainValues): Promise<ChainValues>;

61

62

/** Create prediction with just input text */

63

predict(values: Record<string, any>): Promise<string>;

64

65

/** Create prediction and return LLM result */

66

predictAndParse(values: Record<string, any>): Promise<any>;

67

}

68

69

/**

70

* Conversation chain for maintaining chat context

71

*/

72

class ConversationChain extends LLMChain {

73

constructor(fields: ConversationChainInput);

74

75

/** Memory instance for conversation context */

76

memory: BaseMemory;

77

78

/** Key for input in conversation */

79

inputKey: string;

80

81

/** Key for output in conversation */

82

outputKey: string;

83

84

_call(values: ChainValues): Promise<ChainValues>;

85

86

static fromLLM(

87

llm: BaseLanguageModelInterface,

88

memory?: BaseMemory,

89

options?: Partial<ConversationChainInput>

90

): ConversationChain;

91

}

92

```

93

94

**Usage Example:**

95

96

```typescript

97

import { LLMChain } from "langchain/chains";

98

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

99

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

100

101

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

102

const prompt = PromptTemplate.fromTemplate(

103

"What are the key points about {topic}?"

104

);

105

106

const chain = new LLMChain({

107

llm: model,

108

prompt,

109

verbose: true

110

});

111

112

const result = await chain.call({ topic: "quantum computing" });

113

console.log(result.text);

114

```

115

116

### Document Processing Chains

117

118

Specialized chains for handling document-based operations like question answering and summarization.

119

120

```typescript { .api }

121

/**

122

* Retrieval-based question answering chain

123

*/

124

class RetrievalQAChain extends BaseChain {

125

constructor(fields: RetrievalQAChainInput);

126

127

/** The retriever for finding relevant documents */

128

retriever: BaseRetrieverInterface;

129

130

/** Chain for combining documents */

131

combineDocumentsChain: BaseChain;

132

133

/** Key for input question */

134

inputKey: string;

135

136

/** Key for output answer */

137

returnSourceDocuments: boolean;

138

139

static fromLLM(

140

llm: BaseLanguageModelInterface,

141

retriever: BaseRetrieverInterface,

142

options?: Partial<RetrievalQAChainInput>

143

): RetrievalQAChain;

144

145

_call(values: ChainValues): Promise<ChainValues>;

146

}

147

148

/**

149

* Conversational retrieval QA with memory

150

*/

151

class ConversationalRetrievalQAChain extends BaseChain {

152

constructor(fields: ConversationalRetrievalQAChainInput);

153

154

/** The retriever for finding relevant documents */

155

retriever: BaseRetrieverInterface;

156

157

/** Chain for combining documents */

158

combineDocumentsChain: BaseChain;

159

160

/** Chain for generating standalone questions */

161

questionGeneratorChain: LLMChain;

162

163

/** Whether to return source documents */

164

returnSourceDocuments: boolean;

165

166

/** Whether to return generated question */

167

returnGeneratedQuestion: boolean;

168

169

static fromLLM(

170

llm: BaseLanguageModelInterface,

171

retriever: BaseRetrieverInterface,

172

options?: Partial<ConversationalRetrievalQAChainInput>

173

): ConversationalRetrievalQAChain;

174

}

175

176

/**

177

* Stuff documents chain - puts all documents into prompt

178

*/

179

class StuffDocumentsChain extends BaseChain {

180

constructor(fields: StuffDocumentsChainInput);

181

182

/** The LLM chain for processing stuffed documents */

183

llmChain: LLMChain;

184

185

/** Variable name for documents in prompt */

186

documentVariableName: string;

187

188

/** Separator between documents */

189

documentSeparator: string;

190

191

_call(values: ChainValues): Promise<ChainValues>;

192

}

193

194

/**

195

* Map-reduce documents chain

196

*/

197

class MapReduceDocumentsChain extends BaseChain {

198

constructor(fields: MapReduceDocumentsChainInput);

199

200

/** Chain for mapping over individual documents */

201

llmChain: LLMChain;

202

203

/** Chain for reducing mapped results */

204

reduceDocumentsChain: BaseChain;

205

206

/** Variable name for documents */

207

documentVariableName: string;

208

209

/** Whether to return intermediate steps */

210

returnIntermediateSteps: boolean;

211

212

_call(values: ChainValues): Promise<ChainValues>;

213

}

214

215

/**

216

* Refine documents chain - iteratively refines answer

217

*/

218

class RefineDocumentsChain extends BaseChain {

219

constructor(fields: RefineDocumentsChainInput);

220

221

/** Initial LLM chain */

222

llmChain: LLMChain;

223

224

/** Refinement LLM chain */

225

refineLLMChain: LLMChain;

226

227

/** Variable name for documents */

228

documentVariableName: string;

229

230

/** Variable name for initial answer */

231

initialResponseName: string;

232

233

/** Whether to return intermediate steps */

234

returnIntermediateSteps: boolean;

235

236

_call(values: ChainValues): Promise<ChainValues>;

237

}

238

239

/**

240

* Analyze document chain for document analysis workflows

241

*/

242

class AnalyzeDocumentChain extends BaseChain {

243

constructor(fields: AnalyzeDocumentChainInput);

244

245

/** Chain for combining documents */

246

combineDocumentsChain: BaseChain;

247

248

/** Text splitter for document processing */

249

textSplitter?: TextSplitter;

250

251

/** Input key for document */

252

inputKey: string;

253

254

/** Output key for analysis result */

255

outputKey: string;

256

257

_call(values: ChainValues): Promise<ChainValues>;

258

}

259

```

260

261

**Usage Example:**

262

263

```typescript

264

import { RetrievalQAChain } from "langchain/chains";

265

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

266

import { MemoryVectorStore } from "langchain/vectorstores/memory";

267

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

268

269

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

270

const embeddings = new OpenAIEmbeddings();

271

const vectorStore = new MemoryVectorStore(embeddings);

272

273

// Add documents to vector store

274

await vectorStore.addDocuments([

275

{ pageContent: "LangChain is a framework for developing applications powered by language models.", metadata: {} },

276

{ pageContent: "It provides tools for chaining together LLM calls and managing prompts.", metadata: {} }

277

]);

278

279

const chain = RetrievalQAChain.fromLLM(llm, vectorStore.asRetriever());

280

281

const result = await chain.call({

282

query: "What is LangChain?"

283

});

284

```

285

286

### Sequential Chains

287

288

Chains that execute multiple operations in sequence, passing outputs as inputs to subsequent steps.

289

290

```typescript { .api }

291

/**

292

* Sequential chain that runs multiple chains in order

293

*/

294

class SequentialChain extends BaseChain {

295

constructor(fields: SequentialChainInput);

296

297

/** Array of chains to execute in order */

298

chains: BaseChain[];

299

300

/** Input variables for the overall chain */

301

inputVariables: string[];

302

303

/** Output variables from the overall chain */

304

outputVariables?: string[];

305

306

/** Whether to return all intermediate outputs */

307

returnAll?: boolean;

308

309

_call(values: ChainValues): Promise<ChainValues>;

310

}

311

312

/**

313

* Simple sequential chain where output of one chain feeds into next

314

*/

315

class SimpleSequentialChain extends BaseChain {

316

constructor(fields: SimpleSequentialChainInput);

317

318

/** Array of chains to execute in order */

319

chains: BaseChain[];

320

321

/** Strip whitespace from outputs */

322

stripOutputs?: boolean;

323

324

_call(values: ChainValues): Promise<ChainValues>;

325

}

326

327

/**

328

* Transform chain for applying transformations to input

329

*/

330

class TransformChain extends BaseChain {

331

constructor(fields: TransformChainInput);

332

333

/** The transform function */

334

transform: (values: ChainValues) => ChainValues | Promise<ChainValues>;

335

336

/** Input variables */

337

inputVariables: string[];

338

339

/** Output variables */

340

outputVariables: string[];

341

342

_call(values: ChainValues): Promise<ChainValues>;

343

}

344

```

345

346

**Usage Example:**

347

348

```typescript

349

import { SequentialChain, LLMChain } from "langchain/chains";

350

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

351

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

352

353

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

354

355

// First chain: generate a synopsis

356

const synopsisChain = new LLMChain({

357

llm,

358

prompt: PromptTemplate.fromTemplate("Write a synopsis for a play about {title}"),

359

outputKey: "synopsis"

360

});

361

362

// Second chain: write a review

363

const reviewChain = new LLMChain({

364

llm,

365

prompt: PromptTemplate.fromTemplate("Write a review for this play synopsis: {synopsis}"),

366

outputKey: "review"

367

});

368

369

const overallChain = new SequentialChain({

370

chains: [synopsisChain, reviewChain],

371

inputVariables: ["title"],

372

outputVariables: ["synopsis", "review"]

373

});

374

375

const result = await overallChain.call({ title: "Hamlet" });

376

```

377

378

### Specialized Chains

379

380

Domain-specific chains for particular use cases and integrations.

381

382

```typescript { .api }

383

/**

384

* API chain for making HTTP requests

385

*/

386

class APIChain extends BaseChain {

387

constructor(fields: APIChainInput);

388

389

/** API request chain */

390

apiRequestChain: LLMChain;

391

392

/** API answer chain */

393

apiAnswerChain: LLMChain;

394

395

/** HTTP headers for requests */

396

headers: Record<string, string>;

397

398

_call(values: ChainValues): Promise<ChainValues>;

399

400

static fromLLMAndAPISpec(

401

llm: BaseLanguageModelInterface,

402

apiSpec: string,

403

options?: Partial<APIChainInput>

404

): APIChain;

405

}

406

407

/**

408

* Constitutional chain for self-critique and improvement

409

*/

410

class ConstitutionalChain extends BaseChain {

411

constructor(fields: ConstitutionalChainInput);

412

413

/** Base chain to be improved */

414

chain: BaseChain;

415

416

/** Constitutional principles to apply */

417

constitutionalPrinciples: ConstitutionalPrinciple[];

418

419

/** Critique chain */

420

critiqueChain: LLMChain;

421

422

/** Revision chain */

423

revisionChain: LLMChain;

424

425

_call(values: ChainValues): Promise<ChainValues>;

426

}

427

428

/**

429

* OpenAI moderation chain

430

*/

431

class OpenAIModerationChain extends BaseChain {

432

constructor(fields?: OpenAIModerationChainInput);

433

434

/** OpenAI client for moderation */

435

client: OpenAIApi;

436

437

/** Whether to throw error on flagged content */

438

throwError?: boolean;

439

440

_call(values: ChainValues): Promise<ChainValues>;

441

}

442

443

/**

444

* Multi-route chain for routing to different chains

445

*/

446

class MultiRouteChain extends BaseChain {

447

constructor(fields: MultiRouteChainInput);

448

449

/** Router chain for determining destination */

450

routerChain: RouterChain;

451

452

/** Map of destination names to chains */

453

destinationChains: Record<string, BaseChain>;

454

455

/** Default chain if no route matches */

456

defaultChain?: BaseChain;

457

458

_call(values: ChainValues): Promise<ChainValues>;

459

}

460

```

461

462

### Chain Loading Functions

463

464

Utility functions for creating common chain configurations.

465

466

```typescript { .api }

467

/**

468

* Load a question-answering chain

469

*/

470

function loadQAChain(

471

llm: BaseLanguageModelInterface,

472

params?: {

473

type?: "stuff" | "map_reduce" | "refine";

474

prompt?: BasePromptTemplate;

475

verbose?: boolean;

476

}

477

): BaseChain;

478

479

/**

480

* Load a stuff documents QA chain

481

*/

482

function loadQAStuffChain(

483

llm: BaseLanguageModelInterface,

484

params?: {

485

prompt?: BasePromptTemplate;

486

verbose?: boolean;

487

}

488

): StuffDocumentsChain;

489

490

/**

491

* Load a map-reduce QA chain

492

*/

493

function loadQAMapReduceChain(

494

llm: BaseLanguageModelInterface,

495

params?: {

496

combinePrompt?: BasePromptTemplate;

497

mapPrompt?: BasePromptTemplate;

498

verbose?: boolean;

499

}

500

): MapReduceDocumentsChain;

501

502

/**

503

* Load a refine QA chain

504

*/

505

function loadQARefineChain(

506

llm: BaseLanguageModelInterface,

507

params?: {

508

questionPrompt?: BasePromptTemplate;

509

refinePrompt?: BasePromptTemplate;

510

verbose?: boolean;

511

}

512

): RefineDocumentsChain;

513

514

/**

515

* Load a summarization chain

516

*/

517

function loadSummarizationChain(

518

llm: BaseLanguageModelInterface,

519

params?: {

520

type?: "stuff" | "map_reduce" | "refine";

521

prompt?: BasePromptTemplate;

522

combinePrompt?: BasePromptTemplate;

523

verbose?: boolean;

524

}

525

): BaseChain;

526

```

527

528

### Modern Chain Functions (Runnable-based)

529

530

New-style chain creation functions using the Runnable interface for better composability.

531

532

```typescript { .api }

533

/**

534

* Create a retrieval chain using Runnable interface

535

*/

536

function createRetrievalChain(params: {

537

retriever: BaseRetrieverInterface;

538

combineDocsChain: Runnable;

539

}): Runnable<{ input: string }, { answer: string; context: DocumentInterface[] }>;

540

541

/**

542

* Create a stuff documents chain using Runnable interface

543

*/

544

function createStuffDocumentsChain(params: {

545

llm: BaseLanguageModelInterface;

546

prompt: BasePromptTemplate;

547

outputParser?: BaseOutputParser;

548

documentPrompt?: BasePromptTemplate;

549

documentSeparator?: string;

550

}): Runnable<{ context: DocumentInterface[]; [key: string]: any }, string>;

551

552

/**

553

* Create a history-aware retriever

554

*/

555

function createHistoryAwareRetriever(params: {

556

llm: BaseLanguageModelInterface;

557

retriever: BaseRetrieverInterface;

558

rephrasePrompt: BasePromptTemplate;

559

}): Runnable<{ input: string; chat_history: BaseMessageInterface[] }, DocumentInterface[]>;

560

561

/**

562

* Create an SQL query chain

563

*/

564

function createSqlQueryChain(params: {

565

llm: BaseLanguageModelInterface;

566

db: SqlDatabase;

567

prompt?: BasePromptTemplate;

568

k?: number;

569

}): Runnable<{ question: string }, string>;

570

```

571

572

**Usage Example:**

573

574

```typescript

575

import {

576

createRetrievalChain,

577

createStuffDocumentsChain

578

} from "langchain/chains";

579

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

580

581

const llm = new ChatOpenAI();

582

const retriever = vectorStore.asRetriever();

583

584

// Create document processing chain

585

const combineDocsChain = await createStuffDocumentsChain({

586

llm,

587

prompt: ChatPromptTemplate.fromMessages([

588

["system", "Answer based on the following context:\n\n{context}"],

589

["human", "{input}"]

590

])

591

});

592

593

// Create full retrieval chain

594

const retrievalChain = await createRetrievalChain({

595

retriever,

596

combineDocsChain

597

});

598

599

const result = await retrievalChain.invoke({

600

input: "What is the main topic discussed?"

601

});

602

```

603

604

### OpenAI Functions Chains

605

606

Specialized chains that leverage OpenAI function calling capabilities.

607

608

```typescript { .api }

609

/**

610

* Create extraction chain using OpenAI functions

611

*/

612

function createExtractionChain(

613

schema: Record<string, any>,

614

llm: BaseLanguageModelInterface,

615

options?: CreateExtractionChainOptions

616

): LLMChain;

617

618

/**

619

* Create extraction chain from Zod schema

620

*/

621

function createExtractionChainFromZod(

622

schema: ZodSchema,

623

llm: BaseLanguageModelInterface,

624

options?: CreateExtractionChainOptions

625

): LLMChain;

626

627

/**

628

* Create tagging chain using OpenAI functions

629

*/

630

function createTaggingChain(

631

schema: Record<string, any>,

632

llm: BaseLanguageModelInterface,

633

options?: CreateTaggingChainOptions

634

): LLMChain;

635

636

/**

637

* Create tagging chain from Zod schema

638

*/

639

function createTaggingChainFromZod(

640

schema: ZodSchema,

641

llm: BaseLanguageModelInterface,

642

options?: CreateTaggingChainOptions

643

): LLMChain;

644

645

/**

646

* Create OpenAPI chain

647

*/

648

function createOpenAPIChain(

649

spec: string,

650

llm: BaseLanguageModelInterface,

651

options?: CreateOpenAPIChainOptions

652

): APIChain;

653

654

/**

655

* Convert OpenAPI spec to OpenAI functions

656

*/

657

function convertOpenAPISpecToOpenAIFunctions(

658

spec: OpenAPISpec,

659

options?: ConvertOpenAPISpecOptions

660

): OpenAIFunctionDefinition[];

661

```

662

663

## Types

664

665

### Chain Input Types

666

667

```typescript { .api }

668

interface ChainInputs {

669

memory?: BaseMemory;

670

verbose?: boolean;

671

callbacks?: BaseCallbackHandler[];

672

tags?: string[];

673

metadata?: Record<string, unknown>;

674

}

675

676

interface LLMChainInput extends ChainInputs {

677

llm: BaseLanguageModelInterface;

678

prompt: BasePromptTemplate;

679

outputKey?: string;

680

outputParser?: BaseOutputParser;

681

}

682

683

interface RetrievalQAChainInput extends ChainInputs {

684

retriever: BaseRetrieverInterface;

685

combineDocumentsChain: BaseChain;

686

inputKey?: string;

687

outputKey?: string;

688

returnSourceDocuments?: boolean;

689

}

690

691

interface ConversationalRetrievalQAChainInput extends ChainInputs {

692

retriever: BaseRetrieverInterface;

693

combineDocumentsChain: BaseChain;

694

questionGeneratorChain: LLMChain;

695

outputKey?: string;

696

returnSourceDocuments?: boolean;

697

returnGeneratedQuestion?: boolean;

698

}

699

```

700

701

### Document Chain Types

702

703

```typescript { .api }

704

interface StuffDocumentsChainInput extends ChainInputs {

705

llmChain: LLMChain;

706

documentVariableName?: string;

707

documentSeparator?: string;

708

}

709

710

interface MapReduceDocumentsChainInput extends ChainInputs {

711

llmChain: LLMChain;

712

reduceDocumentsChain: BaseChain;

713

documentVariableName?: string;

714

returnIntermediateSteps?: boolean;

715

maxTokens?: number;

716

maxIterations?: number;

717

}

718

719

interface RefineDocumentsChainInput extends ChainInputs {

720

llmChain: LLMChain;

721

refineLLMChain: LLMChain;

722

documentVariableName?: string;

723

initialResponseName?: string;

724

returnIntermediateSteps?: boolean;

725

}

726

```

727

728

### Sequential Chain Types

729

730

```typescript { .api }

731

interface SequentialChainInput extends ChainInputs {

732

chains: BaseChain[];

733

inputVariables: string[];

734

outputVariables?: string[];

735

returnAll?: boolean;

736

}

737

738

interface SimpleSequentialChainInput extends ChainInputs {

739

chains: BaseChain[];

740

stripOutputs?: boolean;

741

}

742

743

interface TransformChainInput extends ChainInputs {

744

transform: (values: ChainValues) => ChainValues | Promise<ChainValues>;

745

inputVariables: string[];

746

outputVariables: string[];

747

}

748

```

749

750

### Specialized Chain Types

751

752

```typescript { .api }

753

interface APIChainInput extends ChainInputs {

754

apiRequestChain: LLMChain;

755

apiAnswerChain: LLMChain;

756

headers?: Record<string, string>;

757

}

758

759

interface ConstitutionalChainInput extends ChainInputs {

760

chain: BaseChain;

761

constitutionalPrinciples: ConstitutionalPrinciple[];

762

critiqueChain: LLMChain;

763

revisionChain: LLMChain;

764

}

765

766

interface MultiRouteChainInput extends ChainInputs {

767

routerChain: RouterChain;

768

destinationChains: Record<string, BaseChain>;

769

defaultChain?: BaseChain;

770

silentErrors?: boolean;

771

}

772

773

class ConstitutionalPrinciple {

774

constructor(fields: {

775

critiqueRequest: string;

776

revisionRequest: string;

777

name?: string;

778

});

779

780

critiqueRequest: string;

781

revisionRequest: string;

782

name?: string;

783

}

784

```

785

786

### Chain Values and Results

787

788

```typescript { .api }

789

type ChainValues = Record<string, any>;

790

791

interface ChainInputs {

792

[key: string]: any;

793

}

794

795

interface CreateExtractionChainOptions {

796

prompt?: BasePromptTemplate;

797

tags?: string[];

798

verbose?: boolean;

799

}

800

801

interface CreateTaggingChainOptions {

802

prompt?: BasePromptTemplate;

803

tags?: string[];

804

verbose?: boolean;

805

}

806

```