LangGraph Runtime Context
本文最后更新于 2026年7月25日
1.概述
在创建图时,langgraph支持指定上下文context_schema,通过上下文将某些配置信息传递给节点
使用context_schema的优势:
- 分离关注点,上下文信息与State不同,上下文将运行时配置和State分离,以保证状态中没有无用的信息
- 类型安全,上下文通过定义数据类,易于类型检查
- 易于管理,统一管理运行时依赖,例如数据库连接配置,大模型API KEY等
context_schema不属于图的State,但是运行时需要被节点访问,它与State的区别是:
| State | Context | |
|---|---|---|
| 定义 | TypedDict |
@dataclass |
| 内容 | 随着图的执行不断变化 | 图执行期间固定不变 |
| 创建 | StateGraph(state_schema=x) |
StateGraph(context_schema=x) |
| 传值方式 | invoke(x)/invoke(input=x) |
invoke(context=x) |
| 用途 | 存储消息列表,处理结果 | 存储数据库连接配置,大模型配置 |
| 访问方式 | state['x'] |
runtime.context.x |
2.定义
context_schema采用@dataclass定义,在创建图时context_schema=ContextSchema指定context_schema对应的class,在app.invoke(input=dic, context=ctx)调用图时通过context参数传入class的字段值,在节点函数上,通过runtime: Runtime[ContextSchema]参数获取全局的上下文,需要注意的是参数名必须是“runtime”
from typing import TypedDict
from dataclasses import dataclass
from langgraph.constants import START, END
from langgraph.graph import StateGraph
from langgraph.runtime import Runtime
@dataclass
class ContextSchema:
deepseek_api_key: str
qwen_api_key: str
class DemoState(TypedDict):
msg: str
def node1(state: DemoState, runtime: Runtime[ContextSchema]):
print(runtime.context.qwen_api_key)
return state
def node2(state: DemoState, runtime: Runtime[ContextSchema]):
print(runtime.context.deepseek_api_key)
return state
if __name__ == "__main__":
graph = StateGraph(state_schema=DemoState, context_schema=ContextSchema)
graph.add_node('node1', node1)
graph.add_node('node2', node2)
graph.add_edge(START, 'node1')
graph.add_edge('node1', 'node2')
graph.add_edge('node2', END)
app = graph.compile()
ctx = ContextSchema(
deepseek_api_key='bbbbbbbbbb',
qwen_api_key='aaaaaaaaa'
)
dic = DemoState(msg='hello world')
res = app.invoke(input=dic, context=ctx)
print(res)aaaaaaaaa
bbbbbbbbbb
{'msg': 'hello world'}"如果文章对您有帮助,可以请作者喝杯咖啡吗?"
微信支付
支付宝
LangGraph Runtime Context
https://blog.liuzijian.com/post/2026/07/25/langgraph-runtime-context/