Skip to content

State Types API

Complete reference for all TypedDict state schemas used across different agent patterns. These types define the structure of state that flows through LangGraph graphs.

Multi-Agent States

MultiAgentState

State schema for supervisor-based multi-agent collaboration.

python
from typing_extensions import TypedDict
from typing import Annotated
import operator
from langgraph.graph.message import add_messages

class MultiAgentState(TypedDict):
    messages: Annotated[list, add_messages]
    task: str
    next_agent: str
    agent_outputs: Annotated[list[dict], operator.add]
    iteration: int
    max_iterations: int
    final_result: str

Fields

FieldTypeReducerDescription
messageslistadd_messagesConversation history (accumulates)
taskstrReplaceThe current task description
next_agentstrReplaceWhich agent should run next (set by supervisor)
agent_outputslist[dict]operator.addAccumulated outputs from all agents
iterationintReplaceCurrent iteration count
max_iterationsintReplaceMaximum allowed iterations
final_resultstrReplaceThe synthesized final result

Usage

python
from langgraph_ollama_local.agents import MultiAgentState
from langchain_core.messages import HumanMessage

initial_state: MultiAgentState = {
    "messages": [HumanMessage(content="Task: Build calculator")],
    "task": "Build a calculator app",
    "next_agent": "",
    "agent_outputs": [],
    "iteration": 0,
    "max_iterations": 10,
    "final_result": "",
}

TeamState

State schema for a single team within a hierarchical structure.

python
class TeamState(TypedDict):
    messages: Annotated[list, add_messages]
    task: str
    team_name: str
    next_member: str
    member_outputs: Annotated[list[dict], operator.add]
    iteration: int
    max_iterations: int
    team_result: str

Fields

FieldTypeReducerDescription
messageslistadd_messagesTeam conversation history
taskstrReplaceTask assigned to the team
team_namestrReplaceName of this team
next_memberstrReplaceWhich team member should work next
member_outputslist[dict]operator.addAccumulated outputs from members
iterationintReplaceCurrent iteration within the team
max_iterationsintReplaceMaximum iterations for this team
team_resultstrReplaceFinal synthesized result from the team

Usage

python
from langgraph_ollama_local.agents.hierarchical import TeamState

team_state: TeamState = {
    "messages": [],
    "task": "Research quantum computing",
    "team_name": "research",
    "next_member": "",
    "member_outputs": [],
    "iteration": 0,
    "max_iterations": 5,
    "team_result": "",
}

HierarchicalState

State schema for hierarchical agent teams with multiple sub-teams.

python
class HierarchicalState(TypedDict):
    messages: Annotated[list, add_messages]
    task: str
    active_team: str
    team_results: dict[str, str]
    iteration: int
    max_iterations: int
    final_result: str

Fields

FieldTypeReducerDescription
messageslistadd_messagesTop-level conversation history
taskstrReplaceOverall task description
active_teamstrReplaceWhich team is currently working
team_resultsdict[str, str]ReplaceResults from each team (team_name -> result)
iterationintReplaceTop-level iteration count
max_iterationsintReplaceMaximum top-level iterations
final_resultstrReplaceFinal synthesized result from all teams

Usage

python
from langgraph_ollama_local.agents.hierarchical import HierarchicalState

hierarchical_state: HierarchicalState = {
    "messages": [],
    "task": "Build microservices architecture",
    "active_team": "",
    "team_results": {},
    "iteration": 0,
    "max_iterations": 10,
    "final_result": "",
}

Pattern States

SwarmState

State schema for decentralized agent swarm/network.

python
class SwarmState(TypedDict):
    messages: Annotated[list, add_messages]
    task: str
    agents_state: dict[str, dict[str, Any]]
    shared_context: Annotated[list[dict], operator.add]
    current_agent: str
    iteration: int
    max_iterations: int
    final_result: str

Fields

