灵活数据流动:使用LangChain中的RunnablePassthrough在链式任务中传递参数

20 阅读3分钟
# 灵活数据流动:使用LangChain中的RunnablePassthrough在链式任务中传递参数

## 引言

在构建复杂的自动化任务时,灵活地在各个步骤之间传递数据是至关重要的。LangChain提供了一种简便的方法来处理这些需求,那就是`RunnablePassthrough`类。本篇文章将深入介绍如何利用LangChain的`RunnablePassthrough`实现参数在链任务中的传递。

## 主要内容

### 1. LangChain中的基础概念

在深入探讨`RunnablePassthrough`之前,了解以下概念是非常重要的:
- **LangChain表达式语言(LCEL)**:用于定义数据流的表达方式。
- **链式运行(Runnables)**:组合多个步骤以实现复杂任务。
- **并行调用(Calling Runnables in Parallel)**:同时运行多个步骤提高效率。
- **自定义函数(Custom Functions)**:根据需求自定义处理逻辑。

### 2. 使用RunnablePassthrough类

当你在建立链任务时,需要将先前步骤的数据不变地传递到后续步骤中,这时`RunnablePassthrough`便派上用场。它通常与`RunnableParallel`结合使用,以实现数据流的高效传递。

```python
import os
from getpass import getpass
from langchain_core.runnables import RunnableParallel, RunnablePassthrough

# 安装并导入必要的库
os.environ["OPENAI_API_KEY"] = getpass()

runnable = RunnableParallel(
    passed=RunnablePassthrough(),
    modified=lambda x: x["num"] + 1,
)

# 使用API代理服务提高访问稳定性
result = runnable.invoke({"num": 1})
print(result)

运行结果:

{'passed': {'num': 1}, 'modified': 2}

在上述示例中,passed键被RunnablePassthrough调用,因此它简单地传递了{'num': 1}

3. 复杂场景中的数据传递

以下展示了一个更为复杂的实际应用场景,将用户输入格式化为一个合适的提示:

from langchain_community.vectorstores import FAISS
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_openai import ChatOpenAI, OpenAIEmbeddings

vectorstore = FAISS.from_texts(
    ["harrison worked at kensho"], embedding=OpenAIEmbeddings()
)
retriever = vectorstore.as_retriever()

template = """Answer the question based only on the following context:
{context}

Question: {question}
"""
prompt = ChatPromptTemplate.from_template(template)
model = ChatOpenAI()

retrieval_chain = (
    {"context": retriever, "question": RunnablePassthrough()}
    | prompt
    | model
    | StrOutputParser()
)

# 使用API代理服务提高访问稳定性
response = retrieval_chain.invoke("where did harrison work?")
print(response)

输出结果:

'Harrison worked at Kensho.'

在此示例中,RunnablePassthrough帮助将用户的问题传递到提示及模型中,以便生成正确的响应。

常见问题和解决方案

问题1:网络访问不稳定

解决方案:由于某些地区的网络限制,您可能需要使用API代理服务来提高访问的稳定性。

问题2:数据格式不匹配

解决方案:确保在链任务中设定的输入输出格式一致,必要时调整自定义函数来适配数据。

总结和进一步学习资源

RunnablePassthrough在LangChain中为数据跨步骤传递提供了便利。通过这些工具,您可以更高效地利用链任务框架构建复杂的自动化流程。

对于想要更深入了解LangChain及其运行机制的读者,可以参考以下资源:

参考资料

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---