LangChain1.0智能体开发:运行时(Runtime)

基于LangChain1.0创建的智能体是运行在LangGraph的运行时(Runtime)之上。LangChain可以通过LangGraph对外暴露的运行时对象访问上下文、存储以及流写入器。

1、运行时概述

LangChain的create_agent本质上运行在LangGraph的运行时(Runtime)之上。LangGraph会暴露一个包含以下信息的运行时对象(Runtime object):

  • 上下文(Context):静态信息,例如用户ID、数据库连接或智能体调用所需的其他依赖项。
  • 存储(Store):一个用于长期记忆的BaseStore实例。
  • 流写入器(Stream writer):一个用于通过自定义流模式传输信息的对象。

你可以在工具和中间件内部访问运行时信息。

2、配置运行时上下文

运行时上下文(Runtime Context)为工具(tools)和中间件(middleware)提供依赖注入功能。无需硬编码值或使用全局状态,你可以在调用智能体时注入运行时依赖项(如数据库连接、用户ID或配置)。这使得你的工具更易于测试、更具可复用性且灵活性更高。 使用create_agent创建智能体时,你可以指定一个context_schema(上下文模式),用于定义存储在智能体运行时(Runtime)中的上下文结构。调用智能体时,需传入context参数,并在该参数中包含本次运行所需的相关配置。

python 复制代码
from dataclasses import dataclass
from langchain.agents import create_agent


@dataclass
class Context:
    user_name: str

agent = create_agent(
    model="gpt-5-nano",
    tools=[...],
    context_schema=Context  
)

agent.invoke(
    {"messages": [{"role": "user", "content": "What's my name?"}]},
    context=Context(user_name="John Smith")  
)

3、通过工具访问运行时信息

你可以在工具内部访问运行时信息,以实现以下操作:

  • 访问上下文:通过runtime.context访问上下文信息。
  • 读取或写入长期记忆:通过runtime.store访问长期记忆。
  • 写入自定义流(例如,工具进度 / 更新):通过get_stream_writer()获取流写入器,然后使用流写入器写入自定义流。 可使用ToolRuntime参数在工具内部访问运行时(Runtime)对象。
python 复制代码
from dataclasses import dataclass
from langchain.tools import tool, ToolRuntime  

@dataclass
class Context:
    user_id: str

@tool
def fetch_user_email_preferences(runtime: ToolRuntime[Context]) -> str:  
    """Fetch the user's email preferences from the store."""
    user_id = runtime.context.user_id  

    preferences: str = "The user prefers you to write a brief and polite email."
    if runtime.store:  
        if memory := runtime.store.get(("users",), user_id):  
            preferences = memory.value["preferences"]

    return preferences

4、通过中间件访问运行时信息

你可以在中间件中访问运行时信息,从而根据用户上下文创建动态提示词、修改消息或控制智能体行为。

  • 对于封装式中间件,可通过request.runtime访问运行时(Runtime)对象。request运行时对象包含在传递给中间件函数的ModelRequest参数中。
  • 对于节点式中间件,可通过runtime参数访问运行时(Runtime)对象。
python 复制代码
from dataclasses import dataclass
from langchain.messages import AnyMessage
from langchain.agents import create_agent, AgentState
from langchain.agents.middleware import dynamic_prompt, ModelRequest, before_model, after_model
from langgraph.runtime import Runtime


@dataclass
class Context:
    user_name: str

# Dynamic prompts
@dynamic_prompt
def dynamic_system_prompt(request: ModelRequest) -> str:
    user_name = request.runtime.context.user_name  
    system_prompt = f"You are a helpful assistant. Address the user as {user_name}."
    return system_prompt

# Before model hook
@before_model
def log_before_model(state: AgentState, runtime: Runtime[Context]) -> dict | None:  
    print(f"Processing request for user: {runtime.context.user_name}")  
    return None

# After model hook
@after_model
def log_after_model(state: AgentState, runtime: Runtime[Context]) -> dict | None:  
    print(f"Completed request for user: {runtime.context.user_name}")  
    return None

agent = create_agent(
    model="gpt-5-nano",
    tools=[...],
    middleware=[dynamic_system_prompt, log_before_model, log_after_model],  
    context_schema=Context
)

agent.invoke(
    {"messages": [{"role": "user", "content": "What's my name?"}]},
    context=Context(user_name="John Smith")
)
相关推荐
hhzz1 分钟前
《深度学习框架PyTorch入门与实践》系列:01-PyTorch入门与环境搭建之从安装到第一个神经网络
人工智能·pytorch·神经网络
一个天蝎座 白勺 程序猿6 分钟前
MongoDB迁移新范式|从烟囱式孤岛到KES-AI融合架构
人工智能·mongodb·架构·kingbasees
倍利福猎头公司官方账号7 分钟前
人形机器人分析——电机(机器人猎头公司专项分析)
大数据·人工智能·机器人·求职招聘·业界资讯
稳石氢能12 分钟前
政策落地与市场冷遇并存,氢能产业如何跨越“最后一公里”?
大数据·人工智能
9i编程16 分钟前
手敲重构学透 Multi-Agent 代码(下):从 AgentScope 1.0.8 升级到 2.0,API 变了什么、踩了哪些坑
人工智能·openai·ai编程
安逸Ai18 分钟前
AI 编程助手如何读取、检索和修改大型代码仓库?
人工智能
码云之上19 分钟前
Harness Engineering:让 Agent 在受控边界内运行
人工智能·前端框架·前端工程化
AI 小老六24 分钟前
Agent Runtime 如何用 Session、Memory、User Profile 和 Skill 实现外部学习
服务器·人工智能·学习·ai·架构·自动化
aqi0028 分钟前
15天学会AI应用开发(十九)使用LangGraph实现持久记忆功能
人工智能·python·大模型·ai编程·ai应用