Declare graph state
A graph needs a typed state schema shared by its nodes.
AI Agents · Const
Annotation declares channels for StateGraph state. Use it directly for replacement semantics or configure a reducer to combine node updates.
Annotation creates channels for fields in an Annotation.Root state schema. A field can either keep the latest node update or use a reducer to combine the existing value with each update; an optional default supplies its initial value.
Annotation<T>(config?)
Annotation.Root(spec)| Name | Type | Description |
|---|---|---|
value/configuration | T or Annotation<T> configuration | The channel's value type, optionally followed by reducer and default configuration. |
spec | AnnotationRootSpec | An object mapping state field names to annotations, passed to Annotation.Root. |
An annotation channel for a state field, or an annotation root when used through Annotation.Root.
import { Annotation, StateGraph } from "@langchain/langgraph";
const State = Annotation.Root({
input: Annotation<string>,
output: Annotation<string>({
reducer: (current, update) => `${current}\n${update}`,
default: () => "",
}),
});
const graph = new StateGraph(State)
.addNode("respond", (state) => ({ output: `Answer: ${state.input}` }))
.addEdge("__start__", "respond")
.addEdge("respond", "__end__")
.compile();
const result = await graph.invoke({ input: "Hello" });
console.log(result.output);Defines graph state with a direct channel and a reducer-backed channel, then runs a node that writes an output value.
A graph needs a typed state schema shared by its nodes.
Several nodes contribute to one field, such as accumulated messages or text.
A node should return a precisely typed partial state update.
Annotation defines channels used by a StateGraph state schema. With a direct annotation, a node's returned value becomes the channel's current value.
Follow-up: How would you preserve multiple node updates? Define the field with a reducer, then combine the existing value and each incoming update in that reducer.
Use Annotation.Root to wrap an object whose fields are annotated channels. The resulting root annotation can be passed to StateGraph, and its State type can be used to type node input.
Follow-up: How can a node update only part of the state? Return an object containing only the fields that node changes; the graph applies each field's channel behavior.
A reducer-backed annotation applies the reducer to a node's returned update. A default function can provide the channel's initial value, which is useful when combining updates into an initially empty collection or string.
Follow-up: What should a reducer's inputs represent? Treat them as the current channel value and the node-provided update, and return the next channel value.
Annotation.RootStateGraphMessagesAnnotationmessagesStateReducer