从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 默认返回一个包含 StrOutputParser 的输入和输出的 dict,因此要提取输出,您需要访问 "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 概念文档。