LangChain Agent进阶 Runtime

Runtime

LangChain Agent 的 Runtime(运行时) 是驱动 Agent 执行“思考-行动”循环的底层引擎。理解它的关键在于认识到,现代 LangChain Agent(尤其是通过 create_agent 创建的)本质上是由 LangGraph 驱动的有向状态图(StateGraph),而 Runtime 就是管理这个图执行、状态流转和资源注入的核心环境

LangChain的create_agent实际上是在底层构建并编译一个LangGraph的StateGraph。

这个图通常包含两个核心节点,并由条件边控制流转:

  • model节点:调用LLM,并传入工具的描述信息,LLM决定是直接回复,还是返回tool_calls来调用工具
  • tools节点:接收tool_calls,找到并执行对应的真实函数,并将结果包装成ToolMessage.

Runtime运行时,主要包含以下内容:
image

Context

Context是一种依赖注入机制:调用者在运行开始时把用户身份、租户信息、权限等信息转为Agent,节点、中间件和工具在执行时再从Runtime读取

image

  • 调用时注入
  • 工具通过runtime.context按需读取
  • 生命周期仅限本次运行
  • 作用是把隐私数据与Agent解耦

案例

需求: 一个多租户的在线教育Agent,具备一个查询用户资料的工具,可以查询当前用户的资料
image

  • 步骤一 : 准备数据,模拟多租户数据
USER_DATABASE = {
    "school_a": {
        "u001": {"name": "张三", "course": "语文"},
        "u002": {"name": "李四", "course": "数学"},
    },
    "school_b": {
        "u001": {"name": "王五", "course": "英语"},
        "u002": {"name": "赵六", "course": "历史"},
    }
}
  • 步骤二: 定义Context Schema

image

  • 步骤三: 定义Tool,从Context获取信息

image

  • 步骤四: 定义Agent,置顶Context类型

image

  • 步骤五: 调用Agent,通过Context传递数据

image


# 步骤一  准备数据,模拟多租户数据
USER_DATABASE = {
    "school_a": {
        "u001": {"name": "张三", "course": "语文"},
        "u002": {"name": "李四", "course": "数学"},
    },
    "school_b": {
        "u001": {"name": "王五", "course": "英语"},
        "u002": {"name": "赵六", "course": "历史"},
    }
}

from dataclasses import dataclass

@dataclass(frozen=True)
class UserContext:
    """Agent运行时上下文"""
    user_id: str
    tenant_id: str


from langchain.tools import tool, ToolRuntime

@tool
def get_current_user_profile(runtime: ToolRuntime[UserContext]):
    """查询当前登录用户的资料"""

    # 获取context
    ctx = runtime.context

    # 根据user_id和tenant_id查询用户资料
    profile = USER_DATABASE.get(ctx.tenant_id, {}).get(ctx.user_id)

    return (
        f"姓名:{profile['name']},"
        f"课程:{profile["course"]}"
    )

from langchain.agents import create_agent

# 创建Agent时指定context_schema
agent = create_agent(
    model="deepseek-flash",
    tools=[get_current_user_profile],
    context_schema=UserContext,
    system_prompt="你是课程平台助手,需要用户资料时调用工具"
)

from langchain.messages import HumanMessage

# 调用时通过Context传递用户数据
response = agent.invoke(
    {"messages":[HumanMessage("帮我查询我正在学习的课程")]},
    context=UserContext(
        user_id="u001",
        tenant_id="school_a"
    )
)

for message in response["messages"]:
    print("="*20,message.type,"="*20)
    print(message.content)

State

LangChain的短期记忆就是基于AgentState实现的,其中有messages字段,也就是历史消息
image

AgentState则是通过CheckPointer对象保存的,每一次用户与AI的交互都会为AgentState生成一个快照,记录为一个StateSnapshot

同一个会话的多个StateSnapshot形成一个组,用同一个thread_id标记

image

