AI Hints
Home›LangGraph Tutorial›Models and Messages
LangGraph · Lesson 27 of 120

add_messages

The message reducer.

⏱ 2 min read▶ Video at 28:30🎓 Free
Watch this lesson in the LangGraph courseWatch on YouTube ↗Full LangGraph course

Operator add works, but LangGraph has a smarter reducer for messages, called add messages. It appends new messages, turns simple dictionaries into message objects, and replaces a message that has the same ID.

add_messages
From the video: add_messages
  • A smarter reducer
  • Appends and converts
  • Replaces by ID

Trying add_messages

Add messages is a plain function, so we can call it directly. First we append a dictionary, and it becomes a proper AI message, with its own ID. Then we send a new message with the same ID as the reply. Run it. The first call appends. The second call replaces the old reply, instead of adding a duplicate.

add_messages.pypython
from langchain.messages import AIMessage, HumanMessage
from langgraph.graph.message import add_messages

history = [HumanMessage("Is Dune in stock?", id="1")]

history = add_messages(history, [{"role": "ai", "content": "Let me check.", "id": "2"}])
print([(m.type, m.text) for m in history])

history = add_messages(history, [AIMessage("Yes, 3 copies!", id="2")])
print([(m.type, m.text) for m in history])
Output
[('human', 'Is Dune in stock?'), ('ai', 'Let me check.')]
[('human', 'Is Dune in stock?'), ('ai', 'Yes, 3 copies!')]

Why add_messages

Use add messages for any messages key. It accepts dictionaries, so inputs are short. It gives every message an ID. And replacing by ID lets you edit or correct messages later, which matters for human in the loop.

keyvalue
Appendsnew messages
Convertsdicts to messages
IDson every message
Replacessame ID

Summary

Add messages appends, converts dictionaries, and replaces messages with the same ID. Use it for every message list. Next, a ready made state that uses it.

Key takeaways
  • Annotated[list, add_messages]
  • Dicts become messages
  • Same ID replaces
Next up: MessagesState — ready-made state