MessagesState and add_messages
Overview
Imagine building a customer support chatbot that receives the following conversation:
Customer: My name is Priya, and my order number is ORD-1042.
Assistant: Hello Priya! How can I help with your order?
Customer: Can you tell me which order number I mentioned?
Assistant: You mentioned order number ORD-1042.The assistant’s second response depends on information supplied during an earlier interaction. Without access to conversation history, the model cannot reliably determine which order the customer is referring to.
A chat model does not automatically remember every previous API request. Your application must supply the relevant conversation context when generating subsequent responses.
In LangGraph, conversation history can be represented as a field in graph state. However, storing messages is only part of the problem. The application must also decide how new messages are combined with existing messages, how corrections are applied, and how outdated information is removed.
In the previous lesson, Reducers and Annotated types, you learned that reducers control how state updates are merged into existing state.
This lesson applies that concept to conversation management through two fundamental LangGraph components:
MessagesState: a predefined state schema designed for message-based applications.add_messages: a specialized reducer that understands message identity, replacement, and removal.
Together with checkpointing, these components provide the foundation for stateful chatbots, conversational RAG systems, customer support assistants, and multi-step AI agents.
By the end of this lesson, you will have built a conversational application that maintains history across requests, separates different conversations, and supports modifications to previously stored messages.
Environment setup
Install the required packages in your Python environment:
pip install -U "langgraph>=1,<2" "langchain>=1,<2" langchain-openaiFor examples that call an OpenAI model, configure your API key:
export OPENAI_API_KEY="your-api-key"On Windows PowerShell:
$env:OPENAI_API_KEY="your-api-key"The examples use the LangGraph 1.x and LangChain 1.x APIs. Examples that construct messages directly do not require an API key. Model-generated responses are illustrative and depend on model availability and account access.
Understanding message objects
Conversation history should generally contain structured message objects rather than a list of unstructured strings.
Consider the following message types:
| Message type | Purpose | Example |
|---|---|---|
HumanMessage |
Represents user input | Where is my order? |
AIMessage |
Represents assistant output | Your order is being processed. |
SystemMessage |
Provides behavioral instructions | You are a support assistant. |
ToolMessage |
Represents a tool execution result | Order status: shipped |
RemoveMessage |
Requests removal from message state | Remove message with ID msg-1 |
These classes are available through the public langchain.messages module.
The following example constructs a conversation without calling a language model.
from langchain.messages import (
HumanMessage,
AIMessage,
SystemMessage,
)
messages = [
SystemMessage(content="You are a helpful support assistant."),
HumanMessage(content="My order number is ORD-1042."),
AIMessage(content="How can I help with your order?"),
]
for message in messages:
print(f"{message.type}: {message.content}")Expected output:
system: You are a helpful support assistant.
human: My order number is ORD-1042.
ai: How can I help with your order?Message objects preserve information beyond text, including message IDs, tool calls, usage metadata, and structured content where applicable.
This becomes particularly important when building agents that interact with external tools. An assistant message containing a tool request cannot be treated as interchangeable with an ordinary text response.
See the LangChain message API reference for the available message types.
Why not operator.add?
In the previous lesson, you learned how to use operator.add to accumulate list values.
For example, a conversation state could be defined as:
import operator
from typing import Annotated, TypedDict
from langchain.messages import AnyMessage
class ChatState(TypedDict):
messages: Annotated[list[AnyMessage], operator.add]This works for straightforward list concatenation. Whenever a node returns a new list of messages, those messages are appended to the existing list.
However, conversation history is not always append-only.
Imagine a customer initially submits an incorrect order number. Your application receives a corrected version of that message. Ideally, the existing message should be replaced rather than storing both versions as separate conversational events.
The operator.add reducer cannot recognize that two messages represent the same logical message.
Demonstrating the problem
The following example compares ordinary list concatenation with the specialized message reducer.
import operator
from langchain.messages import HumanMessage
from langgraph.graph.message import add_messages
existing = [
HumanMessage(
content="My order number is ORD-1000.",
id="order-message",
)
]
correction = [
HumanMessage(
content="My order number is ORD-1042.",
id="order-message",
)
]
ordinary_result = operator.add(existing, correction)
message_result = add_messages(existing, correction)
print("Using operator.add:")
for message in ordinary_result:
print(message.id, message.content)
print("\nUsing add_messages:")
for message in message_result:
print(message.id, message.content)Expected output:
Using operator.add:
order-message My order number is ORD-1000.
order-message My order number is ORD-1042.
Using add_messages:
order-message My order number is ORD-1042.The difference is message identity.
Both messages have the same ID. The add_messages reducer interprets the incoming message as a replacement for the existing message.
The original message’s position in the conversation is preserved.
Comparing reducer strategies
| Behavior | Default reducer | operator.add |
add_messages |
|---|---|---|---|
| Handle a new list update | Replace existing list | Concatenate lists | Merge messages |
| Preserve previous messages | No | Yes | Yes |
| Recognize message IDs | No | No | Yes |
| Replace matching IDs | No | No | Yes |
| Normalize supported message representations | No | No | Yes |
Process RemoveMessage |
No | No | Yes |
| Recommended use | Ordinary state fields | Generic accumulation | Conversation history |
The default reducer is useful when a field represents a single current value, such as a classification result.
operator.add is appropriate for accumulating independent values, such as search results or execution logs.
For conversation history, add_messages is usually the correct choice because messages have both content and identity.
How add_messages works internally
Conceptually, add_messages receives two inputs:
- The existing collection of messages.
- An incoming message or collection of message updates.
It normalizes supported message representations, ensures messages have IDs when necessary, and merges incoming updates according to their identity.
For ordinary message updates, the rules are:
- If the incoming message has a new ID, append it.
- If its ID matches an existing message, replace that message.
- If the update is a
RemoveMessage, remove the corresponding message. - If a supported reset marker is supplied, clear the previous history.
The following diagram illustrates the reducer’s conceptual decision process.
An ID identifies a message, not its textual content. Two messages with identical content but different IDs are considered distinct messages.
Similarly, replacing an existing ID replaces the message object; it is not a field-by-field merge of its metadata.
The precise public behavior is documented in the add_messages API reference.
MessagesState
Because conversation history is so common in agentic applications, LangGraph provides a predefined schema called MessagesState.
You can import it directly:
from langgraph.graph import MessagesStateConceptually, it is equivalent to the following state definition:
from typing import Annotated, TypedDict
from langchain.messages import AnyMessage
from langgraph.graph.message import add_messages
class CustomMessagesState(TypedDict):
messages: Annotated[list[AnyMessage], add_messages]The annotation combines two responsibilities:
list[AnyMessage]describes the expected state value.add_messagesspecifies how updates to that value are merged.
You do not need to redefine this schema in every conversational application. MessagesState already provides it.
It is a state schema, not a database, language model, or memory service.
Message normalization
Applications frequently receive messages as JSON-compatible dictionaries through REST APIs or frontend interfaces.
The message reducer supports common message representations and converts them into LangChain message objects.
The following example demonstrates this normalization.
from langchain.messages import HumanMessage, AIMessage
from langgraph.graph.message import add_messages
history = add_messages(
[],
[
{"role": "user", "content": "Hello!"},
{"role": "assistant", "content": "How can I help?"},
],
)
print(isinstance(history[0], HumanMessage))
print(isinstance(history[1], AIMessage))
for message in history:
print(message.type, message.content, bool(message.id))Expected output:
True
True
human Hello! True
ai How can I help? TrueOnce normalized, access message attributes using dot notation:
history[-1].content
history[-1].id
history[-1].typeThis gives nodes a consistent interface regardless of whether supported dictionaries or message objects were originally submitted.
At an application boundary, however, validate client input and assign permitted roles yourself. Do not allow an untrusted client to submit arbitrary system messages or fabricated tool results.
Extending MessagesState
Real-world agents often need more than conversation history.
A customer support assistant might also track:
- The detected support category.
- The current order number.
- Whether human intervention is required.
- Retrieved knowledge base documents.
You can extend MessagesState using inheritance.
The following runnable example adds an ordinary state field alongside the reducer-managed message history.
from langchain.messages import HumanMessage, AIMessage
from langgraph.graph import StateGraph, MessagesState, START, END
class SupportState(MessagesState):
category: str
def classify(state: SupportState):
text = state["messages"][-1].content.lower()
category = "billing" if "refund" in text else "general"
return {"category": category}
def respond(state: SupportState):
return {
"messages": [
AIMessage(
content=f"Your support category is {state['category']}."
)
]
}
builder = StateGraph(SupportState)
builder.add_node("classify", classify)
builder.add_node("respond", respond)
builder.add_edge(START, "classify")
builder.add_edge("classify", "respond")
builder.add_edge("respond", END)
graph = builder.compile()
result = graph.invoke({
"messages": [
HumanMessage(content="I would like a refund.")
]
})
print(result["category"])
print(result["messages"][-1].content)
print("Message count:", len(result["messages"]))Expected output:
billing
Your support category is billing.
Message count: 2The classify node updates only category. The respond node updates only messages.
LangGraph preserves fields that are not included in a node’s update. Each field follows its own reducer behavior.
This is a powerful pattern: conversation history accumulates while ordinary state fields can hold the latest business information.
A stateful conversational app
Let us build the hands-on project for this chapter: a multi-turn customer support assistant.
We will use:
MessagesStatefor conversation history.StateGraphfor orchestration.- A chat model for generating responses.
InMemorySaverfor thread-level checkpointing.
The application has a single processing node, making it easy to understand how conversation state behaves before introducing more complex graph architectures.
Application architecture
For each user request, the graph restores the thread’s existing state, merges the new message, invokes the model, and saves the updated state.
The following diagram illustrates the application’s execution and persistence flow.
Although the graph itself contains only one application node, LangGraph manages state restoration, merging, and checkpointing around its execution.
Implementing the application
The following complete program creates a chatbot and sends two messages to the same conversation thread.
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage, SystemMessage
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.checkpoint.memory import InMemorySaver
model = init_chat_model("openai:gpt-5.4-mini")
def chatbot(state: MessagesState):
instructions = SystemMessage(
content=(
"You are a professional customer support assistant. "
"Use the conversation history to answer follow-up questions. "
"Do not invent customer or order information."
)
)
response = model.invoke([
instructions,
*state["messages"],
])
return {"messages": [response]}
builder = StateGraph(MessagesState)
builder.add_node("chatbot", chatbot)
builder.add_edge(START, "chatbot")
builder.add_edge("chatbot", END)
checkpointer = InMemorySaver()
graph = builder.compile(checkpointer=checkpointer)
config = {
"configurable": {
"thread_id": "support-conversation-001"
}
}
result = graph.invoke(
{
"messages": [
HumanMessage(
content="My name is Priya. My order number is ORD-1042."
)
]
},
config=config,
)
print("Assistant:", result["messages"][-1].content)
result = graph.invoke(
{
"messages": [
HumanMessage(
content="What is my name and order number?"
)
]
},
config=config,
)
print("Assistant:", result["messages"][-1].content)
print("Stored messages:", len(result["messages"]))Illustrative output:
Assistant: Hello Priya! How can I help with order ORD-1042?
Assistant: Your name is Priya, and your order number is ORD-1042.
Stored messages: 4The exact generated wording may vary. The history should contain two human messages and two assistant messages after both successful invocations.
Step 1: Define conversation state
builder = StateGraph(MessagesState)This establishes a message-aware state channel. LangGraph knows that updates to messages must be processed using add_messages.
Step 2: Read existing conversation history
Inside the chatbot node:
state["messages"]This represents the conversation available to the current graph execution, including the newly supplied user message.
The node passes that history to the model, providing the context required to answer follow-up questions.
The system instruction is constructed separately for each model call. It controls the assistant’s behavior without accumulating duplicate system messages in checkpointed conversation history.
Step 3: Return only the new assistant message
return {"messages": [response]}This is the recommended update pattern.
The node produces a new assistant message. The reducer takes responsibility for merging it with existing conversation history.
Avoid manually appending to or mutating the state object. Treat incoming state as read-only and express changes through returned updates.
Step 4: Enable checkpointing
graph = builder.compile(checkpointer=InMemorySaver())A checkpointer saves graph state at execution boundaries.
When another request uses the same thread ID, LangGraph can restore the latest checkpoint and continue the conversation.
Note:
MessagesStatedoes not provide cross-invocation persistence by itself. The message reducer controls merging, while the checkpointer provides state continuity between graph runs.
Carrying the conversation forward
Understanding thread IDs
A thread represents an independent sequence of graph executions.
The thread ID tells the checkpointer which conversation state to load and update.
Consider two customers using the same support application:
| Thread ID | Conversation context |
|---|---|
customer-a |
Order ORD-1042 |
customer-b |
Refund request |
customer-c |
Shipping address change |
All customers can use the same compiled graph while maintaining independent conversation histories.
The application should reuse a thread ID when continuing a conversation and allocate a new one when creating a separate conversation.
A thread ID identifies the conversation; it is not proof that a caller is authorized to access it.
Demonstrating conversation continuity
The following runnable example uses a deterministic assistant instead of a language model. This allows you to verify state behavior without API costs or unpredictable model responses.
from langchain.messages import HumanMessage, AIMessage
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.checkpoint.memory import InMemorySaver
def assistant(state: MessagesState):
count = sum(
isinstance(message, HumanMessage)
for message in state["messages"]
)
return {
"messages": [
AIMessage(content=f"User messages received: {count}")
]
}
builder = StateGraph(MessagesState)
builder.add_node("assistant", assistant)
builder.add_edge(START, "assistant")
builder.add_edge("assistant", END)
graph = builder.compile(checkpointer=InMemorySaver())
thread_a = {"configurable": {"thread_id": "customer-a"}}
thread_b = {"configurable": {"thread_id": "customer-b"}}
def send_message(text, config):
result = graph.invoke(
{"messages": [HumanMessage(content=text)]},
config=config,
)
print(result["messages"][-1].content)
send_message("Hello!", thread_a)
send_message("I need help with my order.", thread_a)
send_message("I would like a refund.", thread_b)
send_message("When will my order arrive?", thread_a)
print(
"Thread A history:",
len(graph.get_state(thread_a).values["messages"]),
)
print(
"Thread B history:",
len(graph.get_state(thread_b).values["messages"]),
)Expected output:
User messages received: 1
User messages received: 2
User messages received: 1
User messages received: 3
Thread A history: 6
Thread B history: 2This demonstrates that each thread maintains its own state independently.
The calls for customer B do not modify customer A’s conversation.
Submit only the new user message
When checkpointing is enabled, the application generally needs to send only the latest message:
graph.invoke(
{"messages": [HumanMessage(content="What did I ask earlier?")]},
config=config,
)Do not repeatedly reconstruct and submit the entire conversation unless you deliberately manage message IDs and synchronization.
Resubmitting previous messages with new or missing IDs can introduce duplicate history.
Reusing stable IDs can prevent duplicate message entries, but it does not guarantee that repeated graph invocations will avoid duplicate model calls or external side effects.
Inspecting stored conversation history
The get_state() method retrieves a checkpointed state snapshot.
Using the preceding application:
snapshot = graph.get_state(thread_a)
for message in snapshot.values["messages"]:
print(message.type, message.id, message.content)The resulting output includes message roles, IDs, and content.
This is useful for displaying conversation transcripts, debugging unexpected responses, and identifying messages that need modification.
Historical checkpoints can also be inspected using get_state_history(config). We will explore checkpoint histories and durable execution in later chapters.
For production applications, replace InMemorySaver with an appropriate persistent checkpointer, such as PostgresSaver. In-memory checkpoints are suitable for development but disappear when their hosting process terminates.
The LangGraph checkpointer documentation explains thread persistence and state inspection in greater detail.
Editing and removing messages
Conversation history sometimes needs to change after messages have already been stored.
Common scenarios include:
- Correcting an incorrectly captured user message.
- Applying a human-reviewed assistant response.
- Removing irrelevant or outdated conversation turns.
- Resetting the conversation.
- Managing the amount of history supplied to the model.
The add_messages reducer supports these operations through message identity and explicit removal instructions.
Editing an existing message
To replace a message, submit another message with the same ID.
The following complete example demonstrates message editing, removal, and conversation reset directly through the reducer.
from langchain.messages import HumanMessage, AIMessage, RemoveMessage
from langgraph.graph.message import add_messages, REMOVE_ALL_MESSAGES
history = add_messages(
[],
[
HumanMessage(
content="My order number is ORD-1000.",
id="msg-1",
),
AIMessage(
content="Thank you for providing your order number.",
id="msg-2",
),
],
)
history = add_messages(
history,
[
HumanMessage(
content="My order number is ORD-1042.",
id="msg-1",
)
],
)
print("After editing:", history[0].content)
print("Message count:", len(history))
history = add_messages(
history,
[RemoveMessage(id="msg-2")],
)
print("After removal:", len(history))
history = add_messages(
history,
[RemoveMessage(id=REMOVE_ALL_MESSAGES)],
)
print("After reset:", history)Expected output:
After editing: My order number is ORD-1042.
Message count: 2
After removal: 1
After reset: []Notice that editing does not increase the number of messages.
Also notice that removing a message requires a special update. Returning an empty list to an add_messages field does not clear existing history.
An empty list simply means there are no incoming messages to merge.
Modifying checkpointed graph state
When a graph uses checkpointing, you can modify its saved state through update_state() without executing the chatbot node.
The following complete example demonstrates how an application can correct a previously saved user message.
from langchain.messages import HumanMessage, AIMessage, RemoveMessage
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.graph.message import REMOVE_ALL_MESSAGES
from langgraph.checkpoint.memory import InMemorySaver
def chatbot(state: MessagesState):
return {
"messages": [
AIMessage(
content="Thank you for the information.",
id="assistant-1",
)
]
}
builder = StateGraph(MessagesState)
builder.add_node("chatbot", chatbot)
builder.add_edge(START, "chatbot")
builder.add_edge("chatbot", END)
graph = builder.compile(checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "editable-chat"}}
graph.invoke(
{
"messages": [
HumanMessage(
content="My name is Anita.",
id="user-1",
)
]
},
config=config,
)
graph.update_state(
config,
{
"messages": [
HumanMessage(content="My name is Ananya.", id="user-1")
]
},
as_node="chatbot",
)
print(graph.get_state(config).values["messages"][0].content)
graph.update_state(
config,
{"messages": [RemoveMessage(id="assistant-1")]},
as_node="chatbot",
)
print(len(graph.get_state(config).values["messages"]))
graph.update_state(
config,
{"messages": [RemoveMessage(id=REMOVE_ALL_MESSAGES)]},
as_node="chatbot",
)
print(graph.get_state(config).values["messages"])Expected output:
My name is Ananya.
1
[]The update_state() method applies updates through the graph’s reducers and creates an updated checkpoint.
The as_node argument specifies which node the update is attributed to. This can influence subsequent execution routing, which is why it must be selected carefully in graphs containing multiple nodes.
Editing an earlier user message does not automatically regenerate subsequent assistant responses. If those responses relied on the original information, the application must explicitly remove, regenerate, or otherwise reconcile them.
Note: Removing a message from the latest state is not equivalent to permanently deleting it from storage. Earlier checkpoints, traces, logs, or backups may still contain the original content.
Removing messages safely
When deleting messages, preserve a conversation structure that the model provider accepts.
This becomes essential when working with tool-calling agents.
An assistant message requesting a tool execution and its corresponding ToolMessage results are logically connected.
Removing one while retaining the other can create invalid model input. Preserve or remove the complete tool interaction, including all associated tool results.
Similarly, when removing old conversational turns, prefer meaningful boundaries rather than deleting arbitrary messages from the middle of a conversation.
Check whether the remaining history starts with an appropriate message type and whether every retained tool interaction is complete.
See the LangGraph memory management documentation for message deletion and context management patterns.
Managing conversation history in production
Controlling conversation growth
Checkpointing allows conversations to accumulate across many requests.
However, an unlimited message history creates several practical problems:
- Increasing model input token costs.
- Longer response latency.
- Context window exhaustion.
- Reduced relevance caused by outdated information.
- Increased checkpoint storage requirements.
A production assistant should distinguish between its stored conversation history and the context selected for an individual model call.
You can retain the complete conversation while supplying only relevant recent messages to the model. Alternatively, you can summarize older turns or deliberately remove unnecessary messages from active state.
These strategies have different effects:
| Strategy | Stored history | Model input |
|---|---|---|
| Context trimming | Preserved | Reduced |
| Summarization | Depends on implementation | Condensed |
| Message removal | Modified | Reduced when using updated history |
| Conversation reset | Cleared from active state | Starts fresh |
For tool-based conversations, context trimming must preserve valid tool-call and tool-result relationships.
Common mistakes
Using operator.add for conversation history. This prevents meaningful replacement and removal operations.
Compiling without a checkpointer. History merges during a graph run but is not automatically restored during subsequent independent invocations.
Generating a new thread ID for every request. Every request begins a separate conversation.
Sharing a thread ID across unrelated users. This risks mixing conversations and exposing sensitive information.
Using message content as an identifier. Messages with identical text can represent different events.
Returning {"messages": []} to reset history. Use an explicit removal marker instead.
Assigning the same ID to every new assistant message. This unintentionally replaces earlier responses.
Deleting individual tool messages without considering their corresponding tool calls. This can produce invalid conversation sequences.
Production best practices
Generate stable, unique message identifiers when clients need to reference or edit specific messages.
Validate incoming messages at the application boundary and restrict which roles clients are allowed to submit.
Keep authorization checks separate from checkpoint lookup. Verify that the authenticated user owns or is permitted to access the requested thread.
Use a persistent checkpointer for applications that must survive process restarts. Define explicit retention, deletion, and access policies for sensitive conversation data.
Coordinate concurrent requests that modify the same conversation to prevent conflicting updates or confusing response ordering.
Finally, test reducer behavior separately from language model behavior. Deterministic tests can verify message counts, replacement semantics, deletion, and thread isolation without depending on generated text.
The APIs used throughout this lesson have been checked against the LangGraph 1.x and LangChain 1.x reference documentation. The examples are designed to run with the listed dependencies, but live model calls have not been executed here.
Connecting state management to graph nodes
Throughout this chapter, you have progressed from understanding graph state to defining schemas, applying reducers, and managing structured conversation history.
MessagesState combines these concepts into a practical foundation for conversational AI applications.
The next lesson, Nodes — sync, async and what they receive, moves from designing state to implementing the functions that operate on it.
You will learn how nodes receive state, produce partial updates, access runtime context, and execute synchronous or asynchronous operations.
The conversation management patterns introduced here will continue to apply as you build graphs with multiple nodes, conditional routing, tool execution, and human-in-the-loop workflows.
Build a Stateful Support Assistant
Build a conversational support assistant using MessagesState, StateGraph, and InMemorySaver. Enable the assistant to maintain separate conversation histories for different threads and demonstrate that previous user messages remain available across invocations. Implement message editing, individual message removal, and conversation reset using the appropriate message IDs.
from langchain.messages import HumanMessage, AIMessage, RemoveMessage
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.graph.message import REMOVE_ALL_MESSAGES
from langgraph.checkpoint.memory import InMemorySaver
def assistant(state: MessagesState):
# TODO: Count HumanMessage objects in the conversation.
# TODO: Return an AIMessage containing the number of user messages.
# Return only the new message.
raise NotImplementedError
builder = StateGraph(MessagesState)
# TODO: Register the assistant node.
# TODO: Connect START -> assistant -> END.
# TODO: Compile with InMemorySaver.
thread_a = {"configurable": {"thread_id": "customer-a"}}
thread_b = {"configurable": {"thread_id": "customer-b"}}
# TODO: Send two messages to thread_a.
# Assign explicit IDs to the user messages.
# TODO: Send one message to thread_b.
# Verify that the threads have separate histories.
# TODO: Edit the first user message in thread_a.
# TODO: Remove the first user-assistant message pair.
# TODO: Reset the conversation in thread_a.
# TODO: Verify that thread_b remains unchanged.from langchain.messages import HumanMessage, AIMessage, RemoveMessage
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.graph.message import REMOVE_ALL_MESSAGES
from langgraph.checkpoint.memory import InMemorySaver
def assistant(state: MessagesState):
user_messages = [
message
for message in state["messages"]
if isinstance(message, HumanMessage)
]
response = AIMessage(
content=f"You have sent {len(user_messages)} user messages."
)
return {"messages": [response]}
builder = StateGraph(MessagesState)
builder.add_node("assistant", assistant)
builder.add_edge(START, "assistant")
builder.add_edge("assistant", END)
graph = builder.compile(checkpointer=InMemorySaver())
thread_a = {"configurable": {"thread_id": "customer-a"}}
thread_b = {"configurable": {"thread_id": "customer-b"}}
result_a1 = graph.invoke(
{"messages": [
HumanMessage(content="I need help with my order.", id="a-1")
]},
config=thread_a,
)
result_a2 = graph.invoke(
{"messages": [
HumanMessage(content="My order is delayed.", id="a-2")
]},
config=thread_a,
)
result_b = graph.invoke(
{"messages": [
HumanMessage(content="How can I request a refund?", id="b-1")
]},
config=thread_b,
)
print("Thread A:", result_a2["messages"][-1].content)
print("Thread B:", result_b["messages"][-1].content)
assert len(result_a2["messages"]) == 4
assert len(result_b["messages"]) == 2
# Edit the first user message without increasing history length.
graph.update_state(
thread_a,
{"messages": [
HumanMessage(
content="I need help with order ORD-1042.",
id="a-1",
)
]},
as_node="assistant",
)
history_a = graph.get_state(thread_a).values["messages"]
assert history_a[0].content == "I need help with order ORD-1042."
assert len(history_a) == 4
print("Edited message:", history_a[0].content)
# Remove the first complete conversational turn.
graph.update_state(
thread_a,
{"messages": [
RemoveMessage(id=message.id)
for message in history_a[:2]
]},
as_node="assistant",
)
remaining = graph.get_state(thread_a).values["messages"]
assert len(remaining) == 2
assert remaining[0].id == "a-2"
print("Remaining messages:", len(remaining))
# Clear the active message history.
graph.update_state(
thread_a,
{"messages": [RemoveMessage(id=REMOVE_ALL_MESSAGES)]},
as_node="assistant",
)
assert graph.get_state(thread_a).values["messages"] == []
assert len(graph.get_state(thread_b).values["messages"]) == 2
print("Thread A has been reset.")
print("Thread B remains unchanged.")
print("All assertions passed.")Summary
- MessagesState is a predefined state schema for managing conversation history in LangGraph.
- The add_messages reducer appends new messages and replaces existing messages that share the same ID.
- Unlike operator.add, add_messages supports message normalization, replacement, and removal.
- Nodes should return only new or intentionally modified messages rather than reconstructing the entire conversation.
- A checkpointer and a consistent thread ID enable conversation history to survive across graph invocations.
- RemoveMessage and REMOVE_ALL_MESSAGES allow applications to modify or clear their active message history.
- Production conversational applications must manage context size, thread isolation, message consistency, and checkpoint retention.