Core LangChain.js abstractions and schemas for building applications with Large Language Models
npx @tessl/cli install tessl/npm-langchain--core@0.3.00
# LangChain Core
1
2
LangChain Core provides the foundational abstractions and runtime for the LangChain.js ecosystem, serving as the base layer for building applications with Large Language Models (LLMs). It includes base classes for language models, chat models, vectorstores, retrievers, and the LangChain Expression Language (LCEL) runtime that enables composable sequences called "runnables".
3
4
## Package Information
5
6
- **Package Name**: @langchain/core
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @langchain/core`
10
11
## Core Imports
12
13
**Important**: @langchain/core uses subpath imports for optimal tree-shaking. Always import from specific module paths, never from the root package.
14
15
```typescript
16
// ✅ Correct - use subpath imports
17
import { BaseMessage, HumanMessage, AIMessage } from "@langchain/core/messages";
18
import { BaseChatModel } from "@langchain/core/language_models/chat_models";
19
import { Runnable } from "@langchain/core/runnables";
20
import { VectorStore } from "@langchain/core/vectorstores";
21
import { BaseRetriever } from "@langchain/core/retrievers";
22
import { PromptTemplate } from "@langchain/core/prompts";
23
import { StringOutputParser } from "@langchain/core/output_parsers";
24
25
// ❌ Incorrect - root imports are not supported
26
// import { BaseMessage } from "@langchain/core";
27
```
28
29
For CommonJS:
30
31
```javascript
32
const { BaseMessage, HumanMessage, AIMessage } = require("@langchain/core/messages");
33
const { BaseChatModel } = require("@langchain/core/language_models/chat_models");
34
const { Runnable } = require("@langchain/core/runnables");
35
```
36
37
## Basic Usage
38
39
```typescript
40
import { StringOutputParser } from "@langchain/core/output_parsers";
41
import { ChatPromptTemplate } from "@langchain/core/prompts";
42
import { RunnableSequence } from "@langchain/core/runnables";
43
44
// Create a prompt template
45
const prompt = ChatPromptTemplate.fromTemplate(
46
"Answer the following question: {question}"
47
);
48
49
// Create an output parser
50
const outputParser = new StringOutputParser();
51
52
// Chain components using LCEL (LangChain Expression Language)
53
const chain = prompt.pipe(outputParser);
54
55
// Use the chain
56
const result = await chain.invoke({
57
question: "What is the capital of France?"
58
});
59
```
60
61
## Architecture
62
63
LangChain Core is built around several key design patterns:
64
65
- **Runnable Interface**: Universal composability pattern enabling any component to be chained, streamed, or batched
66
- **Modular Abstractions**: Pluggable interfaces allowing any provider to implement required functionality
67
- **Type Safety**: Comprehensive TypeScript support with generic types throughout
68
- **Streaming Support**: Built-in streaming capabilities for real-time applications
69
- **Callback System**: Universal event handling and observability across all components
70
- **Serialization**: Consistent serialization patterns for persistence and debugging
71
72
## Capabilities
73
74
### Runnable System
75
76
Core composability framework enabling universal chaining, streaming, and batch operations across all LangChain components.
77
78
```typescript { .api }
79
abstract class Runnable<RunInput, RunOutput, CallOptions = {}> {
80
abstract invoke(input: RunInput, options?: Partial<CallOptions>): Promise<RunOutput>;
81
stream(input: RunInput, options?: Partial<CallOptions>): AsyncGenerator<RunOutput>;
82
batch(inputs: RunInput[], options?: Partial<CallOptions>): Promise<RunOutput[]>;
83
pipe<NewRunOutput>(coerceable: RunnableLike<RunOutput, NewRunOutput>): Runnable<RunInput, NewRunOutput>;
84
}
85
```
86
87
[Runnable System](./runnables.md)
88
89
### Message System
90
91
Structured message types and conversation management for chat-based applications.
92
93
```typescript { .api }
94
abstract class BaseMessage {
95
constructor(content: MessageContent, additional_kwargs?: Record<string, unknown>);
96
readonly content: MessageContent;
97
readonly additional_kwargs: Record<string, unknown>;
98
readonly response_metadata: Record<string, unknown>;
99
abstract getType(): MessageType;
100
}
101
102
class HumanMessage extends BaseMessage {
103
getType(): "human";
104
}
105
106
class AIMessage extends BaseMessage {
107
getType(): "ai";
108
}
109
```
110
111
[Message System](./messages.md)
112
113
### Language Models
114
115
Abstract base classes for language models and chat models with unified interfaces.
116
117
```typescript { .api }
118
abstract class BaseChatModel<CallOptions = {}, OutputMessageType extends BaseMessage = BaseMessage> extends BaseLanguageModel<OutputMessageType, CallOptions> {
119
bindTools(tools: BindToolsInput, kwargs?: Record<string, unknown>): BaseChatModel;
120
withStructuredOutput<T>(outputSchema: z.ZodSchema<T> | Record<string, unknown>): Runnable<BaseMessage[], T>;
121
}
122
```
123
124
[Language Models](./language-models.md)
125
126
### Vector Stores
127
128
Document storage and similarity search functionality for retrieval-augmented generation (RAG).
129
130
```typescript { .api }
131
abstract class VectorStore {
132
abstract addDocuments(documents: Document[], options?: Record<string, unknown>): Promise<string[] | void>;
133
abstract similaritySearch(query: string, k?: number, filter?: object): Promise<Document[]>;
134
abstract similaritySearchWithScore(query: string, k?: number, filter?: object): Promise<[Document, number][]>;
135
asRetriever(fields?: VectorStoreRetrieverInput<this>): VectorStoreRetriever<this>;
136
}
137
```
138
139
[Vector Stores](./vectorstores.md)
140
141
### Document Processing
142
143
Document representation and processing capabilities for content management.
144
145
```typescript { .api }
146
class Document<Metadata = Record<string, unknown>> {
147
constructor(fields: DocumentInput<Metadata>);
148
pageContent: string;
149
metadata: Metadata;
150
id?: string;
151
}
152
```
153
154
[Document Processing](./documents.md)
155
156
### Retrieval System
157
158
Document retrieval abstractions for implementing search and information retrieval.
159
160
```typescript { .api }
161
abstract class BaseRetriever<Metadata = Record<string, unknown>> extends Runnable<string, Document<Metadata>[]> {
162
abstract _getRelevantDocuments(query: string, runManager?: CallbackManagerForRetrieverRun): Promise<Document<Metadata>[]>;
163
getRelevantDocuments(query: string, config?: RunnableConfig): Promise<Document<Metadata>[]>;
164
}
165
```
166
167
[Retrieval System](./retrievers.md)
168
169
### Prompt Templates
170
171
Template system for creating dynamic prompts with variable substitution and formatting.
172
173
```typescript { .api }
174
abstract class BasePromptTemplate<RunInput extends InputValues = InputValues, RunOutput extends PromptValue = PromptValue> extends Runnable<RunInput, RunOutput> {
175
abstract format(values: InputValues): Promise<string>;
176
abstract formatPromptValue(values: InputValues): Promise<PromptValue>;
177
}
178
```
179
180
[Prompt Templates](./prompts.md)
181
182
### Tools System
183
184
Tool definition and execution framework for function calling and external integrations.
185
186
```typescript { .api }
187
abstract class StructuredTool<SchemaT = z.ZodSchema> extends Runnable<z.input<SchemaT>, unknown> {
188
name: string;
189
description: string;
190
schema: SchemaT;
191
abstract _call(arg: z.input<SchemaT>, runManager?: CallbackManagerForToolRun): Promise<unknown>;
192
}
193
```
194
195
[Tools System](./tools.md)
196
197
### Output Parsing
198
199
Structured output parsing for converting LLM responses into typed data structures.
200
201
```typescript { .api }
202
abstract class BaseOutputParser<T = unknown> extends Runnable<string | BaseMessage, T> {
203
abstract parse(text: string): Promise<T>;
204
parseResult(result: ChatResult): Promise<T>;
205
getFormatInstructions(): string;
206
}
207
```
208
209
[Output Parsing](./output-parsers.md)
210
211
### Callback System
212
213
Event handling and observability framework for monitoring and debugging LangChain operations.
214
215
```typescript { .api }
216
abstract class BaseCallbackHandler {
217
name: string;
218
handleLLMStart?(llm: Serialized, prompts: string[], runId: string): Promise<void>;
219
handleLLMEnd?(output: LLMResult, runId: string): Promise<void>;
220
handleLLMError?(err: Error, runId: string): Promise<void>;
221
}
222
```
223
224
[Callback System](./callbacks.md)
225
226
### Memory & Storage
227
228
Memory management and storage abstractions for maintaining conversation state and persistence.
229
230
```typescript { .api }
231
abstract class BaseChatMessageHistory {
232
abstract getMessages(): Promise<BaseMessage[]>;
233
abstract addMessage(message: BaseMessage): Promise<void>;
234
abstract clear(): Promise<void>;
235
}
236
```
237
238
[Memory & Storage](./memory-storage.md)
239
240
### Embeddings
241
242
Embedding model abstractions for converting text to vector representations.
243
244
```typescript { .api }
245
abstract class Embeddings {
246
abstract embedDocuments(documents: string[]): Promise<number[][]>;
247
abstract embedQuery(document: string): Promise<number[]>;
248
}
249
```
250
251
[Embeddings](./embeddings.md)
252
253
### Agents
254
255
Agent framework for autonomous task execution and tool usage.
256
257
```typescript { .api }
258
interface AgentAction {
259
tool: string;
260
toolInput: string | Record<string, any>;
261
log: string;
262
}
263
264
interface AgentFinish {
265
returnValues: Record<string, any>;
266
log: string;
267
}
268
```
269
270
[Agents](./agents.md)
271
272
### Caching
273
274
Caching framework for optimizing repeated operations.
275
276
```typescript { .api }
277
abstract class BaseCache<T> {
278
abstract lookup(prompt: string, llmKey: string): Promise<T | null>;
279
abstract update(prompt: string, llmKey: string, value: T): Promise<void>;
280
}
281
```
282
283
[Caching](./caches.md)
284
285
## Types
286
287
### Core Types
288
289
```typescript { .api }
290
type MessageContent = string | MessageContentComplex[];
291
292
type MessageType = "human" | "ai" | "generic" | "developer" | "system" | "function" | "tool" | "remove";
293
294
interface RunnableConfig {
295
callbacks?: Callbacks;
296
tags?: string[];
297
metadata?: Record<string, unknown>;
298
runName?: string;
299
configurable?: Record<string, unknown>;
300
}
301
302
interface InputValues {
303
[key: string]: unknown;
304
}
305
306
type Callbacks = CallbackManager | (BaseCallbackHandler | CallbackHandlerMethods)[];
307
```