Messages are the fundamental units of conversation in LangChain.js. They represent individual contributions to a dialogue, with each message having a specific role (human, AI, system, tool) and content.
Message classes are defined in @langchain/core/messages
import { HumanMessage } from "@langchain/core/messages";const message = new HumanMessage("Hello, how are you?");// Or with additional fieldsconst message = new HumanMessage({ content: "Hello, how are you?", name: "John", id: "msg_123",});
import { AIMessage, HumanMessage } from "@langchain/core/messages";if (AIMessage.isInstance(message)) { // TypeScript knows this is an AIMessage console.log(message.tool_calls);}if (HumanMessage.isInstance(message)) { // TypeScript knows this is a HumanMessage}
Avoid using instanceof directly. Use the static isInstance() methods instead.
import { HumanMessage, AIMessage } from "@langchain/core/messages";import { ChatOpenAI } from "@langchain/openai";const model = new ChatOpenAI();const history = [];// User messageconst userMessage = new HumanMessage("What's the capital of France?");history.push(userMessage);// Get AI responseconst aiResponse = await model.invoke(history);history.push(aiResponse);// Continue conversationconst followUp = new HumanMessage("What's its population?");history.push(followUp);const response2 = await model.invoke(history);history.push(response2);
import { getBufferString } from "@langchain/core/messages";const formatted = getBufferString(messages);// "Human: Hello\nAI: Hi there!\nHuman: How are you?"
Always use the correct message type for each role:
HumanMessage for user input
AIMessage for model responses
SystemMessage for instructions
ToolMessage for tool results
Maintain Message Order
Keep messages in chronological order. The conversation flow should be logical:
[ new SystemMessage("Instructions"), new HumanMessage("Question 1"), new AIMessage("Answer 1"), new HumanMessage("Question 2"), new AIMessage("Answer 2"),]
Use IDs for Tool Calls
Always include id and tool_call_id for proper tool call tracking:
import { SystemMessage, HumanMessage } from "@langchain/core/messages";const messages = [ new SystemMessage("You are a helpful coding assistant."), new HumanMessage("How do I sort an array in JavaScript?"),];const response = await model.invoke(messages);