在构建AI应用时,选择适合的工具和框架至关重要。LLMChain曾是开发AI生成对话的常用选择,但随着需求的变化,LCEL提供了一种更灵活且易于使用的方式。本文将介绍如何从LLMChain迁移到LCEL,并通过代码演示其应用。
技术背景介绍
LLMChain是一个集成了提示模板(Prompt Template)、大型语言模型(LLM)和输出解析器的类,方便开发者快速搭建AI对话系统。然而,它的一些局限性,比如默认的输出解析器和有限的流处理能力,促使开发者考虑更现代更灵活的解决方案——LCEL。
核心原理解析
LCEL通过将提示模板、LLM和输出解析器分离成独立的模块,不仅提供了更大的灵活性,还简化了流处理,允许直接访问原始消息输出。这种模块化设计提高了代码的可读性和可维护性。
代码实现演示
我们将从传统的LLMChain实现开始,然后展示如何迁移到LCEL。
使用LLMChain
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")],
)
chain = LLMChain(llm=ChatOpenAI(), prompt=prompt)
result = chain({"adjective": "funny"})
print(result)
输出:
{
"adjective": "funny",
"text": "Why couldn't the bicycle stand up by itself?\n\nBecause it was two tired!"
}
使用LCEL
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()
result = chain.invoke({"adjective": "funny"})
print(result)
输出:
'Why was the math book sad?\n\nBecause it had too many problems.'
保留输入输出
如果需要像LLMChain一样同时输出输入和结果,可以使用RunnablePassthrough
。
from langchain_core.runnables import RunnablePassthrough
outer_chain = RunnablePassthrough().assign(text=chain)
result = outer_chain.invoke({"adjective": "funny"})
print(result)
输出:
{
"adjective": "funny",
"text": "Why did the scarecrow win an award? Because he was outstanding in his field!"
}
应用场景分析
LCEL的模块化设计特别适合需要灵活调整组件的复杂AI系统,如多轮对话机器人、智能客服系统等。这种设计允许开发者随时更换任意一个模块,而不需对整个系统进行大规模重构。
实践建议
- 灵活使用模块:根据需求选择合适的输出解析器与提示模板。
- 增强代码可读性:利用LCEL的管道风格,保持代码简洁和直观。
- 扩展性:可以方便地通过增加自定义组件来扩展功能。
如果遇到问题欢迎在评论区交流。
—END—