Skip to main content
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()

遗留问题

Details
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 返回一个包含输入和来自 StrOutputParser 的输出的 dict,因此要提取输出,您需要访问 "text" 键。

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

LCEL

Details
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 Reference:RunnablePassthrough
{'adjective': 'funny',
'text': 'Why did the scarecrow win an award? Because he was outstanding in his field!'}

下一步

请参阅本教程以获取更多关于使用提示模板、LLMs和输出解析器构建的详细信息。

查看LCEL概念文档以获取更多背景信息。


这个页面有帮助吗?