Skip to main content
Open In Colab在 GitHub 上打开

从 LLMChain 迁移

LLMChain将提示模板、LLM 和输出解析器合并到一个类中。

切换到 LCEL 实施的一些优点是:

  • 内容和参数清晰。遗产LLMChain包含默认输出解析器和其他选项。
  • 更轻松的流媒体。LLMChain仅支持通过回调进行流式处理。
  • 如果需要,可以更轻松地访问原始消息输出。LLMChainonly 通过 parameter 或 callback 公开这些内容。
%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
API 参考:LLMChain | ChatPromptTemplate 模板 | 聊天OpenAI
{'adjective': 'funny',
'text': "Why couldn't the bicycle stand up by itself?\n\nBecause it was two tired!"}

请注意,LLMChain默认情况下,返回一个dict包含 Importing 和 Output 的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.'

如果您想模仿dict输入和输出的打包LLMChain,您可以使用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 概念文档 了解更多背景信息。