链的组合:链里套链

🎉摘要:本文讲解 LCEL 中每条链本身就是一个 Runnable,管道运算符两边都接收 Runnable,因此完整链可作为组件嵌入更大的链,实现链里套链。通过翻译与写诗示例,展示用子链结果作为另一条链输入的链嵌套用法,并说明 RunnablePassthrough.assign 的等价写法。

LCEL 中每一条链本身就是一个 Runnable。

管道(|)运算符两边都接收 Runnable,那么一条完整的链,可以直接作为组件,嵌入另一条更大的链里面,也就是链里套链。

这本质不是什么特殊语法,只是 LCEL 统一抽象带来的能力:链 = Runnable,组件 = Runnable,所以链可以当成普通组件使用。  

简单示例:

from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough, RunnableLambda
from langchain_ollama import ChatOllama

# 创建模型
llm = ChatOllama(model="qwen3:4b", temperature=0)

def show(data):
    print(f"翻译后的结果:{data}")
    return data

# 提示词模板
# 翻译
translate = ChatPromptTemplate.from_template("翻译成英文:{q}") | llm | StrOutputParser()
# 写诗
poem = ChatPromptTemplate.from_template("""以下面的英文主题写一句诗。
输出格式:
主题 —— xxx
诗句 —— xxx

主题:{trans}
""") | llm | StrOutputParser()

# 先算出翻译,塞进字典,再调用第二条链
full = ({"trans": translate} | RunnableLambda(show) | poem)
print(full.invoke({"q": "春天的风"}))

# 和上面等价
full = (RunnablePassthrough.assign(trans=translate) | RunnableLambda(show) | poem)
print(full.invoke({"q": "春天的风"}))

运行结果:

翻译后的结果:{'trans': 'spring wind'}
主题 —— spring wind
诗句 —— 春风轻舞万物苏
翻译后的结果:{'q': '春天的风', 'trans': 'spring wind'}
主题 —— spring wind
诗句 —— 春风轻舞万物苏

这种“用子链的结果当另一个链的输入”是 LCEL 最强大的地方。

   

说说我的看法
全部评论()
没有评论