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!'}

后续步骤

请参阅此教程,了解有关使用 prompt 模板、LLM 和输出解析器的更多详细信息。

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