Langchain表达式语言(LCEL) 多链顺序调用
时间: 2025-05-28 16:51:09 AIGC 浏览: 41
### LangChain LCEL 实现多链顺序调用
LangChain 提供了一种灵活的方式来组合多个链条(Chains),并通过其表达语言(LCEL)实现复杂的逻辑操作。以下是关于如何通过 LangChain 的 `SimpleSequentialChain` 和其他组件来实现多链顺序调用的具体方法。
#### 使用 SimpleSequentialChain 组合两条 Chain
可以通过 `SimpleSequentialChain` 将多个链条按顺序连接起来,从而形成一个多阶段的工作流程。以下是一个具体的代码示例:
```python
from langchain.chains import SimpleSequentialChain, LLMChain
from langchain.prompts import PromptTemplate
from langchain.llms import OpenAI
# 定义第一个 Chain (Synopsis Chain)
synopsis_template = """You are a helpful assistant that generates movie synopses.
Title: {title}
Genre: {genre}
Write a brief synopsis for this movie:"""
synopsis_prompt = PromptTemplate(input_variables=["title", "genre"], template=synopsis_template)
llm = OpenAI(temperature=0.7)
synopsis_chain = LLMChain(llm=llm, prompt=synopsis_prompt)
# 定义第二个 Chain (Review Chain)
review_template = """You are a helpful assistant that writes reviews about movies.
Movie Synopsis:
{movie_synopsis}
Write a short review of this movie."""
review_prompt = PromptTemplate(input_variables=["movie_synopsis"], template=review_template)
review_chain = LLMChain(llm=llm, prompt=review_prompt)
# 创建 Sequential Chain 来串联这两个 Chains
overall_chain = SimpleSequentialChain(chains=[synopsis_chain, review_chain], verbose=True)
# 执行整体 Chain
result = overall_chain.run({"title": "The Matrix", "genre": "Science Fiction"})
print(result)
```
上述代码展示了如何使用 `SimpleSequentialChain` 将两个链条按顺序执行[^1]。首先生成电影简介 (`synopsis_chain`),然后基于该简介撰写评论 (`review_chain`)。
---
#### 利用 Runnable 协议扩展功能
除了 `SimpleSequentialChain`,还可以利用 LangChain 中的 `Runnable` 协议来自定义更复杂的行为。例如,如果需要支持批量处理或流式传输数据,则可以借助 `Runnable` 接口中的 `stream` 或 `batch` 方法[^3]。下面展示一个简单的例子:
```python
from langchain.schema.runnable import RunnableLambda
# 自定义函数作为 Chain 的一部分
def process_input(text):
return f"Processed Input: {text}"
custom_chain = RunnableLambda(process_input)
# 结合之前的 Chains 构建新的 Sequence
complex_chain = synopsis_chain | custom_chain | review_chain
# 调用 Complex Chain 并查看结果
output = complex_chain.invoke({"title": "Inception", "genre": "Thriller"})
print(output)
```
在这个例子中,我们引入了 `RunnableLambda` 来封装自定义函数,并将其与其他链条结合起来,形成了一个新的工作流。
---
#### 声明式的 LangChain 表达语言(LCEL)
对于更加高级的需求,可以直接采用 LangChain 表达语言(LCEL)。它允许开发者以声明的方式描述整个流水线结构,而无需显式编写 Python 代码。这种模式非常适合大规模部署以及动态调整配置场景下的应用开发[^2]。
虽然官方文档尚未提供完整的 LCEL 示例脚本,但可以根据现有 API 文档推测其实现形式如下所示:
```yaml
pipeline:
steps:
- name: generate_synopsis
type: llm_chain
config:
prompt: |
You are an AI writer who creates engaging summaries...
input_vars:
title: string
genre: string
- name: write_review
type: llm_chain
depends_on: [generate_synopsis]
config:
prompt: |
Based on the provided summary, craft a compelling critique...
input_vars:
movie_synopsis: string
```
此 YAML 文件定义了一个两步管道:第一步生成摘要;第二步依据前一步的结果撰写影评。实际运行时会由框架解析这些指令并完成相应任务。
---
阅读全文
相关推荐



















