Runtime
顾名思义,就是指,agent 运行过程中,可以获取到的一些数据或者变量
主要分为Context、State、Store
专业一点的区分如下

一、Context
1.特性
对于context变量,他有下面这些特性

他是会在agent每一次调用工具,或者中间件的时侯,自动注入的,工具读取的话就是通过 runtime.context取出,生命周期就是本次运行
2.定义Context结构
1 2 3 4 5 6 7 8
| from dataclasses import dataclass
@dataclass(frozen=True)
class UserContext: """Agent运行时上下文""" user_id: str tenant_id: str
|
注意点:
- 省去魔法函数已经构造函数等等,并且通过
frozen参数确保结构不会改变
- class UserContext:就是结构约束
3.定义工具
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| from langchain.tools import tool, ToolRuntime
@tool def get_current_user_profile(runtime: ToolRuntime[UserContext]): """查询当前登录用户的资料。"""
ctx= runtime.context
print("ctx : ", ctx)
profile = USER_DATABASE.get(ctx.tenant_id, {}).get(ctx.user_id)
return f"姓名:{profile['name']},课程:{profile['course']}"
|
python中传参有点独特,放到java中,也就是

注意点:
- 工具本身是由模型决定调用的,参数不需要管,由langchain自动实现注入
- runtime.context取出context对象
4.定义agent
重点就是这里,主要是在定义agent的时候传入了context的上下文结构
所以,agent每次调用才会识别出agent的上下文结构
1 2 3 4 5 6 7 8 9
| from langchain.agents import create_agent
agent = create_agent( model="deepseek-flash", tools=[get_current_user_profile], context_schema=UserContext, system_prompt="你是课程平台助手。需要用户资料时调用工具。" )
|
context_schema=UserContext
这一行就是重点
5.调用
context被发明出来就是保证每次调用都是独立的,模型不需要保存隐私信息,通过这种自动注入的方式来实现重要信息和模型解耦,实现agent每次调用的时候都是独立的
1 2 3 4 5 6 7 8 9 10
| from langchain.messages import HumanMessage
response = agent.invoke( {"messages": [HumanMessage("Hello, 帮我查询我正在学习的课程")]}, context=UserContext(user_id="u001", tenant_id="school_a") )
for message in response['messages']: message.pretty_print()
|
所有的流程,大概就是下面这样


二、State
1.短期记忆实现
短期记忆就是通过state实现的
具体实现方式以及原理如下

checkpointer 是存取快照的组件,快照本身叫 checkpoint
同时
- checkpoint 就是对 AgentState 每次的快照
- 快照还包含下一步要执行的节点、元数据(第几步、谁写入的)、
thread_id 和 checkpoint_id
- 不是每次
invoke 存一份,而是每执行完一步就存一份一次调用里”模型思考、调用工具、再次思考”会产生多份快照
2.特性
langchain默认是最底层的AgentState,它里面只有messages,也就是会话数组,为了在每次会话里长期保存更多的东西,我们可以去扩展继承它,然后在其基础之上实现一些自定义的字段
除此之外一些特性

3.实现
3.1、场景
需求:自定义state,记录调用模型的次数,定义工具,每次调用模型后次数就累加
就是要实现每个会话中统计工具的调用次数
3.2、定义state
1 2 3 4 5 6 7
| from langchain.agents import AgentState
class CustomState(AgentState): """Agent的任务状态""" model_call_count: int
|
就是在记录聊天消息的基础之上,增加了一个计数字段
需要注意的是
State本质是一个字典,但是结构不能改变(其实就是TypedDict),所以操作的时候必须要按照字典的方式操作

3.3、定义工具
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| @tool def update_model_call_count(runtime: ToolRuntime): """A tool that count model call """
count = runtime.state.get("model_call_count", 0) print("model_call_count:", count)
update = { "model_call_count": count + 1, "messages": [ ToolMessage( content="Successfully updated agent state", tool_call_id=runtime.tool_call_id ) ] }
return Command(update=update)
|
必须通过Command(update=update)来更新值
更新谁,改谁就ok,update是一个字典,对于messages,langchain会自动拼接,我们只需要加入要更新的就ok
3.4、定义agent
1 2 3 4 5 6 7 8 9 10 11
| model = init_chat_model("deepseek-flash", extra_body={"thinking": {"type": "disabled"}})
agent = create_agent( model, tools=[update_model_call_count], state_schema=CustomState, checkpointer=InMemorySaver(), system_prompt="你是AI助手,你需要在每次回答用户前调用工具记录模型调用次数" )
|
注意,记忆是必须要开启的
3.5、调用
1 2 3 4 5 6 7 8 9 10
| from langchain.messages import HumanMessage
config = {"configurable": {"thread_id": "1"}} response = agent.invoke( {"messages": [HumanMessage(content="Hi,我是虎哥")]}, config )
for message in response['messages']: message.pretty_print()
|
必须要保证同一个会话
agent.get_state(config) 可以去拿到最新的快照 最新的checkpoint

三、Store
store不同于之前俩种,他比state周期更长呢个,他是跨会话的,算是长期记忆
1.特性

他的数据结构十分特殊

是以类似这种多级目录的形式存储
最恰当的数据展示

2.场景

就是说需要保存长期记忆的时候用到它
3.实现
3.1、初始化store
1 2 3 4
| from langgraph.store.memory import InMemoryStore
memory_store = InMemoryStore()
|
也可以基于数据库来存储
3.2、定义namespace与key
1 2 3 4 5 6 7 8 9 10
| def preference_namespace(ctx: UserContext) -> tuple[str, ...]: return ( "heima_platform", ctx.tenant_id, ctx.user_id )
key = "learning_preferences"
|
3.3、定义工具
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 27 28 29 30 31 32 33 34 35 36 37 38
| @tool def save_learning_preference( preference_name: str, preference_value: str, runtime: ToolRuntime[UserContext], ) -> str: """保存当前用户的长期学习偏好。"""
namespace = preference_namespace(runtime.context) print("namespace:", namespace)
item = runtime.store.get(namespace, key) preferences = item.value if item else {}
preferences[preference_name] = preference_value
runtime.store.put(namespace, key, preferences)
return f"已保存偏好:{preference_name}={preference_value}"
@tool def get_learning_preferences( runtime: ToolRuntime[UserContext], ) -> str: """读取当前用户的长期学习偏好。"""
namespace = preference_namespace(runtime.context) item = runtime.store.get(namespace, key)
if item is None: return "当前用户还没有保存学习偏好"
return f"当前学习偏好:{item.value}"
|
store可以允许我们自己去读取修改,所以就不需要command命令,这个是我们来维护的
3.4、创建agent
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| from langchain.agents import create_agent from langgraph.checkpoint.memory import InMemorySaver
checkpointer = InMemorySaver()
agent = create_agent( model="deepseek-flash", tools=[ get_current_user_profile, save_learning_preference, get_learning_preferences, ], context_schema=UserContext, checkpointer=checkpointer, store=store, system_prompt=( "你是课程平台助手。" "涉及用户资料时调用资料工具," "涉及长期学习偏好或给用户讲解代码时调用偏好工具。" ), )
|
重点这个就是实现了跨会话的功能,实现会话记忆
总之,大概这一部分就是下面这些知识点
