从 LLMChain 迁移
LLMChain 将提示模板、LLM 和输出解析器组合到一个类中。
切换到 LCEL 实现的一些优势包括:
- 内容清晰且参数明确。旧的
LLMChain包含默认的输出解析器和其他选项。 - 更流畅的流式传输。
LLMChain仅支持通过回调进行流式传输。 - 如果 desired,可以更容易地访问原始消息输出。
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 参考:可运行传递器
{'adjective': 'funny',
'text': 'Why did the scarecrow win an award? Because he was outstanding in his field!'}
下一步
有关使用提示模板、LLM 和输出解析器进行构建的更多详细信息,请查看 此教程。
查看 LCEL 概念文档 以获取更多信息。