langgraph
Description
Trusted by companies shaping the future of agents β including Klarna, Replit, Elastic, and more β LangGraph is a low-level orchestration framework for building, managing, and deploying long-running, stateful agents.
Get started
Install LangGraph:
pip install -U langgraph
Create a simple workflow:
from langgraph.graph import START, StateGraph
from typing_extensions import TypedDict
class State(TypedDict):
text: str
def node_a(state: State) -> dict:
return {"text": state["text"] + "a"}
def node_b(state: State) -> dict:
return {"text": state["text"] + "b"}
graph = StateGraph(State)
graph.add_node("node_a", node_a)
graph.add_node("node_b", node_b)
graph.add_edge(START, "node_a")
graph.add_edge("node_a", "node_b")
print(graph.compile().invoke({"text": ""}))
# {'text': 'ab'}Get started with the LangGraph Quickstart.
To quickly build agents with LangChain's create_agent (built on LangGraph), see the LangChain Agents documentation.
Core benefits
LangGraph provides low-level supporting infrastructure for any long-running, stateful workflow or agent. LangGraph does not abstract prompts or architecture, and provides the following central benefits:
- Durable execution: Build agents that persist through failures and can run for extended periods, automatically resuming from exactly where they left off.
- Human-in-the-loop: Seamlessly incorporate human oversight by inspecting and modifying agent state at any point during execution.
- Comprehensive memory: Create truly stateful agents with both short-term working memory for ongoing reasoning and long-term persistent memory across sessions.
- Debugging with LangSmith: Gain deep visibility into complex agent behavior with visualization tools that trace execution paths, capture state transitions, and provide detailed runtime metrics.
- Production-ready deployment: Deploy sophisticated agent systems confidently with scalable infrastructure designed to handle the unique challenges of stateful, long-running workflows.
LangGraphβs ecosystem
While LangGraph can be used standalone, it also integrates seamlessly with any LangChain product, giving developers a full suite of tools for building agents. To improve your LLM application development, pair LangGraph with:
- LangSmith β Helpful for agent evals and observability. Debug poor-performing LLM app runs, evaluate agent trajectories, gain visibility in production, and improve performance over time.
- LangSmith Deployment β Deploy and scale agents effortlessly with a purpose-built deployment platform for long running, stateful workflows. Discover, reuse, configure, and share agents across teams β and iterate quickly with visual prototyping in LangGraph Studio.
- LangChain β Provides integrations and composable components to streamline LLM application development.
[!NOTE] Looking for the JS version of LangGraph? See the JS repo and the JS docs.
Additional resources
- Guides: Quick, actionable code snippets for topics such as streaming, adding memory & persistence, and design patterns (e.g. branching, subgraphs, etc.).
- Reference: Detailed reference on core classes, methods, how to use the graph and checkpointing APIs, and higher-level prebuilt components.
- Examples: Guided examples on getting started with LangGraph.
- LangChain Forum: Connect with the community and share all of your technical questions, ideas, and feedback.
- LangChain Academy: Learn the basics of LangGraph in our free, structured course.
- Case studies: Hear how industry leaders use LangGraph to ship AI applications at scale.
Acknowledgements
LangGraph is inspired by Pregel and Apache Beam. The public interface draws inspiration from NetworkX. LangGraph is built by LangChain Inc, the creators of LangChain, but can be used without LangChain.
Classes
ErrorCode
GraphRecursionError
Raised when the graph has exhausted the maximum number of steps.
InvalidUpdateError
Raised when attempting to update a channel with an invalid set of updates.
GraphBubbleUp
GraphInterrupt
Raised when a subgraph is interrupted, suppressed by the root graph.
ParentCommand
EmptyInputError
Raised when graph receives an empty input.
TaskNotFound
Raised when the executor is unable to find a task (for distributed mode).
Runtime
Convenience class that bundles run-scoped context and other runtime utilities.
ToolOutputMixin
RetryPolicy
Configuration for retrying nodes.
CachePolicy
Configuration for caching nodes.
Interrupt
Information about an interrupt that occurred in a node.
StateUpdate
PregelTask
A Pregel task.
CacheKey
Cache key for a task.
PregelExecutableTask
StateSnapshot
Snapshot of the state of the graph at the beginning of a step.
Send
A message or packet to send to a specific node in the graph.
Command
One or more commands to update the graph's state and send messages to nodes.
Overwrite
Bypass a reducer and write the wrapped value directly to a BinaryOperatorAggregate channel.
LangGraphDeprecationWarning
A LangGraph specific deprecation warning.
LangGraphDeprecatedSinceV05
A specific LangGraphDeprecationWarning subclass defining functionality deprecated since LangGraph v0.5.0
LangGraphDeprecatedSinceV10
A specific LangGraphDeprecationWarning subclass defining functionality deprecated since LangGraph v1.0.0
Topic
A configurable PubSub Topic.
BaseChannel
Base class for all channels.
LastValue
Stores the last value received, can receive at most one value per step.
LastValueAfterFinish
Stores the last value received, but only made available after finish().
EphemeralValue
Stores the value received in the step immediately preceding, clears after.
AnyValue
Stores the last value received, assumes that if multiple values are
NamedBarrierValue
A channel that waits until all named values are received before making the value available.
NamedBarrierValueAfterFinish
A channel that waits until all named values are received before making the value ready to be made available. It is only made available after finish() is called.
BinaryOperatorAggregate
Stores the result of applying a binary operator to the current value and each new value.
UntrackedValue
Stores the last value received, never checkpointed.
StateGraph
A graph whose nodes communicate by reading and writing to a shared state.
CompiledStateGraph
UIMessage
A message type for UI updates in LangGraph.
RemoveUIMessage
A message type for removing UI components in LangGraph.
StateNodeSpec
MessagesState
BranchSpec
entrypoint
Define a LangGraph workflow using the entrypoint decorator.
final
A primitive that can be returned from an entrypoint.
FunctionNonLocals
Get the nonlocal variables accessed of a function.
NonLocals
Get nonlocal variables accessed.
SyncAsyncFuture
NodeBuilder
Pregel
Pregel manages the runtime behavior for LangGraph applications.
ChannelWriteEntry
ChannelWriteTupleEntry
ChannelWrite
Implements the logic for sending writes to CONFIG_KEY_SEND.
StreamMessagesHandler
A callback handler that implements stream_mode=messages.
TaskPayload
TaskResultPayload
CheckpointTask
CheckpointPayload
PregelProtocol
StreamProtocol
PregelLoop
SyncPregelLoop
AsyncPregelLoop
ChannelRead
Implements the logic for reading state from CONFIG_KEY_READ.
PregelNode
A node in a Pregel graph. This won't be invoked as a runnable by the graph
Submit
BackgroundExecutor
A context manager that runs sync tasks in the background.
AsyncBackgroundExecutor
A context manager that runs async tasks in the background.
RemoteException
Exception raised when an error occurs in the remote graph.
RemoteGraph
The RemoteGraph class is a client implementation for calling remote
WritesProtocol
Protocol for objects containing writes to be applied to checkpoint.
PregelTaskWrites
Simplest implementation of WritesProtocol, for usage with writes that
Call
LazyAtomicCounter
Edge
TriggerEdge
FuturesDict
PregelRunner
Responsible for executing a set of Pregel tasks concurrently, committing
IsLastStepManager
RemainingStepsManager
ManagedValue
PregelScratchpad
AsyncQueue
Async unbounded FIFO queue with a wait() method.
Semaphore
Semaphore subclass with a wait() method.
SyncQueue
Unbounded FIFO queue with a wait() method.
TypedDictLikeV1
Protocol to represent types that behave like TypedDicts
TypedDictLikeV2
Protocol to represent types that behave like TypedDicts
DataclassLike
Protocol to represent types that behave like dataclasses.
DeprecatedKwargs
TypedDict to use for extra keyword arguments, enabling type checking warnings for deprecated arguments.
StrEnum
A string enum.
RunnableCallable
A much simpler version of RunnableLambda that requires sync and async functions.
RunnableSeq
Sequence of Runnable, where the output of each is the input of the next.
NodeInterrupt
deprecatedRaised by a node to interrupt execution.
MessageGraph
deprecatedA StateGraph where every node receives a list of messages as input and returns one or more messages as output.
Functions
create_error_message
get_runtime
Get the runtime for the current graph run.
get_config
get_store
Access LangGraph store from inside a graph node or entrypoint task at runtime.
get_stream_writer
Access LangGraph StreamWriter from inside a graph node or entrypoint task at runtime.
ensure_valid_checkpointer
interrupt
Interrupt the graph with a resumable exception from within a node.
push_ui_message
Push a new UI message to update the UI state.
delete_ui_message
Delete a UI message by ID from the UI state.
ui_message_reducer
Merge two lists of UI messages, supporting removing UI messages.
add_messages
Merges two lists of messages, updating existing messages by ID.
push_message
Write a message manually to the messages / messages-tuple stream mode.
task
Define a LangGraph task using the task decorator.
get_new_channel_versions
Get subset of current_versions that are newer than previous_versions.
find_subgraph_pregel
get_function_nonlocals
Get the nonlocal variables accessed by a function.
is_xxh3_128_hexdigest
Check if the given string matches the format of xxh3_128_hexdigest.
identifier
Return the module and name of an object.
get_runnable_for_entrypoint
get_runnable_for_task
call
empty_checkpoint
create_checkpoint
Create a checkpoint for the given channels.
channels_from_checkpoint
Get channels from a checkpoint.
copy_checkpoint
map_debug_tasks
Produce "task" events for stream_mode=debug.
is_multiple_channel_write
Return True if the payload already wraps multiple writes from the same channel.
map_task_result_writes
Folds task writes into a result dict and aggregates multiple writes to the same channel.
map_debug_task_results
Produce "task_result" events for stream_mode=debug.
rm_pregel_keys
Remove pregel-specific keys from the config.
map_debug_checkpoint
Produce "checkpoint" events for stream_mode=debug.
tasks_w_writes
Apply writes / subgraph states to tasks to be returned in a StateSnapshot.
get_colored_text
Get colored text.
get_bolded_text
Get bolded text.
validate_graph
validate_keys
DuplexStream
gated
A coroutine that waits for a semaphore before running another coroutine.
next_tick
A function that yields control to other threads before running another function.
read_channel
read_channels
map_command
Map input chunk to a sequence of pending writes in the form (channel, value).
map_input
Map input chunk to a sequence of pending writes in the form (channel, value).
map_output_values
Map pending writes (a sequence of tuples (channel, value)) to output chunk.
map_output_updates
Map pending writes (a sequence of tuples (channel, value)) to output chunk.
run_with_retry
Run a task with retries.
arun_with_retry
Run a task asynchronously with retries.
should_interrupt
Check if the graph should be interrupted based on current state.
local_read
Function injected under CONFIG_KEY_READ in task config, to read current state.
increment
Default channel versioning function, increments the current int version.
apply_writes
Apply writes from a set of tasks (usually the tasks from a Pregel step)
prepare_next_tasks
Prepare the set of tasks that will make up the next Pregel step.
prepare_single_task
Prepares a single task for the next Pregel step, given a task path, which
prepare_push_task_functional
Prepare a push task with an attached caller. Used for the functional API.
prepare_push_task_send
checkpoint_null_version
Get the null version for the checkpoint, if available.
task_path_str
Generate a string representation of the task path.
sanitize_untracked_values_in_send
Pop any values belonging to UntrackedValue channels in Send.arg for safe checkpointing.
draw_graph
Get the graph for this Pregel instance.
add_edge
Add an edge to the graph.
is_managed_value
default_cache_key
Default cache key function that uses the arguments and keyword arguments to generate a hashable key.
get_field_default
Determine the default value for a field in a state schema.
get_enhanced_type_hints
Attempt to extract default values and descriptions from provided type, used for config schema.
get_update_as_tuples
Get Pydantic state update as a list of (key, value) tuples.
get_cached_annotated_keys
Return cached annotated keys for a Python class.
recast_checkpoint_ns
Remove task IDs from checkpoint namespace.
patch_configurable
patch_checkpoint_map
merge_configs
Merge multiple configs into one.
patch_config
Patch a config with new values.
get_callback_manager_for_config
Get a callback manager for a config.
get_async_callback_manager_for_config
Get an async callback manager for a config.
ensure_config
Return a config with all keys, merging any provided configs.
chain_future
run_coroutine_threadsafe
Submit a coroutine object to a given event loop.
apply_checkpointer_allowlist
curated_core_allowlist
build_serde_allowlist
collect_allowlist_from_schemas
set_config_context
Set the child Runnable config + tracing context.
is_async_callable
Check if a function is async.
is_async_generator
Check if a function is an async generator.
coerce_to_runnable
Coerce a runnable-like object into a Runnable.
get_fields
Get the field names of a Pydantic model.
create_model
Create a pydantic model with the given field definitions.
is_supported_by_pydantic
Check if a given "complex" type is supported by pydantic.
default_retry_on
Modules
langgraph
version
Exports package version.
errors
runtime
config
typing
types
warnings
LangGraph specific warnings.
constants
channels
topic
base
last_value
ephemeral_value
any_value
named_barrier_value
binop
untracked_value
graph
state
ui
message
utils
Legacy utilities module, to be removed in v1.
config
Backwards compat imports for config utilities, to be removed in v1.
runnable
Backwards compat imports for runnable utilities, to be removed in v1.
func
pregel
main
debug
protocol
types
Re-export types moved to langgraph.types