LangChain 进阶必备:lca-lc-foundations 掌握 Runtime Context 运行时上下文

原创2026-11-02 10:55:091,655 阅读

LangChain 进阶必备:lca-lc-foundations 掌握 Runtime Context 运行时上下文

想快速掌握 LangChain 的 Runtime Context(运行时上下文) 吗?开源课程仓库 lca-lc-foundations 正是学习这一特性的最佳起点。它把「上下文」与「会话状态」清晰分离,让你只需几行代码,就能在调用时注入用户偏好、角色、语言等变量,并让 Agent 的工具与中间件动态响应这些变量。

一句话理解:State 是"对话里记住的东西",Runtime Context 是"每次调用都带上、但不进入对话历史的东西"。

先搞清楚:Runtime Context 到底是什么?

在 LangChain 里,信息大体分三类,很多人会混淆:

  • Messages(消息):用户和模型之间的对话历史。
  • State(状态):跨轮次保留、可被读写、并持久化的"记忆",适合随对话演进的变量。
  • Runtime Context(运行时上下文):每次调用时从外部注入的一组结构化数据,默认不写进 State、不进入对话历史,却能让工具(Tool)和中间件(Middleware)读到,用来做"因人而异"的动态行为。

lca-lc-foundations 把这三者拆开讲,正是它最值得推荐的原因。下面跟着仓库里的 Notebook,一步步上手。

LangChain Runtime Context 运行时上下文课程仓库 lca-lc-foundations 的多模态示例图

三步上手:定义、绑定、注入

lca-lc-foundations 的核心示例在 notebooks/module-2/2.2_runtime_context.ipynb。整个流程只有三步,非常清爽。

第 1 步:用一个 dataclass 定义上下文结构。 以"用户最爱的颜色"为例:

from dataclasses import dataclass

@dataclass
class ColourContext:
    favourite_colour: str = "blue"
    least_favourite_colour: str = "yellow"

第 2 步:在创建 Agent 时用 context_schema 绑定结构。 告诉 LangChain"我会在调用时传一个长这样的对象":

from langchain.agents import create_agent

agent = create_agent(
    model="gpt-5-nano",
    context_schema=ColourContext,   # 声明上下文的"形状"
)

第 3 步:调用时通过 context= 注入具体值。

response = agent.invoke(
    {"messages": [HumanMessage(content="What is my favourite colour?")]},
    context=ColourContext(),
)

就这么简单——上下文已经"就位"。但此时模型本身还不知道它,接下来要看谁来消费它。

让工具读取上下文:ToolRuntime

上下文真正的威力,在于它能被 Agent 的工具读取。在 2.2_runtime_context.ipynb 中,作者给两个工具都加了一个 runtime: ToolRuntime[ColourContext] 参数:

from langchain.tools import tool, ToolRuntime

@tool
def get_favourite_colour(runtime: ToolRuntime[ColourContext]) -> str:
    """Get the favourite colour of the user"""
    return runtime.context.favourite_colour

把这两个工具交给 Agent 后,模型问"我最爱的颜色是什么"时,会主动调用 get_favourite_colour,通过 runtime.context 拿到答案。更妙的是:同一套代码,注入不同上下文,答案就不同。

# 默认是蓝色
agent.invoke({...}, context=ColourContext())
# 注入绿色 —— 答案随之改变
agent.invoke({...}, context=ColourContext(favourite_colour="green"))

这就是 Runtime Context 的精髓:逻辑固定,行为可变。

进阶:让 Prompt 和 Tools 随上下文动态变化

仓库把这一特性用到了"生产级"。在 notebooks/module-3/3.4_dynamic_prompts.ipynb 中,上下文携带 user_language,通过 @dynamic_prompt 中间件根据语言动态改写系统提示词:

@dynamic_prompt
def user_language_prompt(request: ModelRequest) -> str:
    user_language = request.runtime.context.user_language
    if user_language != "English":
        return f"You are a helpful assistant. only respond in {user_language}."

注入 LanguageContext(user_language="Spanish"),模型就用西班牙语回答——无需改任何代码。

3.4_dynamic_tools.ipynb 则用 @wrap_model_call 依据 user_role 动态开关工具:内部用户可查 SQL 数据库,外部用户只能用 web_search,实现基于角色的权限控制。

综合实战:邮件助手的上下文鉴权

最完整的范例是 notebooks/module-3/3.5_email_agent.py。它用 EmailContext 携带邮箱与密码,authenticate 工具读取 runtime.context.email_address 做校验,再由中间件决定"能查收件箱 / 能发信 / 只能鉴权",并配合 HITL(人在回路)拦截敏感操作:

@dataclass
class EmailContext:
    email_address: str = "julie@example.com"
    password: str = "password123"

agent = create_agent(
    "gpt-5-nano",
    tools=[authenticate, check_inbox, send_email],
    context_schema=EmailContext,
    middleware=[dynamic_tool_call, dynamic_prompt_func, ...],
)

这正是"上下文驱动一切"的落地形态:同一 Agent,不同上下文,不同的能力、提示词与权限。

Runtime Context vs State:到底该用哪个?

2.2_state.ipynb 专门演示了 State 的写法,正好和 Context 形成对照,帮你做决策:

维度 State(状态) Runtime Context(运行时上下文)
生命周期 跨轮次保留、可持久化 每次调用注入,不写入历史
谁能改 工具可通过 Command(update=...) 写回 外部注入,Agent 只读
典型场景 对话中逐渐记住的信息 用户身份、角色、语言、密钥等
读取方式 runtime.state["key"] runtime.context.xxx

简单判断:"会变、要记住"用 State;"每次调用都该带上、不该进历史"用 Context。

动手环境:如何跑起来这个课程仓库

lca-lc-foundations 要求 Python 3.12+,推荐用 uv。完整步骤见 README.md:

git clone --depth 1 https://gitcode.com/gh_mirrors/lc/lca-lc-foundations
cd lca-lc-foundations
cp example.env .env     # 填入 OPENAI_API_KEY 等
uv sync
uv run jupyter lab

打开 Jupyter 后,按模块学习即可。涉及 Context 的文件都集中在 notebooks/module-2/ 与 notebooks/module-3/ 目录下,建议按 2.2 → 3.4 → 3.5 的顺序渐进练习。

小结

  • 定义:用一个 dataclass 描述上下文结构。
  • 绑定:create_agent(..., context_schema=...)。
  • 注入:agent.invoke(..., context=...)。
  • 消费:工具用 runtime.context,中间件用 request.runtime.context。
  • 选型:持久记忆用 State,调用级变量用 Runtime Context。

掌握 Runtime Context,你的 Agent 就能做到"千人千面"——同一套代码,随上下文自动切换语言、权限与能力。这正是 lca-lc-foundations 这门课程留给进阶者最有价值的技能之一。🚀

登录后查看全文
lca-lc-foundations