TypeScript framework for developing context-aware applications powered by language models with composable tools and integrations
npx @tessl/cli install tessl/npm-langchain@0.3.00
# LangChain JavaScript/TypeScript
1
2
LangChain is a comprehensive framework for developing context-aware applications powered by language models. It provides composable tools and integrations that enable the creation of sophisticated AI applications including autonomous agents, retrieval-augmented generation systems, conversational AI, and document processing workflows. The framework offers both functional utilities and object-oriented interfaces with full TypeScript support.
3
4
## Package Information
5
6
- **Package Name**: langchain
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install langchain`
10
- **Version**: 0.3.32
11
- **Documentation**: https://js.langchain.com
12
- **License**: MIT
13
14
## Core Imports
15
16
```typescript
17
import { LLMChain } from "langchain/chains";
18
import { AgentExecutor, createReactAgent } from "langchain/agents";
19
import { DynamicTool } from "langchain/tools";
20
import { BufferMemory } from "langchain/memory";
21
import { TextLoader } from "langchain/document_loaders/fs/text";
22
```
23
24
CommonJS:
25
```javascript
26
const { LLMChain } = require("langchain/chains");
27
const { AgentExecutor, createReactAgent } = require("langchain/agents");
28
const { DynamicTool } = require("langchain/tools");
29
const { BufferMemory } = require("langchain/memory");
30
```
31
32
## Basic Usage
33
34
```typescript
35
import { LLMChain } from "langchain/chains";
36
import { AgentExecutor, createReactAgent } from "langchain/agents";
37
import { DynamicTool } from "langchain/tools";
38
import { BufferMemory } from "langchain/memory";
39
40
// Note: This example shows the structure - you'll need to provide your own LLM
41
// from packages like @langchain/openai, @langchain/anthropic, etc.
42
43
// Create tools for an agent
44
const tools = [
45
new DynamicTool({
46
name: "calculator",
47
description: "Calculate simple math expressions",
48
func: async (input: string) => {
49
try {
50
// Simple calculator - in production, use a proper math parser
51
const result = Function('"use strict"; return (' + input + ')')();
52
return result.toString();
53
} catch (error) {
54
return "Error: Invalid calculation";
55
}
56
},
57
}),
58
];
59
60
// Create memory for conversation context
61
const memory = new BufferMemory({
62
memoryKey: "chat_history",
63
returnMessages: true,
64
});
65
66
// With an LLM (from separate packages), you would create agents like:
67
// const agent = await createReactAgent({ llm, tools, prompt });
68
// const executor = new AgentExecutor({ agent, tools, memory });
69
```
70
71
## Architecture
72
73
LangChain is built around several foundational concepts:
74
75
- **Runnables**: Core abstraction for chainable components that can be invoked, streamed, and composed
76
- **Chains**: Sequences of calls to LLMs, tools, or data processing steps
77
- **Agents**: Autonomous systems that use LLMs to decide which tools to use and how
78
- **Memory**: Systems for persisting state between chain/agent runs
79
- **Retrievers**: Interfaces for fetching relevant documents or data
80
- **Tools**: Functions that agents can call to interact with the world
81
- **Prompts**: Templates and managers for LLM inputs
82
- **Output Parsers**: Components for extracting structured data from LLM outputs
83
84
The framework follows a composable design where components can be mixed and matched to build complex workflows.
85
86
## Capabilities
87
88
### Agents and Agent Toolkits
89
90
Autonomous systems that use language models to determine which actions to take, including specialized toolkits for different domains like SQL, JSON manipulation, and API interactions.
91
92
```typescript { .api }
93
class AgentExecutor {
94
constructor(input: AgentExecutorInput);
95
invoke(input: { input: string }): Promise<{ output: string }>;
96
}
97
98
function createReactAgent(params: {
99
llm: BaseLanguageModelInterface;
100
tools: StructuredToolInterface[];
101
prompt: BasePromptTemplate;
102
streamRunnable?: boolean;
103
}): Promise<RunnableAgent>;
104
105
function createOpenAIFunctionsAgent(params: {
106
llm: BaseLanguageModelInterface;
107
tools: StructuredToolInterface[];
108
prompt: BasePromptTemplate;
109
streamRunnable?: boolean;
110
}): Promise<RunnableAgent>;
111
```
112
113
[Agents and Agent Toolkits](./agents.md)
114
115
### Chains and Document Processing
116
117
Sequences of operations for processing documents, question answering, summarization, and complex multi-step reasoning workflows.
118
119
```typescript { .api }
120
class LLMChain extends BaseChain {
121
constructor(fields: LLMChainInput);
122
call(values: ChainValues): Promise<ChainValues>;
123
}
124
125
class RetrievalQAChain extends BaseChain {
126
static fromLLM(
127
llm: BaseLanguageModelInterface,
128
retriever: BaseRetrieverInterface,
129
options?: Partial<RetrievalQAChainInput>
130
): RetrievalQAChain;
131
}
132
133
function createRetrievalChain(params: {
134
retriever: BaseRetrieverInterface;
135
combineDocsChain: Runnable;
136
}): Runnable;
137
138
function createStuffDocumentsChain(params: {
139
llm: BaseLanguageModelInterface;
140
prompt: BasePromptTemplate;
141
}): Runnable;
142
```
143
144
[Chains and Document Processing](./chains.md)
145
146
### Tools and Tool Calling
147
148
Built-in and custom tools that agents can use to interact with external systems, APIs, databases, and perform various operations.
149
150
```typescript { .api }
151
abstract class Tool {
152
name: string;
153
description: string;
154
abstract _call(arg: string): Promise<string>;
155
}
156
157
class DynamicTool extends Tool {
158
constructor(fields: DynamicToolInput);
159
}
160
161
class DynamicStructuredTool extends StructuredTool {
162
constructor(fields: DynamicStructuredToolInput);
163
}
164
165
function formatToOpenAIFunction(tool: StructuredToolInterface): FunctionDefinition;
166
function formatToOpenAITool(tool: StructuredToolInterface): ToolDefinition;
167
```
168
169
[Tools and Tool Calling](./tools.md)
170
171
### Retrievers and Vector Operations
172
173
Systems for finding and retrieving relevant documents from vector stores, databases, and other sources with support for similarity search, filtering, and ranking.
174
175
```typescript { .api }
176
class ContextualCompressionRetriever extends BaseRetriever {
177
constructor(args: ContextualCompressionRetrieverArgs);
178
_getRelevantDocuments(query: string): Promise<DocumentInterface[]>;
179
}
180
181
class MultiQueryRetriever extends BaseRetriever {
182
static fromLLM(args: {
183
retriever: BaseRetrieverInterface;
184
llm: BaseLanguageModelInterface;
185
prompt?: BasePromptTemplate;
186
}): MultiQueryRetriever;
187
}
188
189
class EnsembleRetriever extends BaseRetriever {
190
constructor(args: {
191
retrievers: BaseRetrieverInterface[];
192
weights?: number[];
193
});
194
}
195
```
196
197
[Retrievers and Vector Operations](./retrievers.md)
198
199
### Memory and Chat History
200
201
Systems for managing conversation state, storing chat history, and maintaining context across interactions with various storage backends.
202
203
```typescript { .api }
204
abstract class BaseMemory {
205
abstract get memoryKeys(): string[];
206
abstract loadMemoryVariables(values: InputValues): Promise<MemoryVariables>;
207
abstract saveContext(inputValues: InputValues, outputValues: OutputValues): Promise<void>;
208
}
209
210
class BufferMemory extends BaseChatMemory {
211
constructor(fields?: BufferMemoryInput);
212
}
213
214
class ConversationSummaryMemory extends BaseConversationSummaryMemory {
215
constructor(fields: ConversationSummaryMemoryInput);
216
}
217
218
class VectorStoreRetrieverMemory extends BaseMemory {
219
constructor(fields: VectorStoreRetrieverMemoryInput);
220
}
221
```
222
223
[Memory and Chat History](./memory.md)
224
225
### Document Loading and Processing
226
227
Comprehensive document loaders for various file formats and sources, plus text splitting and transformation utilities.
228
229
```typescript { .api }
230
abstract class BaseDocumentLoader {
231
abstract load(): Promise<DocumentInterface[]>;
232
}
233
234
class DirectoryLoader extends BaseDocumentLoader {
235
constructor(directoryPath: string, loaders: { [extension: string]: (filePath: string) => BaseDocumentLoader });
236
}
237
238
class TextLoader extends BaseDocumentLoader {
239
constructor(filePathOrBlob: string | Blob);
240
}
241
242
class JSONLoader extends BaseDocumentLoader {
243
constructor(filePathOrBlob: string | Blob, pointers?: string[]);
244
}
245
```
246
247
[Document Loading and Processing](./document-loaders.md)
248
249
### Output Parsers
250
251
Components for extracting and structuring data from language model outputs, including JSON parsing, list extraction, and custom formats.
252
253
```typescript { .api }
254
abstract class BaseOutputParser<T = unknown> {
255
abstract parse(text: string): Promise<T>;
256
abstract getFormatInstructions(): string;
257
}
258
259
class StructuredOutputParser<T> extends BaseOutputParser<T> {
260
static fromZodSchema<T>(schema: ZodSchema<T>): StructuredOutputParser<T>;
261
static fromNamesAndDescriptions<T>(schemas: Record<string, string>): StructuredOutputParser<T>;
262
}
263
264
class JsonOutputFunctionsParser extends BaseOutputParser<Record<string, any>> {
265
constructor(config?: { argsOnly?: boolean });
266
}
267
268
class CommaSeparatedListOutputParser extends BaseOutputParser<string[]> {}
269
```
270
271
[Output Parsers](./output-parsers.md)
272
273
### Embeddings and Vector Stores
274
275
Embedding models and vector storage solutions with caching, similarity search, and filtering capabilities.
276
277
```typescript { .api }
278
class CacheBackedEmbeddings extends Embeddings {
279
static fromBytesStore(
280
underlyingEmbeddings: EmbeddingsInterface,
281
documentEmbeddingStore: BaseStore<string, Uint8Array>,
282
options?: CacheBackedEmbeddingsFields
283
): CacheBackedEmbeddings;
284
285
embedQuery(document: string): Promise<number[]>;
286
embedDocuments(documents: string[]): Promise<number[][]>;
287
}
288
289
interface CacheBackedEmbeddingsFields {
290
namespace?: string;
291
}
292
```
293
294
[Embeddings and Vector Stores](./embeddings.md)
295
296
### Experimental Features
297
298
Cutting-edge features including AutoGPT, BabyAGI, generative agents, and advanced planning systems.
299
300
```typescript { .api }
301
class AutoGPT extends BaseAgent {
302
constructor(fields: AutoGPTInput);
303
}
304
305
class AutoGPTPrompt extends BasePromptTemplate {
306
constructor(fields: AutoGPTPromptInput);
307
}
308
309
function preprocessJsonInput(text: string): string;
310
```
311
312
[Experimental Features](./experimental.md)
313
314
### Utilities and Integrations
315
316
Helper functions, LangSmith integration, Hub connectivity, and storage utilities for building robust applications.
317
318
```typescript { .api }
319
function pull<T>(ownerRepoCommit: string, options?: {
320
apiKey?: string;
321
apiUrl?: string;
322
includeModel?: boolean;
323
modelClass?: any;
324
}): Promise<T>;
325
326
function runOnDataset(params: RunOnDatasetParams): Promise<EvalResults>;
327
328
class LocalFileStore extends BaseStore<string, Uint8Array> {
329
constructor(rootPath: string);
330
static fromPath(rootPath: string): Promise<LocalFileStore>;
331
mget(keys: string[]): Promise<(Uint8Array | undefined)[]>;
332
mset(keyValuePairs: [string, Uint8Array][]): Promise<void>;
333
mdelete(keys: string[]): Promise<void>;
334
yieldKeys(prefix?: string): AsyncGenerator<string>;
335
}
336
```
337
338
[Utilities and Integrations](./utilities.md)
339
340
## Types
341
342
### Core Interfaces
343
344
```typescript { .api }
345
interface DocumentInterface {
346
pageContent: string;
347
metadata: Record<string, any>;
348
}
349
350
interface BaseRetrieverInterface {
351
getRelevantDocuments(query: string): Promise<DocumentInterface[]>;
352
}
353
354
interface StructuredToolInterface {
355
name: string;
356
description: string;
357
schema: ZodSchema<any>;
358
call(arg: any): Promise<string>;
359
}
360
361
interface BaseLanguageModelInterface {
362
predict(text: string): Promise<string>;
363
predictMessages(messages: BaseMessageInterface[]): Promise<BaseMessageInterface>;
364
}
365
```
366
367
### Chain and Agent Types
368
369
```typescript { .api }
370
interface ChainInputs {
371
memory?: BaseMemory;
372
verbose?: boolean;
373
callbacks?: BaseCallbackHandler[];
374
}
375
376
interface LLMChainInput extends ChainInputs {
377
llm: BaseLanguageModelInterface;
378
prompt: BasePromptTemplate;
379
outputKey?: string;
380
outputParser?: BaseOutputParser;
381
}
382
383
interface AgentExecutorInput extends ChainInputs {
384
agent: BaseAgent | RunnableAgent;
385
tools: StructuredToolInterface[];
386
maxIterations?: number;
387
maxExecutionTime?: number;
388
earlyStoppingMethod?: string;
389
handleParsingErrors?: boolean | string | ((error: Error) => string);
390
}
391
```
392
393
### Memory Types
394
395
```typescript { .api }
396
interface BufferMemoryInput {
397
humanPrefix?: string;
398
aiPrefix?: string;
399
memoryKey?: string;
400
inputKey?: string;
401
outputKey?: string;
402
returnMessages?: boolean;
403
chatHistory?: BaseListChatMessageHistory;
404
}
405
406
interface ConversationSummaryMemoryInput extends BaseChatMemoryInput {
407
llm: BaseLanguageModelInterface;
408
prompt?: BasePromptTemplate;
409
summaryMessageKey?: string;
410
}
411
412
interface VectorStoreRetrieverMemoryInput {
413
vectorStoreRetriever: BaseRetrieverInterface;
414
memoryKey?: string;
415
inputKey?: string;
416
returnDocs?: boolean;
417
}
418
```
419
420
### Tool Types
421
422
```typescript { .api }
423
interface DynamicToolInput {
424
name: string;
425
description: string;
426
func: (input: string) => Promise<string> | string;
427
verbose?: boolean;
428
}
429
430
interface DynamicStructuredToolInput<T = ZodAny> {
431
name: string;
432
description: string;
433
schema: T;
434
func: (input: TypeOf<T>) => Promise<string> | string;
435
verbose?: boolean;
436
}
437
```
438
439
### Evaluation Types
440
441
```typescript { .api }
442
interface RunOnDatasetParams {
443
datasetName: string;
444
llmOrChainFactory: () => BaseLanguageModelInterface | BaseChain;
445
evaluation?: EvaluatorType[];
446
concurrency?: number;
447
projectName?: string;
448
projectMetadata?: Record<string, any>;
449
}
450
451
interface EvalResults {
452
projectName: string;
453
results: Record<string, any>[];
454
}
455
```