跳到主要內容
Open In ColabOpen on GitHub

如何串聯可執行物件

先決條件

關於 LangChain 運算式語言 的一點是,任何兩個可執行物件都可以「串聯」成序列。先前可執行物件的 .invoke() 呼叫的輸出會作為下一個可執行物件的輸入傳遞。這可以使用管道運算符 (|),或更明確的 .pipe() 方法來完成,兩者執行相同的操作。

產生的 RunnableSequence 本身就是一個可執行物件,這表示它可以像任何其他可執行物件一樣被調用、串流或進一步串聯。以這種方式串聯可執行物件的優點是高效的串流(序列將在輸出可用時立即串流輸出),以及使用 LangSmith 等工具進行偵錯和追蹤。

管道運算符:|

為了展示其運作方式,讓我們來看一個範例。我們將逐步介紹 LangChain 中的常見模式:使用 提示範本 將輸入格式化為 聊天模型,最後使用 輸出解析器 將聊天訊息輸出轉換為字串。

pip install -qU "langchain[openai]"
import getpass
import os

if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ")

from langchain.chat_models import init_chat_model

model = init_chat_model("gpt-4o-mini", model_provider="openai")
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_template("tell me a joke about {topic}")

chain = prompt | model | StrOutputParser()

提示和模型都是可執行物件,並且來自提示調用的輸出類型與聊天模型的輸入類型相同,因此我們可以將它們串聯在一起。然後,我們可以像任何其他可執行物件一樣調用產生的序列

chain.invoke({"topic": "bears"})
"Here's a bear joke for you:\n\nWhy did the bear dissolve in water?\nBecause it was a polar bear!"

強制轉換

我們甚至可以將此鏈與更多可執行物件組合以建立另一個鏈。這可能涉及使用其他類型的可執行物件進行一些輸入/輸出格式化,具體取決於鏈組件所需的輸入和輸出。

例如,假設我們想要將笑話生成鏈與另一個評估生成的笑話是否有趣的鏈組合。

我們需要小心如何格式化下一個鏈的輸入。在下面的範例中,鏈中的字典會自動解析並轉換為 RunnableParallel,它會平行執行其所有值,並返回包含結果的字典。

這恰好是下一個提示範本期望的相同格式。以下是它的實際運作

from langchain_core.output_parsers import StrOutputParser

analysis_prompt = ChatPromptTemplate.from_template("is this a funny joke? {joke}")

composed_chain = {"joke": chain} | analysis_prompt | model | StrOutputParser()

composed_chain.invoke({"topic": "bears"})
API 參考:StrOutputParser
'Haha, that\'s a clever play on words! Using "polar" to imply the bear dissolved or became polar/polarized when put in water. Not the most hilarious joke ever, but it has a cute, groan-worthy pun that makes it mildly amusing. I appreciate a good pun or wordplay joke.'

函數也會被強制轉換為可執行物件,因此您也可以將自訂邏輯添加到您的鏈中。下面的鏈產生與之前相同的邏輯流程

composed_chain_with_lambda = (
chain
| (lambda input: {"joke": input})
| analysis_prompt
| model
| StrOutputParser()
)

composed_chain_with_lambda.invoke({"topic": "beets"})
"Haha, that's a cute and punny joke! I like how it plays on the idea of beets blushing or turning red like someone blushing. Food puns can be quite amusing. While not a total knee-slapper, it's a light-hearted, groan-worthy dad joke that would make me chuckle and shake my head. Simple vegetable humor!"

但是,請記住,像這樣使用函數可能會干擾串流等操作。有關更多資訊,請參閱 本節

.pipe() 方法

我們也可以使用 .pipe() 方法組合相同的序列。以下是它的樣子

from langchain_core.runnables import RunnableParallel

composed_chain_with_pipe = (
RunnableParallel({"joke": chain})
.pipe(analysis_prompt)
.pipe(model)
.pipe(StrOutputParser())
)

composed_chain_with_pipe.invoke({"topic": "battlestar galactica"})
API 參考:RunnableParallel
"I cannot reproduce any copyrighted material verbatim, but I can try to analyze the humor in the joke you provided without quoting it directly.\n\nThe joke plays on the idea that the Cylon raiders, who are the antagonists in the Battlestar Galactica universe, failed to locate the human survivors after attacking their home planets (the Twelve Colonies) due to using an outdated and poorly performing operating system (Windows Vista) for their targeting systems.\n\nThe humor stems from the juxtaposition of a futuristic science fiction setting with a relatable real-world frustration – the use of buggy, slow, or unreliable software or technology. It pokes fun at the perceived inadequacies of Windows Vista, which was widely criticized for its performance issues and other problems when it was released.\n\nBy attributing the Cylons' failure to locate the humans to their use of Vista, the joke creates an amusing and unexpected connection between a fictional advanced race of robots and a familiar technological annoyance experienced by many people in the real world.\n\nOverall, the joke relies on incongruity and relatability to generate humor, but without reproducing any copyrighted material directly."

或縮寫形式

composed_chain_with_pipe = RunnableParallel({"joke": chain}).pipe(
analysis_prompt, model, StrOutputParser()
)
  • 串流:查看串流指南以了解鏈的串流行為

此頁面是否有幫助?