跳到主要內容
Open In ColabOpen on GitHub

從 LLMChain 遷移

LLMChain 將提示範本、LLM 和輸出解析器組合成一個類別。

切換到 LCEL 實作的一些優點是

  • 內容和參數的清晰度。舊版 LLMChain 包含預設輸出解析器和其他選項。
  • 更輕鬆的串流。LLMChain 僅透過回呼支援串流。
  • 如果需要,更容易存取原始訊息輸出。LLMChain 僅透過參數或透過回呼公開這些輸出。
%pip install --upgrade --quiet langchain-openai
import os
from getpass import getpass

if "OPENAI_API_KEY" not in os.environ:
os.environ["OPENAI_API_KEY"] = getpass()

舊版

詳細資訊
from langchain.chains import LLMChain
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI

prompt = ChatPromptTemplate.from_messages(
[("user", "Tell me a {adjective} joke")],
)

legacy_chain = LLMChain(llm=ChatOpenAI(), prompt=prompt)

legacy_result = legacy_chain({"adjective": "funny"})
legacy_result
{'adjective': 'funny',
'text': "Why couldn't the bicycle stand up by itself?\n\nBecause it was two tired!"}

請注意,LLMChain 預設返回一個 dict,其中包含來自 StrOutputParser 的輸入和輸出,因此要提取輸出,您需要存取 "text" 鍵。

legacy_result["text"]
"Why couldn't the bicycle stand up by itself?\n\nBecause it was two tired!"

LCEL

詳細資訊
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI

prompt = ChatPromptTemplate.from_messages(
[("user", "Tell me a {adjective} joke")],
)

chain = prompt | ChatOpenAI() | StrOutputParser()

chain.invoke({"adjective": "funny"})
'Why was the math book sad?\n\nBecause it had too many problems.'

如果您想模擬 LLMChain 中輸入和輸出的 dict 包裝,您可以使用 RunnablePassthrough.assign,例如

from langchain_core.runnables import RunnablePassthrough

outer_chain = RunnablePassthrough().assign(text=chain)

outer_chain.invoke({"adjective": "funny"})
API 參考:RunnablePassthrough
{'adjective': 'funny',
'text': 'Why did the scarecrow win an award? Because he was outstanding in his field!'}

下一步

請參閱 本教學,以取得有關使用提示範本、LLM 和輸出解析器建構的更多詳細資訊。

查看 LCEL 概念文件,以取得更多背景資訊。


此頁面是否有幫助?