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

Messages in State

Chat history.

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

Chatbots and agents work with a list of messages. The user's, the model's, and later, the tools'. So most LLM graphs keep a messages list in the state, and each node adds to it.

Messages in State
From the video: Messages in State
  • A list of messages
  • User, AI, tools
  • Kept in the state

A messages list

Our state has one key, messages, a list with operator add, so new messages are appended. The chat node sends the whole list to the model, and returns the reply as a one item list. Run it. The final state holds the user's message, and the model's reply, in order.

messages_state.pypython
import operator
from typing import Annotated, TypedDict
from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage
from langgraph.graph import StateGraph, START

model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)

class State(TypedDict):
    messages: Annotated[list, operator.add]

def chat(s):
    return {"messages": [model.invoke(s["messages"])]}

b = StateGraph(State); b.add_node(chat); b.add_edge(START, "chat")
out = b.compile().invoke({"messages": [HumanMessage("Name a cosy mystery novel. Title only.")]})
for m in out["messages"]:
    print(f"{m.type}: {m.text.strip()}")
Output
human: Name a cosy mystery novel. Title only.
ai: The Thursday Murder Club

Message types

You'll meet four message types. Human, from the user. AI, from the model, which may include tool calls. Tool, the result of a tool. And system, the instructions. A list of these is the whole conversation.

keyvalue
humanthe user
aithe model
toola tool's result
systeminstructions

Summary

LLM graphs keep a list of messages in the state, and nodes append to it. Next, add messages, the reducer made for message lists.

Key takeaways
  • messages key
  • Append replies
  • The whole conversation
Next up: add_messages — the message reducer