Put a Model in a Node
A graph becomes an assistant when one of its nodes calls a language model. That needs three things: an object that talks to the model, a way to write the conversation as a list of messages, and a rule for how each new message joins the list kept in the state. This page explains each of them, and a stand-in model that lets a graph run the same way every time.
A chat model: one interface over many providers
Every model provider has its own HTTP API, with its own request format, field names and way of returning tool calls. Writing that code by hand for each provider ties the whole program to one of them. LangChain hides these differences behind a chat model: a Python object with the same methods whichever provider is behind it. Each provider package implements that interface in a class whose name starts with Chat, such as ChatOpenAI.
The method you use most is invoke(). You pass it a list of messages, which is the conversation so far, and it waits for the model to finish and returns one message: the reply of the model, as an AIMessage object. The chat model turns your messages into the provider's request format on the way out and turns the provider's response back into a message on the way in.
- Your code
- Chat model
- Provider API
- Your code to Chat model: invoke(list of messages)
- Chat model to Provider API: request in the provider format
- Provider API to Chat model: response in the provider format
- Chat model to Your code: AIMessage
Because every chat model answers the same call, code that uses one does not change when the provider does. A graph node that calls model.invoke(messages) works with any chat model you hand it.
LangGraph itself does not depend on any of this. It is a library for graphs of state and steps, and a node is a plain function: it may call a provider's own SDK, send an HTTP request, or not call a model at all. LangChain chat models are simply a convenient way to fill a node with a model call, which is why the LangGraph documentation uses them in its examples.
True or false?
A LangGraph node can only call a model through a LangChain chat model.
False. A node is a plain Python function, so it can call a model any way it likes. LangGraph works with LangChain chat models but does not require them.
Calling invoke() on a chat model with a list of messages returns one AIMessage once the model has finished its reply.
True. invoke() waits for the full response and returns it as a single AIMessage, whichever provider produced it.
One class, many endpoints: the OpenAI-compatible setup
Many providers, and servers that run models on your own machine, accept requests in the same format as the OpenAI API. Such an endpoint is called OpenAI-compatible. For all of them, one chat model class is enough: ChatOpenAI from the langchain-openai package. Three settings decide where it sends its requests and what it asks for:
base_url: the address of the API. Left empty, it is the official OpenAI API; set it, and the same class talks to any compatible server.api_key: the key that endpoint expects. A local server often accepts any placeholder value.model: the name of the model, as that endpoint knows it.
import os
from langchain_openai import ChatOpenAI
model = ChatOpenAI(
base_url=os.environ["MODEL_BASE_URL"], # e.g. http://localhost:8000/v1
api_key=os.environ["MODEL_API_KEY"],
model=os.environ["MODEL_NAME"],
)Reading the three values from the environment keeps them out of the code. Switching from a hosted provider to a local model is then a change of configuration, not of program. LangChain and the OpenAI SDK also read an address of their own from the OPENAI_API_BASE and OPENAI_BASE_URL environment variables. An explicit base_url wins over both, so the address you pass is the one that is used.
- ChatOpenAI base_url, api_key, model
- OpenAI API base_url left empty
- Hosted compatible provider its base URL
- Local model server http://localhost:.../v1
- ChatOpenAI to OpenAI API
- ChatOpenAI to Hosted compatible provider
- ChatOpenAI to Local model server
The shared format has a limit. ChatOpenAI follows the official OpenAI specification and reads only the fields it defines. Some providers add fields of their own to a response, for example a separate field that carries the model's reasoning. ChatOpenAI does not extract or keep such a field: the reply arrives with its text and tool calls, and the extra is lost. A feature that only one provider offers therefore may not come through the compatible route. When you need it, the provider's own LangChain package, which knows its extensions, is the way to reach it.
The common ground is wide, though. Plain text replies and tool calling are part of the shared format, so a graph that relies only on them runs on any endpoint that supports tool calling.
True or false?
Pointing ChatOpenAI at another provider with base_url gives access to every feature that provider offers.
False. ChatOpenAI reads only what the official OpenAI specification defines. Non-standard response fields of other providers are not extracted or preserved.
With base_url, api_key and model read from the environment, the same code can run against a hosted provider or a local server.
True. Only the three values change. The chat model and everything that calls it stay the same.
Message objects: the roles of a conversation
A request to a chat model is a list of messages, and each message has a role that tells the model who is speaking. LangChain gives each role its own class, defined in langchain_core.messages:
| Class | Role in the request | What it holds |
|---|---|---|
| SystemMessage | system | Instructions on how the model should behave, usually first in the list |
| HumanMessage | user | What the person typed |
| AIMessage | assistant | A reply of the model: text, tool calls, or both, plus metadata |
| ToolMessage | tool | The result of one tool call, linked to it by tool_call_id |
A conversation is these objects in order. The system message sets the rules, then human and AI messages alternate as the exchange goes on.
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
messages = [
SystemMessage("You are a support assistant. Answer briefly."),
HumanMessage("Where is my order?"),
AIMessage("Could you give me the order number?"),
HumanMessage("It is 1042."),
]
reply = model.invoke(messages)
print(reply.content)The reply is an AIMessage. Its content holds the text, its tool_calls lists the tools the model asks for (empty when it asks for none), and its id identifies the message, set by the provider or generated by LangChain. A ToolMessage answers one of those calls, and its tool_call_id must match the id of the call in the AIMessage, so the model can tell which result belongs to which request.
You do not always have to build the objects yourself. Wherever LangChain accepts messages, a dictionary in the OpenAI format such as {"role": "user", "content": "Hi"} is turned into the matching class: "user" becomes a HumanMessage, "assistant" an AIMessage, "system" a SystemMessage and "tool" a ToolMessage.
True or false?
The reply of a chat model is a HumanMessage, because it is answering the person.
False. A HumanMessage is what the person says. Whatever the model produces comes back as an AIMessage.
A ToolMessage carries the id of the tool call it answers.
True. Its tool_call_id must match the id of the call in the AIMessage, which pairs each result with its request.
A model call inside a node
A node is a function that receives the current state and returns only the keys it changes. A node that talks to a model reads the conversation from the state, invokes the chat model with it, and returns the reply under the same key:
def chatbot(state: State) -> dict:
reply = model.invoke(state["messages"])
return {"messages": [reply]}The node returns a list with one message, the reply, and it does not change state["messages"] in place: nodes return their updates and let the graph apply them. That leaves an open question. The state already holds the earlier messages, and the node has returned a list with only the new one. Does the reply join the conversation, or does it take the place of it? The answer depends on the reducer of the messages key.
Reducers: how an update joins the state
When a node returns an update, the graph has to merge each returned key into the state. A reducer is the rule for one key. It is a function of two arguments: the value the state holds now and the value the node returned. What it returns becomes the new value of the key. Keys the node did not return are left as they are.
A key with no reducer uses the default rule: the returned value replaces the old one. That suits a key holding one value, such as a category or a counter, where the newest value is the right one. For a list it is usually wrong, because a node that returns one new item wipes out every item before it.
To combine instead of replace, you attach a reducer to the key in the state schema with Annotated. Any function that takes the old value and the update works; operator.add, which joins two lists, is a common one:
import operator
from typing import Annotated, TypedDict
class State(TypedDict):
topic: str # no reducer: replaced
notes: Annotated[list[str], operator.add] # reducer: appendedHere is the same update applied to the two kinds of key. The state holds {"topic": "billing", "notes": ["hi"]}, and a node returns a new value for each:
| Key | In the state | Node returns | New value |
|---|---|---|---|
| topic (no reducer) | "billing" | "shipping" | "shipping" |
| notes (operator.add) | ["hi"] | ["bye"] | ["hi", "bye"] |
The reducer decides, not the node. The node above returns a one-item list either way, and only the schema says whether that list is added or substituted. One consequence surprises people: with a merging reducer, returning an empty list changes nothing. The empty list is merged in, and the old items stay. To replace such a key on purpose, a node returns its new value wrapped in Overwrite from langgraph.types.
True or false?
With no reducer on a list key, a node that returns a one-item list leaves the state with that one item only.
True. The default rule replaces the old value with the returned one, so the earlier items are gone.
With operator.add on a list key, a node can empty the list by returning [].
False. The reducer joins the old list with the empty one, which leaves the old list unchanged. Replacing it needs Overwrite.
A node has to return every key of the state, or the missing keys are lost.
False. A node returns only the keys it changes. Every other key keeps its value.
Messages in state: the add_messages reducer
A conversation is a list that grows, so the messages key needs a reducer. operator.add would append, but LangGraph provides one made for messages: add_messages. It follows two rules:
- A returned message with a new id is appended to the end of the list.
- A returned message with the same id as one already in the list replaces that message where it stands.
So the conversation only grows, unless a node deliberately sends back a message it wants to change, such as a corrected answer. Before merging, add_messages gives an id to every message that has none, so every message in the state can be found again by its id.
| Messages in the state | Node returns | After add_messages |
|---|---|---|
| human (id h1), ai (id a1) | ai (id a2) | human h1, ai a1, ai a2 |
| human (id h1), ai (id a1) | ai (id a1), new text | human h1, ai a1 with the new text |
It also turns dictionaries into message objects as it merges, so a graph can be started with {"role": "user", "content": "..."} and every node still reads proper objects, such as state["messages"][-1].content. Put together, a one-node graph that holds a conversation looks like this. Its messages key is typed list[AnyMessage]: AnyMessage, from langchain_core.messages, is not a fifth class but a type that stands for any of the message classes above, so the list can hold system, human, AI and tool messages side by side.
from typing import Annotated, TypedDict
from langchain_core.messages import AnyMessage
from langgraph.graph import END, START, StateGraph
from langgraph.graph.message import add_messages
class State(TypedDict):
messages: Annotated[list[AnyMessage], add_messages]
def chatbot(state: State) -> dict:
reply = model.invoke(state["messages"])
return {"messages": [reply]}
builder = StateGraph(State)
builder.add_node("chatbot", chatbot)
builder.add_edge(START, "chatbot")
builder.add_edge("chatbot", END)
graph = builder.compile()
result = graph.invoke(
{"messages": [{"role": "user", "content": "Where is my order?"}]}
)
for message in result["messages"]:
print(message.type, message.content)The final state holds two messages: the human message the run started with and the AI reply the node returned, appended after it. A schema with just this key is common enough that LangGraph ships it as MessagesState in langgraph.graph; you can subclass it to add your own keys next to messages.
True or false?
add_messages and operator.add behave the same way on a list of messages.
False. operator.add only appends. add_messages appends too, but replaces a message whose id is already in the list, and gives ids to messages that have none.
When a node returns a message with the id of an earlier message, add_messages puts it in the place of the earlier one.
True. Same id means the same message, so the new version replaces the old one where it stands instead of being added at the end.
Fake chat models: the same run every time
A real model gives a slightly different reply on each call, needs a key and a network, and costs money per request. That makes it a poor fit for checking that a graph is wired correctly. A fake chat model is a stand-in with the chat model interface that calls no provider: you prepare its replies in advance, and each call returns the next one in order. A graph that uses it gives the same result on every run, offline and for free.
langchain_core ships several. GenericFakeChatModel takes an iterator of replies, strings or AIMessage objects, and returns one per call:
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage
model = GenericFakeChatModel(
messages=iter([
AIMessage("Your order shipped yesterday."),
"Is there anything else I can help with?",
])
)
model.invoke([{"role": "user", "content": "Where is my order?"}])
# AIMessage: "Your order shipped yesterday."
model.invoke([{"role": "user", "content": "Thanks!"}])
# AIMessage: "Is there anything else I can help with?"The fake model ignores what it is sent; the order of the script alone decides the reply. Since a prepared reply can be a full AIMessage, it can carry tool calls too, which lets a script stand in for every turn of a model, not just its text. A few details matter when you choose one:
GenericFakeChatModeldoes not start over: once its iterator is used up, it cannot give more replies, so the script must hold one reply per call.FakeListChatModeltakes strings only and cycles back to the first reply when it runs out, so it cannot script tool calls.- None of the fake classes implements
bind_tools, the method that attaches tool definitions to a model. Code that calls it needs a small subclass of its own whosebind_toolsreturns the model itself.
Because a node only calls invoke(), the graph cannot tell the fake from the real model. Passing one or the other into the graph is the only change between a predictable run and a live one.
True or false?
A fake chat model reads the messages it receives and picks a fitting prepared reply.
False. It returns its prepared replies strictly in order, whatever it is sent. That is what makes every run the same.
A scripted reply can be an AIMessage with tool calls, so a fake model can stand in for a model that asks for tools.
True. GenericFakeChatModel accepts AIMessage objects, and those may carry tool_calls. FakeListChatModel, which takes strings only, cannot.