Merges two lists of messages, updating existing messages by ID.
By default, this ensures the state is "append-only", unless the new message has the same ID as an existing message.
add_messages(
left: Messages,
right: Messages,
*,
format: Literal['langchain-openai'] | None = None
) -> MessagesBasic usage:
from langchain_core.messages import AIMessage, HumanMessage
msgs1 = [HumanMessage(content="Hello", id="1")]
msgs2 = [AIMessage(content="Hi there!", id="2")]
add_messages(msgs1, msgs2)
# [HumanMessage(content='Hello', id='1'), AIMessage(content='Hi there!', id='2')]
Overwrite existing message:
msgs1 = [HumanMessage(content="Hello", id="1")]
msgs2 = [HumanMessage(content="Hello again", id="1")]
add_messages(msgs1, msgs2)
# [HumanMessage(content='Hello again', id='1')]
Use in a StateGraph:
from typing import Annotated
from typing_extensions import TypedDict
from langgraph.graph import StateGraph
class State(TypedDict):
messages: Annotated[list, add_messages]
builder = StateGraph(State)
builder.add_node("chatbot", lambda state: {"messages": [("assistant", "Hello")]})
builder.set_entry_point("chatbot")
builder.set_finish_point("chatbot")
graph = builder.compile()
graph.invoke({})
# {'messages': [AIMessage(content='Hello', id=...)]}
Use OpenAI message format:
from typing import Annotated
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, add_messages
class State(TypedDict):
messages: Annotated[list, add_messages(format="langchain-openai")]
def chatbot_node(state: State) -> list:
return {
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Here's an image:",
"cache_control": {"type": "ephemeral"},
},
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/jpeg",
"data": "1234",
},
},
],
},
]
}
builder = StateGraph(State)
builder.add_node("chatbot", chatbot_node)
builder.set_entry_point("chatbot")
builder.set_finish_point("chatbot")
graph = builder.compile()
graph.invoke({"messages": []})
# {
# 'messages': [
# HumanMessage(
# content=[
# {"type": "text", "text": "Here's an image:"},
# {
# "type": "image_url",
# "image_url": {"url": "data:image/jpeg;base64,1234"},
# },
# ],
# ),
# ]
# }| Name | Type | Description |
|---|---|---|
left* | Messages | The base list of |
right* | Messages | The list of |
format | Literal['langchain-openai'] | None | Default: NoneThe format to return messages in. If Requirement Must have |