一、Runnable 与输入输出约定
1.1 职责不同,执行接口相同
Runnable[Input, Output] 表示一个接收输入、产生输出的工作单元。提示词、聊天模型、解析器和检索器都可以采用这套接口,组合后的链也仍然是 Runnable。

| 组件 | 常见输入 | 常见输出 |
|---|---|---|
| 提示词模板 | 变量字典 | PromptValue |
| 聊天模型 | 文本、消息或 PromptValue | AIMessage |
| 输出解析器 | 模型消息或文本 | 字符串、字典或对象 |
| 检索器 | 查询字符串 | Document 列表 |
编译后的 LangGraph 图也可作为 Runnable 使用,输入输出由图的 Schema 与调用方式决定。
统一执行接口不代表数据类型相同,能连接的组件也可能在运行时遇到数据不兼容。
1.2 查看输入输出结构
可通过 Schema 查看输入输出约定,类型标注有助于推断:
python
from langchain_core.runnables import RunnableLambda
def add_one(value: int) -> int:
return value + 1
step = RunnableLambda(add_one)
print(step.input_schema.model_json_schema())
print(step.output_schema.model_json_schema())
print(step.invoke(2)) # 3
Schema 精度取决于类型信息,不等于自动执行 Pydantic 校验。业务必填、范围和权限仍需明确检查。
二、单次、异步与批量执行
2.1 组合后的链沿用相同接口
python
from langchain.chat_models import init_chat_model
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
prompt = ChatPromptTemplate.from_template("用一句话解释{topic}。")
model = init_chat_model("openai:gpt-4o-mini", temperature=0)
parser = StrOutputParser()
chain = prompt | model | parser
print(chain.invoke({"topic": "递归"}))
results = chain.batch(
[{"topic": "栈"}, {"topic": "队列"}],
config={"max_concurrency": 2},
)
print(results)
invoke() 处理单个输入,batch() 按输入位置返回独立结果,不合并对话,也不自动等于厂商的离线 Batch API。

2.2 异步调用需要 await
python
import asyncio
async def run_async():
answer = await chain.ainvoke({"topic": "哈希表"})
answers = await chain.abatch(
[{"topic": "树"}, {"topic": "图"}],
config={"max_concurrency": 2},
)
print(answer)
print(answers)
if __name__ == "__main__":
asyncio.run(run_async())
异步方法需 await 才取得结果。已有事件循环的 Notebook 可直接 await run_async()。
默认批量使用并发,组件可覆盖实现;异步也可能通过线程执行同步方法。流式分块能力取决于链中组件,留待后续章节展开。
三、LCEL 怎样描述组合关系
3.1 声明数据流,而不是另写执行循环
LCEL 是 LangChain Expression Language,用表达式组合组件。prompt | model | parser 依次构造提示词、调用模型、解析响应。

