LangGraph Runtime: keeping runtime dependencies separate from state
Use context_schema and Runtime to pass a model choice into a node, then check state and context separately.
Prepare the input and environment · Mechanism and data flow · Workflow map
At a glance
This article covers one task: passing a runtime dependency such as a model choice to a node through context instead of graph state, then checking what ends up in state. It rests on the Runtime context section of the official Graph API page. In the official example, get_llm only returns the provider string and calls no model, so output is a string, not a model answer.
Runtime and applicability
- Article type
- Engineering practice
- Verified
- Applies to
- LangGraph Documented langgraph task and conditions
Execution locations and responsibilities
- Python application definition and caller Define the configuration or request shown here and check its inputs, outputs and failure branches.
When to use
- A Python environment where LangGraph can be installed and run, with
langgraph.graph,langgraph.runtimeandtyping_extensionsimportable. The official page gives no install command or version requirement, so check the official docs first.
When not to use
get_llmin the example calls no model, sooutputis not a model answer, and the code alone does not prove semantic correctness.
Prepare the input and environment
- A Python environment where LangGraph can be installed and run, with
langgraph.graph,langgraph.runtimeandtyping_extensionsimportable. The official page gives no install command or version requirement, so check the official docs first. - A dependency you want to hand to a node, such as a model name or a database handle. The example here passes only one string,
llm_provider. - A clear idea of the two things to inspect: what should appear in state and what should appear in context.
Mechanism and data flow
State and runtime dependencies are separate data: The official page describes State as the shared data nodes read and update, stored in channels named after the keys of the state schema. Nodes return partial updates, and LangGraph applies them through each channel's reducer; with no reducer, a new value overwrites the old one. Runtime context passes dependencies into nodes, and the page says this avoids putting them in graph state, naming a model name and a database handle as examples.
Declared at build time, supplied at call time: The example declares the shape of context with StateGraph(State, context_schema=ContextSchema), where ContextSchema is a dataclass with an llm_provider field. The page also says a graph must be compiled before you invoke or stream it, and that compilation checks graph structure, for example for orphaned nodes. The actual value is given in graph.invoke through the context argument, which is separate from the input dictionary.
Nodes read context through the runtime argument: The page says a node can accept state, config and runtime, where runtime is a Runtime object with runtime context, store, stream_writer, execution_info and related helpers. The example's node_a declares runtime: Runtime[ContextSchema], reads runtime.context.llm_provider, and places the result in the returned {"output": llm}. The dependency enters through context and the result leaves through the return value into state, so the two paths stay apart.
Workflow map
| Stage | What happens |
|---|---|
| State and runtime dependencies are separate data | The official page describes State as the shared data nodes read and update, stored in channels named after the keys of the state schema. |
| Declared at build time, supplied at call time | The example declares the shape of context with StateGraph(State, context_schema=ContextSchema), where ContextSchema is a dataclass with an llm_provider field. |
| Nodes read context through the runtime argument | The page says a node can accept state, config and runtime, where runtime is a Runtime object with runtime context, store, stream_writer, execution_info and related helpers. |
Complete the task
Confirm the source scope and your own environment: Check the official page for the API you plan to use and prepare Python dependencies in your own environment. Nothing was installed, imported or run in this batch, so any statement about run results below either comes from the official page or is an editor-recommended check, not an execution record.
Define the state schema: The example's State is a TypedDict with two string keys, input and output. Do not add llm_provider here. For the static check, confirm that no dependency appears among the state keys. This check is an editorial recommendation, not an official requirement.
Define ContextSchema and write the node: ContextSchema is a dataclass whose llm_provider field has the default "openai". get_llm takes a provider and returns it unchanged, so the example makes no real model call. node_a reads the provider from runtime.context and returns a partial update containing only output. The official page does not say whether that default applies when context is omitted, so check the official docs before relying on it.
Build the graph and compile: Create StateGraph(State, context_schema=ContextSchema), add node_a, connect START to node_a and node_a to END, then call .compile(). The page requires compiling before invoking. If compilation raises an error, treat it as the failure branch and do not continue to the call.
Invoke with input and context passed separately: The example call is graph.invoke({"input": "hi"}, context={"llm_provider": "anthropic"}). The first argument is the state input, and context is its own top-level argument. The official page does not show a return value for this call.
Check the result and clean up: Reading the code, the returned output should be the string anthropic. That is an expectation drawn from the code, not output reported by the page, and it was not executed in this batch. The four exit paths below are editorial recommendations, not official behavior. Success: output is the expected string, input is still hi, and state has no llm_provider. Failure: compilation or the call raises an exception, or output differs from the provider you passed; do not record success. Empty output: output is missing or empty, which is also not success, so recheck the node's return value. User stopping: you stop the process by hand in your own environment; this article does not invent a cancellation API, and an unfinished run is not recorded as success. On every exit path, remove temporary files and virtual environments you created; if you replace get_llm with a real client, also revoke or delete any environment variables and credentials you set up for it.
Worked example
The official example works like this. State has only input and output, and ContextSchema has only llm_provider. The call passes {"input": "hi"} as input and context={"llm_provider": "anthropic"} as context. node_a writes the provider string into output. The example therefore shows how a dependency reaches a node, not how a model answers.
from dataclasses import dataclass
from langgraph.graph import END, START, StateGraph
from langgraph.runtime import Runtime
from typing_extensions import TypedDict
class State(TypedDict):
input: str
output: str
@dataclass
class ContextSchema:
llm_provider: str = "openai"
def get_llm(provider: str) -> str:
return provider
def node_a(state: State, runtime: Runtime[ContextSchema]):
llm = get_llm(runtime.context.llm_provider)
return {"output": llm}
graph = (
StateGraph(State, context_schema=ContextSchema)
.add_node("node_a", node_a)
.add_edge(START, "node_a")
.add_edge("node_a", END)
.compile()
)
graph.invoke({"input": "hi"}, context={"llm_provider": "anthropic"})
Check the result and failure paths
- Static check (editorial recommendation): the state schema contains only
inputandoutput;llm_provideris aContextSchemafield supplied throughinvoke'scontextargument. Returned state has nollm_providerkey, butoutputholds the provider string. - Semantic check (editorial recommendation): from the code,
outputshould equal the provider string passed in. This is an expectation and was not verified by execution in this batch. - On failure or empty output, do not record success, and state which item failed or was not run.
- On every exit path, including success, failure, empty output and manual stopping, clean up the temporary resources and credentials you created.
Scope and limits
- This article covers only the division of duties between context and state. It does not cover checkpointers, store, reducers or node caching, and it makes no claims about database lifetime across processes, security isolation or default persistence.
- The code is an excerpt from the official page and needs an existing LangGraph runtime; it is not promised to run standalone.
- The completion checks and manual stopping steps are editorial recommendations, not official behavior, and the official page gives no cancellation API.
No product or API was run in this batch, and no dependencies were installed. The official source supplies only example code and prose, and the expected result here is inferred from reading the code, not observed from execution.
Sources
All links are official pages; verification dates are listed per source, and links point to the version checked.