FieldTypeReducerDescription
messageslistadd_messagesConversation history
taskstrReplaceThe overall task for the swarm
agents_statedict[str, dict]ReplacePer-agent state (agent_name -> agent_data)
shared_contextlist[dict]operator.addAccumulated shared findings from all agents
current_agentstrReplaceName of the currently active agent
iterationintReplaceCurrent iteration count
max_iterationsintReplaceMaximum iterations before completion
final_resultstrReplaceThe synthesized final result

Usage

python
from langgraph_ollama_local.patterns.swarm import SwarmState

swarm_state: SwarmState = {
    "messages": [],
    "task": "Research AI trends",
    "agents_state": {},
    "shared_context": [],
    "current_agent": "",
    "iteration": 0,
    "max_iterations": 10,
    "final_result": "",
}

HandoffState

State schema for agent handoff pattern with explicit control transfer.

python
class HandoffState(TypedDict):
    messages: Annotated[list, add_messages]
    task: str
    current_agent: str
    handoff_target: str
    context: Annotated[list[dict], operator.add]
    handoff_history: Annotated[list[str], operator.add]
    iteration: int
    max_iterations: int
    final_result: str

Fields

FieldTypeReducerDescription
messageslistadd_messagesConversation history
taskstrReplaceThe original task or query
current_agentstrReplaceCurrently active agent name
handoff_targetstrReplaceAgent to hand off to (empty if no handoff)
contextlist[dict]operator.addShared context accumulating across handoffs
handoff_historylist[str]operator.addList of handoff events for tracking
iterationintReplaceNumber of handoffs that have occurred
max_iterationsintReplaceMaximum allowed handoffs
final_resultstrReplaceThe final response to the user

Usage

python
from langgraph_ollama_local.patterns.handoffs import HandoffState

handoff_state: HandoffState = {
    "messages": [],
    "task": "I need help with my invoice",
    "current_agent": "sales",
    "handoff_target": "",
    "context": [],
    "handoff_history": [],
    "iteration": 0,
    "max_iterations": 10,
    "final_result": "",
}

MapReduceState

State schema for map-reduce pattern with parallel execution.

python
class MapReduceState(TypedDict):
    task: str
    subtasks: list[str]
    worker_results: Annotated[list[dict], operator.add]
    final_result: str

Fields

FieldTypeReducerDescription
taskstrReplaceThe main task to be processed
subtaskslist[str]ReplaceList of subtasks created by mapper (one per worker)
worker_resultslist[dict]operator.addAccumulated results from all workers
final_resultstrReplaceThe aggregated final result from reducer

Usage

python
from langgraph_ollama_local.patterns.map_reduce import MapReduceState

map_reduce_state: MapReduceState = {
    "task": "Analyze research paper",
    "subtasks": [],
    "worker_results": [],
    "final_result": "",
}

EvaluationState

State schema for agent evaluation sessions with simulated users.

python
class EvaluationState(TypedDict):
    messages: Annotated[list, add_messages]
    conversation: str
    evaluator_scores: Annotated[list[dict], operator.add]
    turn_count: int
    max_turns: int
    session_complete: bool
    final_metrics: dict[str, float]

Fields

FieldTypeReducerDescription
messageslistadd_messagesFull conversation between agent and simulated user
conversationstrReplaceFormatted conversation for evaluator review
evaluator_scoreslist[dict]operator.addList of score dicts from evaluator agent
turn_countintReplaceCurrent conversation turn number
max_turnsintReplaceMaximum number of conversation turns
session_completeboolReplaceWhether the evaluation session is done
final_metricsdict[str, float]ReplaceAggregated metrics summary

Usage

python
from langgraph_ollama_local.patterns.evaluation import EvaluationState

evaluation_state: EvaluationState = {
    "messages": [],
    "conversation": "",
    "evaluator_scores": [],
    "turn_count": 0,
    "max_turns": 10,
    "session_complete": False,
    "final_metrics": {},
}

Understanding Reducers

LangGraph uses reducers to control how state fields are updated when multiple nodes write to the same field.

Common Reducers

Replace (Default)

New value replaces the old value.

python
class MyState(TypedDict):
    task: str  # Uses replace reducer by default

add_messages

Intelligent message accumulation that handles duplicates and updates.

python
from langgraph.graph.message import add_messages
from typing import Annotated

class MyState(TypedDict):
    messages: Annotated[list, add_messages]

Behavior:

  • Appends new messages to the list
  • Handles message updates by ID
  • Removes duplicates intelligently

operator.add

Concatenates lists or adds numbers.

python
import operator
from typing import Annotated

class MyState(TypedDict):
    outputs: Annotated[list[dict], operator.add]
    count: Annotated[int, operator.add]

Behavior:

  • For lists: Concatenates [1, 2] + [3, 4] = [1, 2, 3, 4]
  • For numbers: Adds 5 + 3 = 8

Creating Custom States

Basic Custom State

python
from typing_extensions import TypedDict

class MyCustomState(TypedDict):
    input: str
    output: str
    metadata: dict

Custom State with Reducers

python
from typing_extensions import TypedDict
from typing import Annotated
import operator
from langgraph.graph.message import add_messages

class MyCustomState(TypedDict):
    # Messages with intelligent accumulation
    messages: Annotated[list, add_messages]

    # Simple replacement
    current_step: str

    # List accumulation
    results: Annotated[list[dict], operator.add]

    # Counter
    iteration: int

Using Custom States

python
from langgraph.graph import StateGraph

# Define custom state
class MyState(TypedDict):
    input: str
    output: str

# Create graph with custom state
workflow = StateGraph(MyState)

def my_node(state: MyState) -> dict:
    return {"output": f"Processed: {state['input']}"}

workflow.add_node("process", my_node)
workflow.set_entry_point("process")
workflow.set_finish_point("process")

graph = workflow.compile()

# Run with custom state
result = graph.invoke({"input": "Hello", "output": ""})
print(result["output"])  # "Processed: Hello"

State Best Practices

1. Use Appropriate Reducers

python
# Good: Use add_messages for message history
messages: Annotated[list, add_messages]

# Good: Use operator.add for accumulating results
agent_outputs: Annotated[list[dict], operator.add]

# Good: Use replace (default) for counters and flags
iteration: int
is_complete: bool

2. Initialize All Fields

python
# Good: Provide initial values for all fields
initial_state: MultiAgentState = {
    "messages": [],
    "task": "My task",
    "next_agent": "",
    "agent_outputs": [],
    "iteration": 0,
    "max_iterations": 10,
    "final_result": "",
}

3. Document State Purpose

python
class MyState(TypedDict):
    """
    State for my custom pattern.

    Attributes:
        messages: Conversation history between agents
        task: The current task being processed
        results: Accumulated results from all workers
    """
    messages: Annotated[list, add_messages]
    task: str
    results: Annotated[list, operator.add]

4. Keep State Flat When Possible

python
# Good: Flat structure
class GoodState(TypedDict):
    user_id: str
    user_name: str
    user_email: str

# Avoid: Deep nesting makes updates complex
class AvoidState(TypedDict):
    user: dict[str, dict[str, str]]  # Harder to update

Common State Patterns

Pattern 1: Iterative Processing

python
class IterativeState(TypedDict):
    task: str
    current_iteration: int
    max_iterations: int
    results: Annotated[list, operator.add]
    is_complete: bool

Pattern 2: Agent Coordination

python
class CoordinationState(TypedDict):
    messages: Annotated[list, add_messages]
    active_agent: str
    agent_outputs: Annotated[list[dict], operator.add]
    routing_decision: str

Pattern 3: Evaluation & Metrics

python
class MetricsState(TypedDict):
    input_data: list[dict]
    scores: Annotated[list[float], operator.add]
    metrics: dict[str, float]
    best_score: float