组合结果保留统一调用接口与配置透传。并行和条件依赖需显式声明,不会自动推断。
3.2 LCEL 与 LangGraph 的分工
LCEL 适合摘要、抽取、并行整理等输入输出明确的步骤,也支持条件选择和局部重试。
跨节点状态、循环协作、持久化恢复或人工介入可用 LangGraph 编排,节点内仍可使用 LCEL。
四、RunnableSequence 与管道操作符
4.1 上一步输出就是下一步输入
管道符 | 通过 Python 运算符重载构造顺序组合,下面两种写法等价:
python
from langchain_core.runnables import RunnableSequence
# 沿用前面定义的 prompt、model、parser
upper_chain = prompt | model | parser | str.upper
explicit_chain = RunnableSequence(prompt, model, parser, str.upper)
print(upper_chain.invoke({"topic": "Python"}))
str.upper 接收解析后的字符串。顺序链只传递上一步输出,早期输入不会自动保留,下游需要原字段时须显式组装。
4.2 自动包装发生在组合上下文中
LCEL 可以把可调用对象包装为 RunnableLambda,把管道中的分支字典包装为 RunnableParallel。下面只执行本地函数:
python
from langchain_core.runnables import RunnableLambda
prepare = RunnableLambda(lambda text: {"text": text.strip()})
inspect = prepare | {
"original": lambda data: data["text"],
"length": lambda data: len(data["text"]),
}
print(inspect.invoke(" hello "))
# {'original': 'hello', 'length': 5}
字典只在组合上下文中包装为并行结构,两个普通函数之间的 | 也不是 LCEL,必要时显式包装。
自动包装不转换业务数据。上游返回字符串、下游却按字典取键,仍会报错。
五、RunnableParallel 并行执行
5.1 同一输入分发给多个分支
RunnableParallel 将同一份输入交给各分支,最终按分支名称收集结果。下面分别生成同一项技术的优点与缺点:
python
from langchain_core.runnables import RunnableParallel
pros = (
ChatPromptTemplate.from_template("给出{tech}的一个核心优点。")
| model | parser
)
cons = (
ChatPromptTemplate.from_template("给出{tech}的一个主要缺点。")
| model | parser
)
compare = RunnableParallel(pros=pros, cons=cons)
result = compare.invoke({"tech": "微服务架构"})
print(result["pros"])
print(result["cons"])

两分支都读原输入,cons 不读取 pros 的结果;有依赖时应分步执行。
5.2 并行与批量不是同一层关系
并行是一个输入运行多个分支,批量是多个输入运行整条链。两个输入各运行优缺点分支,就可能调用模型四次。
并行可缩短独立 I/O 等待,但受调度、限流与资源竞争影响。不要精确等同于最慢分支耗时,也应避免分支修改共享输入。
默认分支异常会使并行调用失败;需要局部兜底时应单独配置。
六、RunnablePassthrough 与 assign
6.1 原样保留输入
RunnablePassthrough() 返回收到的输入,常用于在并行结构中保留原始问题:
python
from langchain_core.runnables import RunnablePassthrough
keep_input = RunnableParallel(
question=RunnablePassthrough(),
length=lambda question: len(question),
)
print(keep_input.invoke("什么是 LCEL?"))
这里 question 得到原字符串;输入若是字典,透传的也是整个字典,不会自动取键。
6.2 assign 在字典上补充字段
python
def lookup_context(data: dict) -> str:
return "LCEL 用于组合 Runnable,支持顺序与并行执行。"
enrich = RunnablePassthrough.assign(context=lookup_context)
result = enrich.invoke({"question": "什么是 LCEL?"})
print(result["question"])
print(result["context"])
assign() 只接收字典,保留旧字段,再合并计算结果,同名键会覆盖。

6.3 新字段有依赖时分两步计算
同一次 assign() 中各字段基于本次输入计算,不按书写顺序共享刚生成的新字段。需要读取 context 时,应再接一次 assign:
python
with_length = (
RunnablePassthrough.assign(context=lookup_context)
| RunnablePassthrough.assign(
context_length=lambda data: len(data["context"])
)
)
print(with_length.invoke({"question": "解释 LCEL。"}))
第一步生成 context,第二步再读取。同一次 assign 的新字段不能按书写顺序相互依赖。
七、RunnableLambda 与条件路由
7.1 把业务函数接入执行链
RunnableLambda 将同步或异步可调用对象包装为 Runnable,适合清洗输入、整理字段和处理结果。多个业务值可以放进一个字典,函数内再读取:
python
def clean_input(text: str) -> dict:
value = text.strip()
if not value:
raise ValueError("问题不能为空")
return {"query": value}
clean = RunnableLambda(clean_input)
print(clean.invoke(" 解释 Python 装饰器 "))
业务数据作为一个输入对象传入,函数还可声明受支持的配置或回调参数。异步函数用 async def 定义,配合 ainvoke()。
阻塞 I/O 不会自动变成原生异步,RunnableLambda 也不默认逐块透传,分块处理需选择合适的流式组件。
7.2 RunnableBranch 选择第一个匹配分支
python
from langchain_core.runnables import RunnableBranch
math_step = RunnableLambda(lambda d: f"数学分支:{d['query']}")
code_step = RunnableLambda(lambda d: f"代码分支:{d['query']}")
default_step = RunnableLambda(lambda d: f"通用分支:{d['query']}")
router = RunnableBranch(
(lambda d: "计算" in d["query"], math_step),
(lambda d: "python" in d["query"].lower(), code_step),
default_step,
)
routed_chain = clean | router
print(routed_chain.invoke("请帮我计算 12 + 35"))
print(routed_chain.invoke("解释 Python 闭包"))
按条件顺序只执行第一个匹配分支,否则执行默认分支,与并行不同。
同时包含计算与 Python 时先走数学分支。示例只路由,不执行算式计算。

