Low-level orchestration framework for building stateful, multi-actor applications with LLMs
LangGraph is a low-level orchestration framework for building stateful, multi-actor applications with LLMs. It provides controllable agent orchestration with customizable graph-based workflows, state management through channels, long-term memory via checkpointing, human-in-the-loop capabilities, and streaming support for real-time visibility into agent execution.
npm install @langchain/langgraph @langchain/coreimport { StateGraph, Annotation, START, END } from "@langchain/langgraph";
// Define state using Annotation
const StateAnnotation = Annotation.Root({
messages: Annotation<string[]>({
reducer: (current, update) => [...current, ...update],
default: () => []
}),
count: Annotation<number>({
reducer: (_, update) => update,
default: () => 0
})
});
// Create a graph
const graph = new StateGraph(StateAnnotation)
.addNode("process", (state) => {
return {
messages: [`Processed: ${state.messages.length} messages`],
count: state.count + 1
};
})
.addEdge(START, "process")
.addEdge("process", END);
// Compile and execute
const app = graph.compile();
const result = await app.invoke({
messages: ["Hello"],
count: 0
});
console.log(result);
// { messages: ["Hello", "Processed: 1 messages"], count: 1 }import {
// Graph classes
StateGraph,
Graph,
CompiledStateGraph,
// Annotation system
Annotation,
AnnotationRoot,
MessagesAnnotation,
// State reducers
messagesStateReducer,
addMessages,
// Constants
START,
END,
INTERRUPT,
// Control flow
Send,
Command,
interrupt,
// Persistence
MemorySaver,
BaseCheckpointSaver,
BaseStore,
InMemoryStore
} from "@langchain/langgraph";
// Prebuilt agents
import {
createReactAgent,
ToolNode,
toolsCondition
} from "@langchain/langgraph/prebuilt";
// Remote graphs
import { RemoteGraph } from "@langchain/langgraph/remote";
// Functional API
import {
entrypoint,
task,
getPreviousState,
writer,
getStore
} from "@langchain/langgraph";LangGraph is built around several key components:
Learn the fundamentals and build your first graphs:
Complete API documentation for all classes and functions:
In-depth guides for advanced topics:
Complete working examples:
Build stateful workflows using StateGraph with typed state management.
class StateGraph<StateDefinition> {
constructor(stateDefinition: StateDefinition | StateGraphArgs<StateDefinition>);
addNode(name: string, action: NodeType<StateDefinition>): this;
addEdge(from: string, to: string): this;
addConditionalEdges(
source: string,
path: (state: StateType<StateDefinition>) => string | string[] | Send | Send[],
pathMap?: Record<string, string>
): this;
compile(options?: PregelOptions): CompiledStateGraph;
}Learn more: Graph Construction API | Graph Construction Guide
Channel-based state system with support for different update semantics.
const State = Annotation.Root({
// Last value wins
count: Annotation<number>,
// Array concatenation
messages: Annotation<string[]>({
reducer: (a, b) => a.concat(b),
default: () => []
}),
// Object merging
metadata: Annotation<Record<string, any>>({
reducer: (a, b) => ({ ...a, ...b }),
default: () => ({})
})
});Learn more: Channels API | State & Channels Guide
Run graphs with multiple streaming modes for different levels of visibility.
// Invoke
const result = await graph.invoke(input, options);
// Stream values
for await (const state of await graph.stream(input, { streamMode: "values" })) {
console.log(state);
}
// Stream updates
for await (const update of await graph.stream(input, { streamMode: "updates" })) {
console.log(update);
}Learn more: Execution API Reference
Dynamic routing with Send and Command for flexible execution paths.
class Send<Node = string, Args = any> {
constructor(node: Node, args: Args);
}
class Command<Resume = any, Update = any, Nodes = string> {
resume?: Resume;
update?: Update;
goto?: Nodes | Nodes[] | Send | Send[];
}Learn more: Control Flow API
State snapshots and time-travel debugging via checkpoint savers.
import { MemorySaver } from "@langchain/langgraph-checkpoint";
const graph = new StateGraph(State)
.addNode("process", processNode)
.compile({ checkpointer: new MemorySaver() });
await graph.invoke(input, {
configurable: { thread_id: "conversation-1" }
});Learn more: Persistence API | Checkpointing Guide
Ready-to-use ReAct agents with tool calling.
import { createReactAgent } from "@langchain/langgraph/prebuilt";
const agent = createReactAgent({
llm: model,
tools: [searchTool, calculatorTool]
});
const result = await agent.invoke({
messages: [{ role: "user", content: "What is 25 * 4?" }]
});Learn more: Prebuilt Agents API | Agent Patterns Examples
Simplified workflow definition with task() and entrypoint().
import { task, entrypoint } from "@langchain/langgraph";
const processTask = task("process", async (item: string) => {
return `Processed: ${item}`;
});
const workflow = entrypoint("myWorkflow", async (items: string[]) => {
const results = await Promise.all(items.map(i => processTask(i)));
return results;
});
const result = await workflow.invoke(["a", "b", "c"]);Learn more: Functional API Reference
Execute graphs deployed on LangGraph Cloud.
import { RemoteGraph } from "@langchain/langgraph/remote";
const remoteGraph = new RemoteGraph({
graphId: "my-deployed-graph",
url: "https://api.langgraph.cloud",
apiKey: process.env.LANGGRAPH_API_KEY
});
const result = await remoteGraph.invoke(input);Learn more: Remote Graphs API
Interrupt execution for human review and input.
import { interrupt } from "@langchain/langgraph";
const reviewNode = async (state: any) => {
const reviewData = interrupt({
question: "Approve this action?",
context: state
});
return reviewData.approved ? { status: "approved" } : { status: "rejected" };
};Learn more: Control Flow API | Human-in-the-Loop Guide
import { StateGraph, Annotation, MemorySaver } from "@langchain/langgraph";
const ChatState = Annotation.Root({
messages: Annotation<BaseMessage[]>({
reducer: (a, b) => a.concat(b),
default: () => []
})
});
const chatbot = new StateGraph(ChatState)
.addNode("respond", async (state) => {
const response = await llm.invoke(state.messages);
return { messages: [response] };
})
.addEdge("__start__", "respond")
.addEdge("respond", "__end__")
.compile({ checkpointer: new MemorySaver() });
// Conversation with memory
await chatbot.invoke(
{ messages: [new HumanMessage("Hi!")] },
{ configurable: { thread_id: "user-123" } }
);See more: Stateful Applications Examples
import { createReactAgent } from "@langchain/langgraph/prebuilt";
import { ChatOpenAI } from "@langchain/openai";
const agent = createReactAgent({
llm: new ChatOpenAI({ model: "gpt-4" }),
tools: [searchTool, calculatorTool]
});
const result = await agent.invoke({
messages: [{ role: "user", content: "Search for Python tutorials and calculate 15 * 23" }]
});See more: Agent Patterns Examples
import { Send } from "@langchain/langgraph";
const fanOut = (state: State) => {
return state.items.map(item => new Send("process", { item }));
};
const graph = new StateGraph(State)
.addNode("process", processNode)
.addNode("aggregate", aggregateNode)
.addConditionalEdges("__start__", fanOut)
.addEdge("process", "aggregate")
.compile();See more: Advanced Patterns Examples
Install with Tessl CLI
npx tessl i tessl/npm-langchain--langgraph