AgentState中只有messages信息,保存会话历史。 如果对于一些任务执行的中间状态信息要保存,可以继承AgentState,扩展自定义字段,来保存其他信息
image

  • 使用场景: 统计模型调用次数

需求: 自定义State,记录调用模型的次数,定义工具,每次调用模型后次数累加

  • 步骤一:自定义State,继承AgentState
    image

State结构:本质是一个字典,但是结构不能改变(TypedDict);
操作方式:必须以字典方式操作State

  • 步骤二:工具中通过runtime访问State
    image

  • 步骤三:创建Agent,并制定State类型
    image

from langchain.agents import AgentState


# 自定义State结构
class CustomState(AgentState):
    """Agent的任务状态"""
    count: int  # 模型调用次数


from langchain.tools import tool, ToolRuntime
from langchain_core.messages import ToolMessage
from langgraph.types import Command

@tool
def update_model_call_count(runtime: ToolRuntime):
    """更新模型调用计数"""

    # 获取state中的count值,这里要把state当做dict来看待
    count = runtime.state.get("count", 0)
    update = {
        "count": count + 1,
        "messages": [
            ToolMessage(
                content="成功更新AgentState",
                tool_call_id=runtime.tool_call_id
            )
        ]
    }
    return Command(update=update)

from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain_core.messages import HumanMessage
from langgraph.checkpoint.memory import InMemorySaver

model = init_chat_model(
    "deepseek-flash",
    extra_body={"thinking": {"type": "disabled"}}
)

# 创建Agent时指定context_schema
agent = create_agent(
    model=model,
    tools=[update_model_call_count],
    state_schema=CustomState, # 告诉Agent使用自定义的state
    checkpointer=InMemorySaver(),
    system_prompt="你是一个有用的助手,你需要在每次回答用户问题前调用工具记录模型调用次数"
)

config = {"configurable": {"thread_id": "1"}}

# 调用agent
response = agent.invoke(
    {"messages":[HumanMessage("你好")]},
    config # 调用时添加thread_id
)

for message in response["messages"]:
    print("="*20,message.type,"="*20)
    print(message.content)


# 获取state中的count值
state = agent.get_state(config)
print(state)

Store

数据结构

  • 结构: Store是多级目录结构,用namespace+key 对应一个唯一的JSON文档;
  • 格式: namespace:元组,key:字符串
  • 操作: 读取:get(namespace, key), 存储:put(namespace,key,value)
    image

用Store实现用户偏好的长期记忆

需求: 通过Store保存用户学习偏好,实现跨会话后Agent依然记得用户学习偏好和习惯

  • 步骤一: 初始化Store
    image

  • 步骤二:定义namespace和key

image

  • 步骤三:定义工具,访问和修改Store
def preference_namespace(ctx: UserContext) -> tuple[str,...]:
  return (
   "heima_platform",
    ctx.tenant_id,
    ctx.user_id 
  )

image

@tool
def get_learning_preference(runtime: ToolRuntime[UserContext]) -> str:
  """读取当前用户的长期学习偏好"""
  namespace = preference_namespace(runtime.context)
  item = runtime.store.get(namespace, key)

  if item is None:
    return "当前用户还没有保存学习偏好"

  return f"当前学习偏好: {item.value}"

  • 步骤四:创建Agent,指定Store

checkpointer = InMemorySaver()
store = InMemoryStore()

agent = create_agent(
  model="deepseek-flash",
  tools=[
    get_current_user_profile,
    save_learning_preference,
    get_learning_preference
  ],
  context_schema=UserContext,
  checkpointer=checkpointer,
  store=store,
  system_prompt=(
    "你是课程平台助手。"
    "涉及用户资料时调用本资料工具" 
    "涉及长期学习偏好或给用户讲解代码时调用偏好工具。"
  ),
)

posted @ 2026-11-19 18:55  风陵南  阅读(14)  评论(0)    收藏  举报