Message-based graph state
Build a conversational workflow where each node contributes messages to a shared conversation state.
AI Agents · Const
MessagesAnnotation is a prebuilt LangGraph state annotation for accumulating messages across graph nodes. It supports standard messages and special modifiers such as RemoveMessage.
MessagesAnnotation is a prebuilt LangGraph state annotation for a messages array. It combines messages returned by nodes and supports both ordinary messages and RemoveMessage-based modifications.
const graph = new StateGraph(MessagesAnnotation)A state annotation whose state contains a messages array and whose reducer combines returned messages.
@langchain/langgraph package.StateGraph to make it the graph's state schema.messages field.import { MessagesAnnotation, StateGraph, START, END } from "@langchain/langgraph";
const graph = new StateGraph(MessagesAnnotation)
.addNode("reply", (state) => ({
messages: [{ role: "ai", content: `Received: ${state.messages.at(-1)?.content}` }],
}))
.addEdge(START, "reply")
.addEdge("reply", END)
.compile();
const result = await graph.invoke({
messages: [{ role: "user", content: "Hello" }],
});
console.log(result.messages.at(-1)?.content);Creates a graph whose state uses MessagesAnnotation, appends an AI response, and invokes the compiled graph.
Build a conversational workflow where each node contributes messages to a shared conversation state.
Implement agent loops in which model responses, tool calls, and tool results travel through one state key.
Extend message state with application-specific fields by spreading MessagesAnnotation.spec into a larger annotation schema.
MessagesAnnotation is a prebuilt state annotation that combines messages returned by graph nodes. A StateGraph can receive it directly, so nodes read and update the typed messages state key.
Follow-up: How can a graph add other state fields? Answer: create a root annotation that spreads MessagesAnnotation.spec and adds annotations for the additional fields.
A node can return either one message or an array under the messages key. The annotation combines that returned content with the existing message state rather than replacing the conversation by default.
Follow-up: What should a node return when it has no message update? Answer: return a partial state object without messages, leaving the existing message state unchanged.
Import it from @langchain/langgraph and pass it to new StateGraph(MessagesAnnotation). After adding nodes and edges, compile the graph before invoking it.
Follow-up: How can tool execution be added? Answer: route tool-call-producing AI messages to a tool node, then return tool messages through the same messages state key.
StateGraphAnnotationRemoveMessageToolNodeBaseMessage