0
# Message System
1
2
The message system provides structured message types and conversation management for chat-based applications. Messages form the core communication format between users, AI models, and tools in LangChain applications.
3
4
## Capabilities
5
6
### Base Message
7
8
Abstract base class for all message types in LangChain.
9
10
```typescript { .api }
11
/**
12
* Abstract base class for all messages
13
*/
14
abstract class BaseMessage {
15
/** Message content - can be string or complex content array */
16
content: MessageContent;
17
/** Optional sender name */
18
name?: string;
19
/** Additional implementation-specific data */
20
additional_kwargs: Record<string, unknown>;
21
/** Response metadata from model providers */
22
response_metadata: Record<string, unknown>;
23
/** Unique message identifier */
24
id?: string;
25
26
constructor(
27
content: MessageContent,
28
additional_kwargs?: Record<string, unknown>,
29
response_metadata?: Record<string, unknown>,
30
name?: string,
31
id?: string
32
);
33
34
/** Get the message type identifier */
35
abstract getType(): MessageType;
36
37
/** Get text representation of content */
38
get text(): string;
39
40
/** Convert message to serializable dictionary */
41
toDict(): StoredMessage;
42
43
/** Create message from serialized dictionary */
44
static fromDict(message: StoredMessage): BaseMessage;
45
}
46
```
47
48
### Human Message
49
50
Represents messages from human users.
51
52
```typescript { .api }
53
/**
54
* Message from a human user
55
*/
56
class HumanMessage extends BaseMessage {
57
getType(): "human";
58
59
constructor(
60
content: MessageContent,
61
additional_kwargs?: Record<string, unknown>,
62
response_metadata?: Record<string, unknown>,
63
name?: string,
64
id?: string
65
);
66
}
67
```
68
69
**Usage Examples:**
70
71
```typescript
72
import { HumanMessage } from "@langchain/core/messages";
73
74
// Simple text message
75
const message = new HumanMessage("Hello, how are you?");
76
77
// Message with metadata
78
const messageWithMeta = new HumanMessage(
79
"What is the weather like?",
80
{ priority: "high" },
81
{},
82
"User123"
83
);
84
85
// Complex content with images
86
const complexMessage = new HumanMessage([
87
{ type: "text", text: "What do you see in this image?" },
88
{ type: "image_url", image_url: { url: "data:image/jpeg;base64,..." } }
89
]);
90
```
91
92
### AI Message
93
94
Represents messages from AI assistants or language models.
95
96
```typescript { .api }
97
/**
98
* Message from an AI assistant
99
*/
100
class AIMessage extends BaseMessage {
101
/** Tool calls made by the AI */
102
tool_calls?: ToolCall[];
103
/** Invalid tool calls that couldn't be parsed */
104
invalid_tool_calls?: InvalidToolCall[];
105
/** Usage statistics from the model */
106
usage_metadata?: UsageMetadata;
107
108
getType(): "ai";
109
110
constructor(
111
content: MessageContent,
112
additional_kwargs?: Record<string, unknown>,
113
response_metadata?: Record<string, unknown>,
114
name?: string,
115
id?: string,
116
tool_calls?: ToolCall[],
117
invalid_tool_calls?: InvalidToolCall[],
118
usage_metadata?: UsageMetadata
119
);
120
}
121
```
122
123
**Usage Examples:**
124
125
```typescript
126
import { AIMessage } from "@langchain/core/messages";
127
128
// Simple AI response
129
const response = new AIMessage("I'm doing well, thank you for asking!");
130
131
// AI message with tool calls
132
const messageWithTools = new AIMessage(
133
"I'll help you with that calculation.",
134
{},
135
{},
136
undefined,
137
undefined,
138
[{
139
name: "calculator",
140
args: { operation: "add", a: 5, b: 3 },
141
id: "call_123"
142
}]
143
);
144
145
// AI message with usage metadata
146
const messageWithUsage = new AIMessage(
147
"Here's your answer.",
148
{},
149
{},
150
undefined,
151
undefined,
152
undefined,
153
undefined,
154
{
155
input_tokens: 10,
156
output_tokens: 15,
157
total_tokens: 25
158
}
159
);
160
```
161
162
### System Message
163
164
Represents system-level instructions or context.
165
166
```typescript { .api }
167
/**
168
* System message providing context or instructions
169
*/
170
class SystemMessage extends BaseMessage {
171
getType(): "system";
172
173
constructor(
174
content: MessageContent,
175
additional_kwargs?: Record<string, unknown>,
176
response_metadata?: Record<string, unknown>,
177
name?: string,
178
id?: string
179
);
180
}
181
```
182
183
**Usage Examples:**
184
185
```typescript
186
import { SystemMessage } from "@langchain/core/messages";
187
188
const systemMsg = new SystemMessage(
189
"You are a helpful assistant that answers questions about science."
190
);
191
192
const contextMsg = new SystemMessage(
193
"The current date is 2024-01-15. Answer all questions with this context in mind."
194
);
195
```
196
197
### Function Message
198
199
Represents messages from function/tool executions (deprecated in favor of ToolMessage).
200
201
```typescript { .api }
202
/**
203
* Message from a function execution (deprecated)
204
* @deprecated Use ToolMessage instead
205
*/
206
class FunctionMessage extends BaseMessage {
207
/** Name of the function that was called */
208
name: string;
209
210
getType(): "function";
211
212
constructor(
213
content: MessageContent,
214
name: string,
215
additional_kwargs?: Record<string, unknown>,
216
response_metadata?: Record<string, unknown>,
217
id?: string
218
);
219
}
220
```
221
222
### Tool Message
223
224
Represents responses from tool executions.
225
226
```typescript { .api }
227
/**
228
* Message containing tool execution results
229
*/
230
class ToolMessage extends BaseMessage {
231
/** ID of the tool call this message responds to */
232
tool_call_id: string;
233
/** Name of the tool that was executed */
234
name?: string;
235
/** Artifact returned by the tool */
236
artifact?: unknown;
237
238
getType(): "tool";
239
240
constructor(
241
content: MessageContent,
242
tool_call_id: string,
243
name?: string,
244
artifact?: unknown,
245
additional_kwargs?: Record<string, unknown>,
246
response_metadata?: Record<string, unknown>,
247
id?: string
248
);
249
}
250
```
251
252
**Usage Examples:**
253
254
```typescript
255
import { ToolMessage } from "@langchain/core/messages";
256
257
// Tool execution result
258
const toolResult = new ToolMessage(
259
"The calculation result is 42",
260
"call_123",
261
"calculator"
262
);
263
264
// Tool result with artifact
265
const toolWithArtifact = new ToolMessage(
266
"Chart generated successfully",
267
"call_456",
268
"chart_generator",
269
{ chartUrl: "https://example.com/chart.png", format: "png" }
270
);
271
```
272
273
### Chat Message
274
275
Generic chat message with custom roles for non-standard message types.
276
277
```typescript { .api }
278
/**
279
* Generic chat message with custom role
280
*/
281
class ChatMessage extends BaseMessage {
282
/** Custom role identifier */
283
role: string;
284
285
getType(): "generic";
286
287
constructor(
288
content: MessageContent,
289
role: string,
290
additional_kwargs?: Record<string, unknown>,
291
response_metadata?: Record<string, unknown>,
292
name?: string,
293
id?: string
294
);
295
}
296
```
297
298
**Usage Examples:**
299
300
```typescript
301
import { ChatMessage } from "@langchain/core/messages";
302
303
// Custom role message
304
const customMessage = new ChatMessage(
305
"Processing your request...",
306
"processing_bot"
307
);
308
309
// Assistant with specific role
310
const assistantMessage = new ChatMessage(
311
"I'm a specialized code reviewer.",
312
"code_reviewer"
313
);
314
```
315
316
### Remove Message
317
318
Special message type for indicating message removal in message streams.
319
320
```typescript { .api }
321
/**
322
* Special message indicating removal from message stream
323
*/
324
class RemoveMessage extends BaseMessage {
325
getType(): "remove";
326
327
constructor(id: string);
328
}
329
```
330
331
### Base Message Chunk
332
333
Base class for streamable message chunks that can be concatenated.
334
335
```typescript { .api }
336
/**
337
* Base class for streamable message chunks
338
*/
339
abstract class BaseMessageChunk extends BaseMessage {
340
/** Combine this chunk with another chunk */
341
abstract concat(chunk: BaseMessageChunk): BaseMessageChunk;
342
}
343
344
/**
345
* Streamable chunk of an AI message
346
*/
347
class AIMessageChunk extends BaseMessageChunk {
348
getType(): "ai";
349
350
concat(chunk: AIMessageChunk): AIMessageChunk;
351
}
352
353
/**
354
* Streamable chunk of a human message
355
*/
356
class HumanMessageChunk extends BaseMessageChunk {
357
getType(): "human";
358
359
concat(chunk: HumanMessageChunk): HumanMessageChunk;
360
}
361
362
/**
363
* Streamable chunk of a system message
364
*/
365
class SystemMessageChunk extends BaseMessageChunk {
366
getType(): "system";
367
368
concat(chunk: SystemMessageChunk): SystemMessageChunk;
369
}
370
371
/**
372
* Streamable chunk of a function message
373
*/
374
class FunctionMessageChunk extends BaseMessageChunk {
375
/** Name of the function */
376
name: string;
377
378
getType(): "function";
379
380
concat(chunk: FunctionMessageChunk): FunctionMessageChunk;
381
}
382
383
/**
384
* Streamable chunk of a tool message
385
*/
386
class ToolMessageChunk extends BaseMessageChunk {
387
/** ID of the tool call this chunk responds to */
388
tool_call_id: string;
389
/** Name of the tool */
390
name?: string;
391
/** Artifact from the tool */
392
artifact?: unknown;
393
394
getType(): "tool";
395
396
concat(chunk: ToolMessageChunk): ToolMessageChunk;
397
}
398
```
399
400
**Usage Examples:**
401
402
```typescript
403
import { AIMessageChunk } from "@langchain/core/messages";
404
405
// Streaming AI response
406
const chunk1 = new AIMessageChunk("Hello");
407
const chunk2 = new AIMessageChunk(" world");
408
const combined = chunk1.concat(chunk2); // "Hello world"
409
```
410
411
## Message Utilities
412
413
### Message Conversion Functions
414
415
```typescript { .api }
416
/**
417
* Convert various message-like inputs to BaseMessage instances
418
*/
419
function convertToMessage(message: BaseMessageLike): BaseMessage;
420
421
/**
422
* Convert array of message-like inputs to BaseMessage array
423
*/
424
function convertToMessages(messages: BaseMessageLike[]): BaseMessage[];
425
426
/**
427
* Get buffer string representation of messages
428
*/
429
function getBufferString(messages: BaseMessage[], humanPrefix?: string, aiPrefix?: string): string;
430
431
/**
432
* Convert message to OpenAI format
433
*/
434
function messageToOpenAIRole(message: BaseMessage): { role: string; content: string };
435
436
/**
437
* Convert various message-like inputs to BaseMessage
438
*/
439
function coerceMessageLikeToMessage(message: BaseMessageLike): BaseMessage;
440
441
/**
442
* Convert message to chunk for streaming
443
*/
444
function convertToChunk(message: BaseMessage): BaseMessageChunk;
445
446
/**
447
* Check if message is an AI message
448
*/
449
function isAIMessage(message: BaseMessage): message is AIMessage;
450
451
/**
452
* Check if message is a human message
453
*/
454
function isHumanMessage(message: BaseMessage): message is HumanMessage;
455
456
/**
457
* Check if message is a system message
458
*/
459
function isSystemMessage(message: BaseMessage): message is SystemMessage;
460
461
/**
462
* Check if message is a function message
463
*/
464
function isFunctionMessage(message: BaseMessage): message is FunctionMessage;
465
466
/**
467
* Check if message is a tool message
468
*/
469
function isToolMessage(message: BaseMessage): message is ToolMessage;
470
471
/**
472
* Check if message is a chat message
473
*/
474
function isChatMessage(message: BaseMessage): message is ChatMessage;
475
476
/**
477
* Default tool call parser for OpenAI-style tool calls
478
*/
479
function defaultToolCallParser(rawToolCalls: any[]): ToolCall[];
480
```
481
482
**Usage Examples:**
483
484
```typescript
485
import { convertToMessages, getBufferString } from "@langchain/core/messages";
486
487
// Convert mixed message types
488
const messages = convertToMessages([
489
"Hello there", // Becomes HumanMessage
490
["system", "You are helpful"], // Becomes SystemMessage
491
new AIMessage("How can I help?")
492
]);
493
494
// Get conversation as string
495
const conversationText = getBufferString(messages);
496
```
497
498
## Types
499
500
```typescript { .api }
501
type MessageContent = string | MessageContentComplex[];
502
503
interface MessageContentComplex {
504
type: "text" | "image_url";
505
text?: string;
506
image_url?: {
507
url: string;
508
detail?: "auto" | "low" | "high";
509
};
510
}
511
512
type MessageType = "human" | "ai" | "generic" | "developer" | "system" | "function" | "tool" | "remove";
513
514
interface ToolCall {
515
name: string;
516
args: Record<string, unknown>;
517
id: string;
518
}
519
520
interface ToolCallChunk {
521
name?: string;
522
args?: string;
523
id?: string;
524
index?: number;
525
}
526
527
interface InvalidToolCall {
528
name?: string;
529
args?: string;
530
id: string;
531
error: string;
532
}
533
534
interface UsageMetadata {
535
input_tokens: number;
536
output_tokens: number;
537
total_tokens: number;
538
}
539
540
interface StoredMessage {
541
type: MessageType;
542
content: MessageContent;
543
name?: string;
544
additional_kwargs?: Record<string, unknown>;
545
response_metadata?: Record<string, unknown>;
546
id?: string;
547
}
548
549
interface FunctionCall {
550
name: string;
551
arguments: string;
552
}
553
554
interface DirectToolOutput {
555
content: string;
556
artifact?: unknown;
557
}
558
559
interface MessageLikeDict {
560
role: string;
561
content: string;
562
}
563
564
type BaseMessageLike =
565
| BaseMessage
566
| string
567
| [string, string] // [role, content]
568
| { role: string; content: string };
569
```