7.3 也可以在函数中返回子链
python
def choose_step(data: dict):
if "计算" in data["query"]:
return math_step
if "python" in data["query"].lower():
return code_step
return default_step
function_router = clean | RunnableLambda(choose_step)
print(function_router.invoke("解释 Python 列表"))
函数返回 Runnable 时,框架继续用当前输入执行它。简单条件可用 if,固定映射可用 RunnableBranch。
各分支须返回适合下游的类型,不能让某个分支意外改变结构。
八、RunnableConfig 与运行配置
8.1 配置与业务输入分开传递
业务输入描述要处理什么,RunnableConfig 描述怎样运行和追踪。常见配置有 run_name、tags、metadata、callbacks、max_concurrency 与 configurable。
python
from langchain_core.runnables import RunnableConfig
def inspect_config(data: dict, config: RunnableConfig) -> dict:
return {
"text": data["text"],
"request_id": config.get("metadata", {}).get("request_id"),
"tags": config.get("tags", []),
}
inspect_step = RunnableLambda(inspect_config)
result = inspect_step.invoke(
{"text": "测试请求"},
config={
"run_name": "InspectRequest",
"tags": ["tutorial", "lcel"],
"metadata": {"request_id": "req_9527"},
},
)
print(result)
声明 config 参数可接收配置。metadata 用于追踪,不自动进入提示词,模型需要的事实仍须放入业务输入。

8.2 透传不等于所有字段都全局生效
子调用会继承或合并标签、元数据等配置,并建立回调关系;run_name 命名当前运行,不强制统一子步骤名称。
max_concurrency 作用于支持它的执行路径,不是全局限流器。外层批量与内层并行叠加时,应一起评估请求数。
configurable 只修改明确开放的字段。RunnableConfig 没有通用 timeout,模型超时应在集成中设置。
内部调用子链时可显式传入 config=config,避免跨执行上下文丢失配置。租户标识不能替代鉴权。
九、Retry、Fallback 与异常处理
9.1 with_retry 重试当前组件
重试适合暂时性故障,例如短暂连接失败。下面用本地函数模拟前两次失败,第三次成功,不会调用真实接口:
python
def make_unstable_service():
attempts = 0
def request(query: str) -> str:
nonlocal attempts
attempts += 1
if attempts < 3:
raise ConnectionError("模拟连接失败")
return f"第 {attempts} 次成功:{query}"
return RunnableLambda(request)
reliable = make_unstable_service().with_retry(
retry_if_exception_type=(ConnectionError,),
stop_after_attempt=3,
wait_exponential_jitter=True,
)
print(reliable.invoke("查询订单状态"))
stop_after_attempt=3 包含首次调用。退避抖动分散重试时间,不保证恢复;计数器仅用于本地演示。
只重试可能恢复的错误,并缩小范围。缺字段、无效凭证或业务拒绝通常不会因重试改善;只需重试模型时,不应重跑前序操作。
9.2 with_fallbacks 切换备用方案
python
def unavailable(query: str) -> str:
raise ConnectionError("模拟主服务不可用")
primary = RunnableLambda(unavailable)
backup = RunnableLambda(lambda query: "服务暂不可用,请稍后重试。")
service = primary.with_fallbacks(
[backup], exceptions_to_handle=(ConnectionError,)
)
print(service.invoke("查询订单状态"))
Fallback 按顺序尝试备用组件,不会识别正常返回但内容错误的回答。主备须接受兼容输入、返回兼容输出。
备用模型不支持原有工具或结构化协议时,应单独构建对应子链。

