langgraph查漏补缺

注入上下文

“注入上下文”就是在运行过程中节点/大模型 可能需要、但不会(也不应该)去改变的只读信息的集合。

场景 注入上下文里可能放什么
权限控制 user_id, tenant_id(决定能访问哪些数据)
外部依赖 db_connection, api_key, s3_bucket(节点里要用)
个性化参数 language, timezone, model_temperature
会话元信息 session_id, channel(Slack / 微信 / Web)

案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from dataclasses import dataclass

from langgraph.graph import StateGraph
from langgraph.runtime import Runtime

@dataclass
class Context:
"""Context schema defined by the developer."""
user_id: str
db_connection: str

def node(state: State, runtime: Runtime[Context]):
# type safe access to context attributes
user_id = runtime.context.user_id
db_conn = runtime.context.db_connection
...

builder = StateGraph(state_schema=State, context_schema=Context)

# add nodes, edges, compile the graph...

# top level context arg is typed as Context for autocomplete and type checking
result = graph.invoke(
{'input': 'abc'},
context=Context(user_id='123', db_conn='conn_mock')
)

Runtime 类提供了一个单一接口,用于访问信息,例如:

  • 上下文:在运行开始时传递的静态数据
  • 存储:长期记忆的存储机制
  • 流写入器:用于向图输出流写入的自定义函数
  • 对于功能 API 用户,previous 也可用:给定线程的前一个返回值

现在,开发者不再需要将上述所有内容作为单独的参数注入到节点函数中, 而是可以通过一个 runtime 参数来访问它们。