如何將引數從一個步驟傳遞到下一個步驟
先決條件
本指南假設您熟悉以下概念
當使用多個步驟組合鏈時,有時您會希望傳遞先前步驟的資料保持不變,以便在後續步驟中用作輸入。RunnablePassthrough
類別允許您做到這一點,並且通常與 RunnableParallel 結合使用,以將資料傳遞到您建構的鏈中的後續步驟。
請參見以下範例
%pip install -qU langchain langchain-openai
import os
from getpass import getpass
if "OPENAI_API_KEY" not in os.environ:
os.environ["OPENAI_API_KEY"] = getpass()
from langchain_core.runnables import RunnableParallel, RunnablePassthrough
runnable = RunnableParallel(
passed=RunnablePassthrough(),
modified=lambda x: x["num"] + 1,
)
runnable.invoke({"num": 1})
API 參考:RunnableParallel | RunnablePassthrough
{'passed': {'num': 1}, 'modified': 2}
如上所示,使用 RunnablePassthrough()
調用了 passed
鍵,因此它只是簡單地傳遞了 {'num': 1}
。
我們還在映射中設定了第二個鍵 modified
。這使用 lambda 設定單個值,將 1 加到 num,這導致了具有值 2
的 modified
鍵。
檢索範例
在下面的範例中,我們看到一個更真實世界的用例,我們在鏈中使用 RunnablePassthrough
以及 RunnableParallel
來正確格式化提示的輸入
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()
)
retrieval_chain.invoke("where did harrison work?")
API 參考:FAISS | StrOutputParser | ChatPromptTemplate | RunnablePassthrough | ChatOpenAI | OpenAIEmbeddings
'Harrison worked at Kensho.'
這裡提示的輸入預期是一個包含鍵 "context" 和 "question" 的映射。使用者輸入只是問題。因此,我們需要使用我們的檢索器獲取上下文,並在 "question" 鍵下傳遞使用者輸入。RunnablePassthrough
允許我們將使用者的問題傳遞給提示和模型。
下一步
現在您已經學習了如何通過鏈傳遞資料,以幫助格式化流經鏈的資料。
要了解更多資訊,請參閱本節中關於 runnables 的其他操作指南。