9.3 注意组合顺序与重复执行
primary.with_retry(...).with_fallbacks([backup]) 表示先重试主组件,耗尽后再尝试备用方案。若把重试包在整个主备组合外面,失败时可能重新执行整组流程,行为并不相同。
SDK 与 Runnable 的重试可能叠加,应统一控制总请求预算。
有写入等副作用时需保证幂等性,后续失败不应无条件重做成功步骤。流式已输出部分内容后的恢复需另行设计。
十、组合实践:带参考材料的问答链
10.1 先确定每一步的数据结构
问题字符串经清理变成 question 字典,assign 加入 context,再分别生成 answer、保留 source_context。
本地关键词查找只演示组合,不涉及向量检索。退款、发票内容均为虚构规则。

10.2 完整运行代码
python
from openai import APIConnectionError, RateLimitError, InternalServerError
from langchain.chat_models import init_chat_model
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnableLambda, RunnablePassthrough
def prepare(question: str) -> dict:
question = question.strip()
if not question:
raise ValueError("问题不能为空")
return {"question": question}
def lookup(data: dict) -> str:
rules = {
"退款": "示例规则:已发货订单需提交售后申请,由客服审核。",
"发票": "示例规则:订单完成后,可在个人中心提交开票申请。",
}
for keyword, content in rules.items():
if keyword in data["question"]:
return content
return "没有匹配到参考材料。"
prompt = ChatPromptTemplate.from_messages([
("system", "只根据参考材料回答,不添加未提供的政策。"
"资料不足时说明无法确认。\n参考材料:{context}"),
("human", "{question}"),
])
errors = (APIConnectionError, RateLimitError, InternalServerError)
model = init_chat_model(
"openai:gpt-4o-mini", temperature=0, timeout=20, max_retries=0
)
retry_model = model.with_retry(
retry_if_exception_type=errors,
stop_after_attempt=2,
wait_exponential_jitter=True,
)
answer = prompt | retry_model | StrOutputParser()
backup = RunnableLambda(
lambda data: "模型服务暂不可用,请稍后重试或联系人工。"
)
safe = answer.with_fallbacks(
[backup], exceptions_to_handle=errors
)
chain = (
RunnableLambda(prepare)
| RunnablePassthrough.assign(context=lookup)
| {
"answer": safe,
"source_context": lambda data: data["context"],
}
)
result = chain.invoke(
" 已经发货的订单怎么申请退款? ",
config={
"run_name": "QA",
"tags": ["tutorial", "support"],
"metadata": {"request_id": "req_001"},
},
)
print("参考材料:", result["source_context"])
print("回答:", result["answer"])
max_retries=0 关闭 SDK 重试,外层最多尝试两次。只处理列出的暂时性 API 异常,不把所有错误改成兜底文案。
主备都接收 question、context 字典并返回字符串。模型单独重试,耗尽后由回答链外的兜底接管,不重复清理与材料查找。
10.3 观察正常路径与失败路径
正常路径依次清理问题、找到材料、生成回答。answer 来自模型,source_context 来自本地材料。
指定暂时性异常重试耗尽后,answer 明确提示服务不可用,source_context 仍可保留,不能把兜底当成正常生成。
空字符串在 prepare 阶段抛出 ValueError,不进入模型兜底。模型正常返回但质量不佳,也不会自动触发 Fallback,需另做业务检查。