Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Implementation:Langchain ai Langgraph StateGraph Init

From Leeroopedia
Metadata Value
Type Implementation (API Doc)
Library langgraph
Source File libs/langgraph/langgraph/graph/state.py
Lines L112-250 (class definition and __init__)
Workflow Building_a_Stateful_Graph

Overview

StateGraph.__init__ creates a new graph builder instance from a state schema. It registers internal channels for each schema field, initializes data structures for nodes and edges, and optionally accepts separate input, output, and context schemas to control the graph's external interface.

Description

StateGraph is a generic class parameterized by StateT, ContextT, InputT, and OutputT. The constructor:

  1. Accepts a state_schema (required) which must be a type -- typically a TypedDict or Pydantic BaseModel.
  2. Accepts optional context_schema, input_schema, and output_schema. If input_schema or output_schema are not provided, they default to the state_schema.
  3. Calls _add_schema() for each schema to extract channels and managed values from type annotations.
  4. Initializes empty collections: nodes (dict), edges (set), branches (defaultdict), channels (dict), managed (dict), schemas (dict), and waiting_edges (set).
  5. Sets compiled = False to indicate the graph has not yet been compiled.

The class also supports a deprecated config_schema keyword that maps to context_schema for backward compatibility.

Usage

from typing import Annotated
from typing_extensions import TypedDict
from langgraph.graph import StateGraph
import operator

class State(TypedDict):
    x: Annotated[list, operator.add]

# Minimal instantiation
builder = StateGraph(State)

# With all optional schemas
class Input(TypedDict):
    x: list

class Output(TypedDict):
    x: list

class Context(TypedDict):
    r: float

builder = StateGraph(
    state_schema=State,
    context_schema=Context,
    input_schema=Input,
    output_schema=Output,
)

Code Reference

Source Location

Item Path Lines
StateGraph class libs/langgraph/langgraph/graph/state.py L112-1153
__init__ libs/langgraph/langgraph/graph/state.py L197-249

Signature

class StateGraph(Generic[StateT, ContextT, InputT, OutputT]):

    def __init__(
        self,
        state_schema: type[StateT],
        context_schema: type[ContextT] | None = None,
        *,
        input_schema: type[InputT] | None = None,
        output_schema: type[OutputT] | None = None,
    ) -> None:

Import

from langgraph.graph import StateGraph

I/O Contract

Parameter Type Default Description
state_schema type[StateT] required The primary state schema class. Must be a type with annotations (e.g., TypedDict, BaseModel).
context_schema None None Optional schema defining immutable runtime context available to all nodes.
input_schema None None Optional schema defining what callers provide as input. Defaults to state_schema.
output_schema None None Optional schema defining what the graph returns as output. Defaults to state_schema.

Returns: A new StateGraph instance (the builder), ready to receive node and edge registrations.

Raises:

  • ValueError -- If managed channels are found in input_schema or output_schema (managed channels are only permitted in the state schema).

Usage Examples

Simple State Schema

from typing_extensions import TypedDict
from langgraph.graph import StateGraph

class State(TypedDict):
    count: int
    name: str

builder = StateGraph(State)
# builder.nodes == {}
# builder.edges == set()
# builder.compiled == False

Using MessagesState

from langgraph.graph import StateGraph, MessagesState

builder = StateGraph(MessagesState)
# State has a single field: messages: Annotated[list[AnyMessage], add_messages]

Separate Input and Output

from typing_extensions import TypedDict
from langgraph.graph import StateGraph

class FullState(TypedDict):
    query: str
    documents: list
    answer: str

class InputOnly(TypedDict):
    query: str

class OutputOnly(TypedDict):
    answer: str

builder = StateGraph(
    FullState,
    input_schema=InputOnly,
    output_schema=OutputOnly,
)
# Callers provide {"query": "..."} and receive {"answer": "..."}

With Context Schema

from typing_extensions import TypedDict
from langgraph.graph import StateGraph

class State(TypedDict):
    x: int

class Context(TypedDict):
    multiplier: float

builder = StateGraph(State, context_schema=Context)
# Nodes can access runtime.context["multiplier"] during execution

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment