Compiling, invoking and runtime context
Overview
In the previous lesson, Edges, conditional edges and dynamic routing, you learned how to connect nodes and determine which operation should execute next. You can now describe sequential workflows, conditional branches, and agent loops.
However, describing a graph and executing a graph are two different operations.
A StateGraph is initially a blueprint. It contains information about your state schema, node functions, edges, and routing rules. Before LangGraph can execute that blueprint, it must convert it into a runnable workflow.
This conversion is called compilation.
Once compiled, a graph can process individual requests, handle multiple inputs, stream intermediate results, and receive request-specific dependencies.
Consider a customer support application. Every customer uses the same underlying workflow, but individual requests may have different:
- Questions and conversation histories.
- Account identifiers and access permissions.
- Preferred languages and model selections.
- Execution limits and tracing information.
- Database connections or service clients.
You should not construct an entirely new graph for every combination of these values. Instead, compile the workflow once and supply the appropriate information when executing it.
This diagram illustrates the distinction between graph construction and graph execution.
By the end of this lesson, you should be comfortable deciding not only how a graph runs, but also where different categories of application data belong.
Environment setup
Use Python 3.11 or newer and the current LangGraph 1.x and LangChain 1.x packages.
pip install -U "langgraph>=1.2,<2" "langchain>=1,<2"The examples deliberately use deterministic Python functions and simulated services instead of paid language models. This makes their behavior predictable and lets you concentrate on graph execution.
The APIs have been checked against the current official documentation. The examples have not been executed in the authoring environment because LangGraph is not installed there. Outputs shown are the expected results.
Compilation
Understanding the builder
When you instantiate StateGraph, you create a builder:
builder = StateGraph(State)The builder records the workflow’s structural definition. Adding a node registers a callable; adding an edge registers an execution relationship.
Neither operation executes your business logic.
Calling compile() converts the definition into a CompiledStateGraph, which implements the LangChain Runnable interface.
This distinction resembles defining a database query versus executing it, although LangGraph compilation does not translate Python functions into machine code.
Your first compiled workflow
The following standalone example normalizes a customer question and constructs a response.
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
class State(TypedDict, total=False):
query: str
normalized_query: str
response: str
def normalize(state: State) -> dict:
return {
"normalized_query": state["query"].strip().lower()
}
def respond(state: State) -> dict:
return {
"response": f"Received: {state['normalized_query']}"
}
builder = StateGraph(State)
builder.add_node("normalize", normalize)
builder.add_node("respond", respond)
builder.add_edge(START, "normalize")
builder.add_edge("normalize", "respond")
builder.add_edge("respond", END)
graph = builder.compile()
result = graph.invoke({"query": " RESET PASSWORD "})
print(result)Expected output:
{'query': ' RESET PASSWORD ', 'normalized_query': 'reset password', 'response': 'Received: reset password'}Notice that normalize() and respond() return partial state updates. LangGraph merges those updates into the existing state instead of requiring every node to return the entire dictionary.
The compiled graph contains the information needed to determine when each node should execute and how its updates should affect subsequent nodes.
What does compile() check?
Compilation performs structural validation before constructing the executable graph.
Important checks include:
- Whether the graph has an entry point originating from
START. - Whether known edge sources refer to registered nodes.
- Whether known edge destinations refer to registered nodes or
END. - Whether explicitly declared conditional destinations exist.
- Whether named interrupt points refer to valid nodes.
Some invalid definitions, such as duplicate node names, may be rejected earlier when you register nodes or edges.
The following example demonstrates a missing entry point and how to correct it.
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
class State(TypedDict):
value: int
def increment(state: State) -> dict:
return {"value": state["value"] + 1}
builder = StateGraph(State)
builder.add_node("increment", increment)
builder.add_edge("increment", END)
try:
builder.compile()
except ValueError as error:
print("Compilation failed:", error)
builder.add_edge(START, "increment")
graph = builder.compile()
print(graph.invoke({"value": 10}))Expected output:
Compilation failed: Graph must have an entrypoint: add at least one edge from START to another node
{'value': 11}The first compilation attempt fails because LangGraph does not know where execution should begin.
Once the entry point is registered, compilation succeeds.
What compilation cannot guarantee
Successful compilation does not prove that your workflow is logically correct.
| Problem | Usually detected |
|---|---|
| Missing entry point | Compilation |
| Unknown static edge destination | Construction or compilation |
| Invalid declared routing destination | Compilation |
| Duplicate node name | Construction |
| Missing state value accessed by a node | Execution |
| Invalid dynamically calculated destination | Execution |
| Incorrect business calculation | Testing |
| Failed external API request | Execution |
| Conflicting parallel state updates | Execution |
| Non-terminating agent loop | Execution |
Compilation is not a comprehensive reachability analysis. Do not assume every disconnected or unreachable node will be rejected.
Likewise, TypedDict primarily describes dictionary structure for typing purposes. It does not automatically guarantee that every incoming value has the correct type.
A graph can compile successfully and still fail when processing an unexpected input.
Note: Successful compilation establishes structural validity, not business correctness. Unit tests, integration tests, and explicit input validation remain necessary.
What happens internally?
LangGraph uses a graph execution model inspired by Pregel, a system for coordinated graph computation.
State fields are represented through internal channels. Execution advances through units called super-steps.
Conceptually, each super-step involves three phases:
- Determine which nodes are eligible to execute.
- Execute the selected nodes using the available state.
- Apply their updates and determine what becomes eligible next.
Sequential nodes generally execute in different super-steps. Independent branches can execute within the same super-step, subject to execution constraints.
Updates from parallel nodes become available to subsequent execution steps after the current step’s updates are applied. Reducers determine how compatible updates to shared state fields are combined.
Consider the following parallel research workflow.
The two search nodes can run concurrently. The combining node should be configured with an appropriate join dependency when it must wait for both branches.
This execution model is why graph recursion limits count super-steps rather than ordinary Python function calls.
Compilation options
The compile() method also accepts infrastructure components and debugging options.
| Option | Purpose |
|---|---|
checkpointer |
Saves execution state for persistence and resumption. |
store |
Provides access to shared, longer-lived application data. |
cache |
Enables caching for nodes configured with cache policies. |
interrupt_before |
Pauses execution before specified nodes. |
interrupt_after |
Pauses execution after specified nodes. |
debug |
Enables additional execution diagnostics. |
name |
Assigns a name to the compiled graph. |
You do not need these options for every graph. Later lessons will explore persistence, caching, and human approval workflows in greater detail.
For now, remember that compilation is the appropriate stage for attaching workflow-level infrastructure.
In a web service, compile your graph during application initialization rather than rebuilding it for every HTTP request.
If you change the builder’s topology, compile it again to obtain the updated executable graph. An existing compiled graph should not be treated as a live reflection of subsequent builder modifications.
Official reference: StateGraph.compile.
Ways to run a graph
A compiled graph exposes several execution methods through its Runnable interface.
The appropriate method depends on whether you need one result, multiple results, asynchronous execution, or intermediate progress.
| Method | Execution style | Typical use case |
|---|---|---|
invoke() |
Synchronous, single input | Scripts and simple requests |
ainvoke() |
Asynchronous, single input | Async REST endpoints |
stream() |
Synchronous iterator | Console progress and debugging |
astream() |
Asynchronous iterator | Streaming web responses |
batch() |
Synchronous, multiple inputs | Bulk document processing |
abatch() |
Asynchronous, multiple inputs | Concurrent request processing |
Synchronous execution with invoke()
The simplest execution method is:
result = graph.invoke(inputs)The calling thread waits until the graph produces its result or execution stops because of an error or interrupt.
For a normal completed dictionary-state workflow using the default output behavior, the returned result contains the final graph state, subject to any configured output schema.
Use invoke() when intermediate updates are unnecessary.
Batch execution
Batch execution processes multiple independent inputs through the same compiled graph.
This example classifies several support requests without constructing a separate graph for each request.
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
class State(TypedDict, total=False):
query: str
category: str
def classify(state: State) -> dict:
query = state["query"].lower()
if "invoice" in query or "payment" in query:
category = "billing"
elif "password" in query:
category = "technical"
else:
category = "general"
return {"category": category}
builder = StateGraph(State)
builder.add_node("classify", classify)
builder.add_edge(START, "classify")
builder.add_edge("classify", END)
graph = builder.compile()
requests = [
{"query": "Download my invoice"},
{"query": "Reset my password"},
{"query": "What are your opening hours?"},
]
results = graph.batch(
requests,
config={"max_concurrency": 2},
)
for result in results:
print(result["category"])Expected output:
billing
technical
generalEach input represents an independent graph execution. The returned list follows the input order, even when individual executions finish at different times.
max_concurrency limits the number of simultaneous operations managed by the relevant Runnable execution mechanisms.
By default, an execution exception can cause the batch call to raise. When individual failures should be collected alongside successful outputs, use:
results = graph.batch(
requests,
return_exceptions=True,
)You must then inspect the returned items for exceptions.
Batch execution does not necessarily combine multiple model requests into a single provider API call. It generally coordinates multiple graph executions.
Asynchronous execution
Network operations such as model calls, database queries, and external REST requests often spend substantial time waiting for responses.
Asynchronous execution allows the application to perform other work during these waiting periods.
Use ainvoke() with asynchronous nodes and abatch() for multiple asynchronous executions.
The following example simulates an asynchronous order lookup.
import asyncio
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
class State(TypedDict, total=False):
order_id: str
status: str
async def lookup_order(state: State) -> dict:
await asyncio.sleep(0.1)
orders = {
"ORD-101": "shipped",
"ORD-102": "processing",
}
return {
"status": orders.get(
state["order_id"],
"not found",
)
}
builder = StateGraph(State)
builder.add_node("lookup_order", lookup_order)
builder.add_edge(START, "lookup_order")
builder.add_edge("lookup_order", END)
graph = builder.compile()
async def main():
result = await graph.ainvoke({
"order_id": "ORD-101"
})
print("Single:", result["status"])
results = await graph.abatch(
[
{"order_id": "ORD-101"},
{"order_id": "ORD-102"},
],
config={"max_concurrency": 2},
)
print("Batch:", [r["status"] for r in results])
if __name__ == "__main__":
asyncio.run(main())Expected output:
Single: shipped
Batch: ['shipped', 'processing']A graph containing exclusively asynchronous node implementations should be executed using asynchronous graph methods.
Inside an existing asynchronous environment, such as a FastAPI endpoint or an interactive notebook with an active event loop, directly await the relevant coroutine instead of starting another event loop with asyncio.run().
Declaring a function with async def does not automatically make blocking operations asynchronous. Use genuinely asynchronous service clients and avoid blocking calls inside the event loop.
Streaming graph execution
Imagine an agent that spends thirty seconds researching a question. Returning nothing until the entire workflow finishes creates a poor user experience.
Streaming allows your application to receive progress while execution is underway.
LangGraph supports several stream modes:
| Stream mode | Information emitted |
|---|---|
updates |
State changes produced by individual nodes. |
values |
Complete state snapshots. |
messages |
Model message chunks and associated metadata. |
custom |
Application-defined progress events. |
debug |
Detailed execution diagnostics. |
Use the current version="v2" format to receive consistently structured stream chunks.
This example emits progress events and state updates.
from typing import TypedDict
from langgraph.config import get_stream_writer
from langgraph.graph import StateGraph, START, END
class State(TypedDict, total=False):
query: str
category: str
response: str
def classify(state: State) -> dict:
writer = get_stream_writer()
writer({"status": "Classifying request"})
category = (
"billing"
if "invoice" in state["query"].lower()
else "general"
)
return {"category": category}
def respond(state: State) -> dict:
writer = get_stream_writer()
writer({"status": "Preparing response"})
return {
"response": f"Assigned to {state['category']} support"
}
builder = StateGraph(State)
builder.add_node("classify", classify)
builder.add_node("respond", respond)
builder.add_edge(START, "classify")
builder.add_edge("classify", "respond")
builder.add_edge("respond", END)
graph = builder.compile()
for chunk in graph.stream(
{"query": "I need my invoice"},
stream_mode=["updates", "custom"],
version="v2",
):
print(chunk["type"], chunk["data"])Expected output:
custom {'status': 'Classifying request'}
updates {'classify': {'category': 'billing'}}
custom {'status': 'Preparing response'}
updates {'respond': {'response': 'Assigned to billing support'}}Unlike invoke(), stream() returns an iterator. Consuming that iterator drives execution and retrieves events.
For asynchronous applications, consume graph.astream() using async for.
Streaming is itself a graph execution. Calling invoke() afterward executes the graph again; it does not simply retrieve the previous stream’s result.
Tip: Use
updatesto understand which nodes changed state andvalueswhen you need complete snapshots. Stream only information appropriate for the receiving client.
Official guide: LangGraph streaming.
Config: settings for this run
Configuration controls aspects of the graph execution rather than the business data being processed.
The configuration interface is represented by RunnableConfig, available from langchain_core.runnables.
A typical configuration looks like this:
from langchain_core.runnables import RunnableConfig
config: RunnableConfig = {
"run_name": "support_request",
"tags": ["support", "production"],
"metadata": {
"environment": "production",
"request_id": "req-1001",
},
"recursion_limit": 20,
"max_concurrency": 4,
}Pass it to the compiled graph through the config parameter:
result = graph.invoke(
{"query": "Download my invoice"},
config=config,
)Configuration is optional for many graphs, but explicit settings become increasingly valuable in production.
Important configuration fields
| Field | Responsibility |
|---|---|
run_name |
Descriptive name for the execution trace. |
tags |
Labels used to categorize and filter runs. |
metadata |
Structured, JSON-serializable tracing information. |
callbacks |
Hooks for observing execution lifecycle events. |
max_concurrency |
Concurrency limit for managed parallel operations. |
recursion_limit |
Maximum graph execution super-steps. |
configurable |
Framework and explicitly configurable Runnable settings. |
Tags and metadata are especially useful when analyzing failures, latency, and usage across many graph executions.
They do not enable a tracing backend by themselves.
To enable LangSmith tracing, install the SDK if necessary:
pip install -U langsmithConfigure the environment:
export LANGSMITH_TRACING=true
export LANGSMITH_API_KEY="your-api-key"
export LANGSMITH_PROJECT="langgraph-course"Never place API keys or confidential customer information in tracing metadata. Metadata may be transmitted to observability infrastructure.
Official reference: RunnableConfig.
Controlling graph recursion
Agentic workflows frequently contain loops. An agent might repeatedly call tools, inspect results, and decide whether more information is required.
Incorrect routing can create a loop that never terminates.
LangGraph’s recursion limit provides an execution safety boundary. Current LangGraph releases use a high default of 10,007 super-steps, so production applications should generally specify a smaller, appropriate limit.
The following intentionally faulty graph demonstrates how this protection works.
from typing import TypedDict
from langgraph.errors import GraphRecursionError
from langgraph.graph import StateGraph, START
class State(TypedDict):
attempts: int
def retry(state: State) -> dict:
return {"attempts": state["attempts"] + 1}
builder = StateGraph(State)
builder.add_node("retry", retry)
builder.add_edge(START, "retry")
builder.add_edge("retry", "retry")
graph = builder.compile()
try:
graph.invoke(
{"attempts": 0},
config={"recursion_limit": 5},
)
except GraphRecursionError:
print("Execution stopped: recursion limit reached")Expected output:
Execution stopped: recursion limit reachedCompilation succeeds because loops are legal graph structures. Execution fails because this particular loop has no termination condition.
The correct solution is to introduce an explicit exit condition, not simply increase the recursion limit.
A recursion limit is not a wall-clock timeout, token budget, or direct limit on the number of model calls. Those constraints require separate controls.
Configuration and checkpoint identity
When persistence is enabled, configurable has an important framework-specific purpose: identifying the checkpoint thread.
from typing import TypedDict
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import StateGraph, START, END
class State(TypedDict):
count: int
def increment(state: State) -> dict:
return {"count": state["count"] + 1}
builder = StateGraph(State)
builder.add_node("increment", increment)
builder.add_edge(START, "increment")
builder.add_edge("increment", END)
graph = builder.compile(
checkpointer=InMemorySaver()
)
config = {
"configurable": {
"thread_id": "counter-thread-001"
},
"recursion_limit": 10,
}
print(graph.invoke({"count": 0}, config=config))
print(graph.get_state(config).values)Expected output:
{'count': 1}
{'count': 1}The thread_id identifies the checkpoint history associated with this execution.
Without a checkpointer, ordinary invocations do not automatically retain previous graph state.
InMemorySaver is appropriate for learning and local testing but does not provide durable storage across application restarts.
A checkpoint thread identifier is not an authentication mechanism. Your application must verify that the caller is authorized to access the requested thread.
Runtime context: dependencies for this run
Why runtime context exists
Suppose a support graph requires a database client and the authenticated customer’s identifier.
Putting both values into graph state creates unnecessary coupling between workflow data and application infrastructure.
For example, a database connection may not be serializable, while graph state might eventually be checkpointed or exposed through an API.
Runtime context solves this problem by supplying dependencies separately from state.
There are three categories of information to distinguish.
| Category | State | Config | Runtime context |
|---|---|---|---|
| Main purpose | Workflow data | Execution controls | Application dependencies |
| Examples | Query, answer, attempts | Tags, recursion limit, thread ID | User ID, service client, locale |
| Access | state |
config |
runtime.context |
| Updated by nodes | Yes | Not normally | Treat as read-only |
| Included in state checkpoints | Eligible state fields | No, not as state fields | No, not automatically |
Think of state as what the workflow is processing, configuration as how it should execute, and context as what it needs to know or access.
Defining typed context
LangGraph supports a context schema through the context_schema argument of StateGraph.
A frozen dataclass is particularly useful because it makes request-specific settings explicit and prevents accidental field reassignment.
The following example personalizes a support response using runtime context.
from dataclasses import dataclass
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.runtime import Runtime
class State(TypedDict, total=False):
query: str
response: str
@dataclass(frozen=True)
class Context:
customer_id: str
language: str
def respond(
state: State,
runtime: Runtime[Context],
) -> dict:
context = runtime.context
greetings = {
"en": "Hello",
"es": "Hola",
}
greeting = greetings.get(context.language, "Hello")
return {
"response": (
f"{greeting}, how can we help with "
f"{state['query']}?"
)
}
builder = StateGraph(
State,
context_schema=Context,
)
builder.add_node("respond", respond)
builder.add_edge(START, "respond")
builder.add_edge("respond", END)
graph = builder.compile()
for language in ["en", "es"]:
result = graph.invoke(
{"query": "billing"},
context=Context(
customer_id="customer-101",
language=language,
),
)
print(result)Expected output:
{'query': 'billing', 'response': 'Hello, how can we help with billing?'}
{'query': 'billing', 'response': 'Hola, how can we help with billing?'}The same compiled graph processes both requests.
The customer identifier and language are not automatically copied into the output state. Only data explicitly returned by nodes becomes a state update.
The runtime object is supplied by LangGraph when the node executes. You do not construct Runtime manually during normal graph invocation.
Dependency injection with service clients
Runtime context can also contain initialized Python objects.
This technique is called dependency injection: instead of constructing a dependency inside a node, you supply it from outside.
The following example uses a simulated account service to retrieve customer-specific information.
from dataclasses import dataclass
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.runtime import Runtime
class AccountService:
def __init__(self, accounts: dict[str, float]):
self.accounts = accounts
def get_balance(self, customer_id: str) -> float:
return self.accounts[customer_id]
class State(TypedDict, total=False):
query: str
response: str
@dataclass(frozen=True)
class Context:
customer_id: str
account_service: AccountService
def lookup_balance(
state: State,
runtime: Runtime[Context],
) -> dict:
context = runtime.context
balance = context.account_service.get_balance(
context.customer_id
)
return {
"response": f"Your balance is ${balance:.2f}"
}
builder = StateGraph(
State,
context_schema=Context,
)
builder.add_node("lookup_balance", lookup_balance)
builder.add_edge(START, "lookup_balance")
builder.add_edge("lookup_balance", END)
graph = builder.compile()
service = AccountService({
"customer-a": 120.50,
"customer-b": 350.00,
})
for customer_id in ["customer-a", "customer-b"]:
result = graph.invoke(
{"query": "What is my balance?"},
config={
"tags": ["account", "balance"],
"recursion_limit": 10,
},
context=Context(
customer_id=customer_id,
account_service=service,
),
)
print(result["response"])Expected output:
Your balance is $120.50
Your balance is $350.00Dependency injection makes nodes easier to test because a real database or API client can be replaced with a simulated implementation.
In production, initialize shared clients at application startup when appropriate, derive customer identity from verified authentication, and pass request-specific context during invocation.
Additional runtime capabilities
The Runtime object provides more than application context.
For example, runtime.store provides access to a store attached during compilation, while runtime.stream_writer allows nodes to emit custom streaming events.
These capabilities avoid unnecessary global variables and make dependencies explicit.
Runtime context itself should be treated as immutable throughout an execution. A frozen dataclass prevents field reassignment, but objects stored inside it may still be mutable. Shared clients must therefore be safe for the concurrency model you use.
Context is also not automatically restored from graph checkpoints. Applications resuming persisted executions should supply the necessary context again and reconstruct any required service dependencies.
Official reference: LangGraph Runtime.
Common mistakes and production practices
One common mistake is passing business settings through the framework configuration dictionary:
config = {
"configurable": {
"customer_id": "customer-101",
"language": "en",
}
}Although older LangGraph applications frequently used this pattern, current applications should use context_schema and runtime.context for these values.
Another mistake is storing a customer’s identity in a mutable module-level variable. Concurrent requests could overwrite that variable and accidentally access another customer’s information.
Use request-specific context instead.
Other important practices include:
- Compile the graph once and reuse it where practical.
- Validate external inputs and context before invoking the graph.
- Set deliberate recursion and concurrency limits.
- Keep database connections and service clients outside graph state.
- Do not assume context schemas enforce all business validation rules.
- Supply unique checkpoint thread identifiers for independent conversations.
- Avoid exposing sensitive state or context through logs and streaming events.
- Test every routing branch and important failure condition.
For monetary calculations in production, use decimal arithmetic or integer minor units instead of floating-point values.
Preparing for the intelligent query router
In the next lesson, Project: an intelligent query router, you will combine the concepts introduced throughout this chapter.
Your router will accept an incoming question, classify its intent, select an appropriate processing node, and return a response.
State will carry the question, selected route, and generated answer. Conditional edges will determine which processing branch executes. Configuration will control execution limits and observability, while runtime context will supply application-specific settings and dependencies.
The router can then be compiled once and reused across multiple requests, providing the foundation for a more capable agentic application without tightly coupling workflow logic to its surrounding infrastructure.
Build a configurable pricing workflow
Build a graph that calculates an order's final price using a quantity, unit price, and customer-specific discount supplied through runtime context. Compile the graph once and invoke it for two customers with different discount rates. Configure each execution with tracing tags, metadata, and a recursion limit. Verify that customer-specific information remains outside the graph state.
from dataclasses import dataclass
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.runtime import Runtime
class OrderState(TypedDict, total=False):
quantity: int
unit_price: float
subtotal: float
final_price: float
@dataclass(frozen=True)
class Context:
customer_id: str
discount_rate: float
def calculate_subtotal(state: OrderState) -> dict:
# TODO: Calculate quantity multiplied by unit price.
raise NotImplementedError
def apply_discount(
state: OrderState,
runtime: Runtime[Context],
) -> dict:
# TODO: Read discount_rate from runtime context.
# TODO: Calculate and return the final price.
raise NotImplementedError
builder = StateGraph(OrderState, context_schema=Context)
# TODO: Register both nodes.
# TODO: Connect START, both nodes, and END.
# TODO: Compile the graph.
# TODO: Invoke it for two different customers.
# TODO: Supply config and context separately.
# Expected final prices for quantity=3, unit_price=100:
# Customer A with a 10% discount: 270.0
# Customer B with a 20% discount: 240.0from dataclasses import dataclass
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.runtime import Runtime
class OrderState(TypedDict, total=False):
quantity: int
unit_price: float
subtotal: float
final_price: float
@dataclass(frozen=True)
class Context:
customer_id: str
discount_rate: float
def __post_init__(self):
if not 0 <= self.discount_rate <= 1:
raise ValueError("Invalid discount rate")
def calculate_subtotal(state: OrderState) -> dict:
return {
"subtotal": state["quantity"] * state["unit_price"]
}
def apply_discount(
state: OrderState,
runtime: Runtime[Context],
) -> dict:
discount = runtime.context.discount_rate
return {
"final_price": round(
state["subtotal"] * (1 - discount), 2
)
}
builder = StateGraph(OrderState, context_schema=Context)
builder.add_node("calculate_subtotal", calculate_subtotal)
builder.add_node("apply_discount", apply_discount)
builder.add_edge(START, "calculate_subtotal")
builder.add_edge("calculate_subtotal", "apply_discount")
builder.add_edge("apply_discount", END)
graph = builder.compile()
order = {
"quantity": 3,
"unit_price": 100.0,
}
customers = [
Context(customer_id="customer-a", discount_rate=0.10),
Context(customer_id="customer-b", discount_rate=0.20),
]
results = []
for index, customer in enumerate(customers):
config = {
"run_name": "calculate_order_price",
"tags": ["pricing", "exercise"],
"metadata": {"request_number": index + 1},
"recursion_limit": 10,
}
result = graph.invoke(
order.copy(),
config=config,
context=customer,
)
results.append(result)
print(customer.customer_id, result["final_price"])
assert "customer_id" not in result
assert "discount_rate" not in result
assert results[0]["final_price"] == 270.0
assert results[1]["final_price"] == 240.0
print("All checks passed.")Summary
- The StateGraph builder describes a workflow, while compile() creates its executable representation.
- Compilation validates known graph connections and entry points but cannot guarantee correct business logic or termination.
- Compiled graphs support synchronous, asynchronous, streaming, and batch execution through a consistent Runnable interface.
- RunnableConfig controls execution settings such as tracing metadata, concurrency, checkpoint thread identity, and recursion limits.
- Runtime context supplies request-specific dependencies and application settings without adding them to graph state.
- A compiled graph can be reused across independent requests with different inputs, configurations, and contexts.
- Explicit execution limits, validated context, and isolated request data are essential foundations for production applications.