Principle:Langchain ai Langgraph Graph Instantiation
| Metadata | Value |
|---|---|
| Type | Principle |
| Library | langgraph |
| Source | libs/langgraph/langgraph/graph/state.py
|
| Workflow | Building_a_Stateful_Graph |
Overview
Graph instantiation is the act of creating a StateGraph builder object from one or more typed schemas. This step establishes the contract for what data flows through the graph, how input is accepted, what output is produced, and what runtime context is available. It is the entry point of the Builder pattern that LangGraph uses to construct executable graphs.
Description
A StateGraph is a builder -- it collects nodes, edges, and configuration, but cannot execute anything by itself. Instantiation performs the following work:
- Registers the state schema -- The primary schema (a
TypedDict, PydanticBaseModel, orAnnotatedtype) is analyzed. Each field is mapped to an internal channel (LastValue,BinaryOperatorAggregate, etc.) based on its type annotations and any reducer metadata. - Resolves input and output schemas -- By default, both input and output schemas mirror the state schema. When explicitly provided, they allow the graph to accept a narrower set of fields as input and expose a different subset as output.
- Records the context schema -- An optional context schema defines immutable data (such as database connections, user IDs, or configuration) that is made available to every node at runtime but is not part of the mutable state.
- Initializes internal data structures -- The builder initializes empty collections for
nodes,edges,branches,channels,managedvalues, andschemas.
Schema Separation
The separation of state, input, and output schemas serves important purposes:
- Input schema -- Defines what callers must provide when invoking the graph. By narrowing the input schema, you prevent callers from accidentally overwriting internal state fields.
- Output schema -- Defines what the graph returns to callers. Internal bookkeeping fields can be excluded from the output.
- Context schema -- Defines runtime context that is immutable during execution. Context values are injected into nodes through the
Runtimeobject and do not participate in state updates.
Builder Pattern
LangGraph follows the Builder pattern:
- Instantiate --
StateGraph(MyState) - Configure --
.add_node(),.add_edge(),.add_conditional_edges() - Compile --
.compile()produces an executableCompiledStateGraph
The builder validates the graph topology and creates the Pregel execution engine only at compile time. This separation allows incremental, order-independent configuration before any validation occurs.
Usage
from typing import Annotated
from typing_extensions import TypedDict
from langgraph.graph import StateGraph
from langgraph.graph.message import add_messages
# Basic instantiation with a single state schema
class MyState(TypedDict):
messages: Annotated[list, add_messages]
count: int
graph = StateGraph(MyState)
# Instantiation with separate input/output schemas
class InputSchema(TypedDict):
query: str
class OutputSchema(TypedDict):
answer: str
class FullState(TypedDict):
query: str
answer: str
intermediate_steps: list
graph = StateGraph(
FullState,
input_schema=InputSchema,
output_schema=OutputSchema,
)
# Instantiation with a context schema
class Context(TypedDict):
user_id: str
db_conn: object
graph = StateGraph(MyState, context_schema=Context)
Theoretical Basis
- Builder pattern -- A creational design pattern that separates the construction of a complex object from its representation. In LangGraph, the
StateGraphbuilder collects configuration incrementally and produces an optimizedCompiledStateGraphonly whencompile()is called. - Schema-driven architecture -- The state schema acts as a single source of truth for the data contract. By embedding reducer semantics in type annotations, the schema simultaneously documents the data model and prescribes merge behavior, following the principle of co-locating related concerns.
- Separation of concerns -- Distinct input, output, and context schemas enforce clear boundaries between external interface, internal state, and runtime environment.