# 在子链之间进行路由的技术指南
## 技术背景介绍
在 AI 应用开发中,路由机制允许我们对复杂的互动进行结构化管理,从而在不同的上下文中使用模型。在 LangChain 表达语言 (LCEL) 中,可以通过路由实现非确定性的链操作,使一个步骤的输出定义下一个步骤的执行路径。本文将介绍两种路由实现方式:使用 `RunnableLambda` 和 `RunnableBranch`。
## 核心原理解析
路由的核心是根据条件选择不同的执行路径。我们可以通过自定义函数来实现动态路由,也可以使用预定义的 `RunnableBranch` 来进行条件判断。在自定义函数方法中,您可以灵活地定义条件和执行的逻辑,而 `RunnableBranch` 提供了一个直观的条件执行结构。
## 代码实现演示
我们将通过示例演示如何创建一个路由系统,识别用户问题并根据问题类型进行路由。
### 设置问题分类链
首先,设置一个链来识别问题是否与 LangChain、Anthropic 或其他相关:
```python
from langchain_anthropic import ChatAnthropic
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import PromptTemplate
chain = (
PromptTemplate.from_template(
"""Given the user question below, classify it as either being about `LangChain`, `Anthropic`, or `Other`.
Do not respond with more than one word.
<question>
{question}
</question>
Classification:"""
)
| ChatAnthropic(model_name="claude-3-haiku-20240307")
| StrOutputParser()
)
chain.invoke({"question": "how do I call Anthropic?"})
创建子链
根据分类结果,创建三个子链:
langchain_chain = PromptTemplate.from_template(
"""You are an expert in langchain. \
Always answer questions starting with "As Harrison Chase told me". \
Respond to the following question:
Question: {question}
Answer:"""
) | ChatAnthropic(model_name="claude-3-haiku-20240307")
anthropic_chain = PromptTemplate.from_template(
"""You are an expert in anthropic. \
Always answer questions starting with "As Dario Amodei told me". \
Respond to the following question:
Question: {question}
Answer:"""
) | ChatAnthropic(model_name="claude-3-haiku-20240307")
general_chain = PromptTemplate.from_template(
"""Respond to the following question:
Question: {question}
Answer:"""
) | ChatAnthropic(model_name="claude-3-haiku-20240307")
使用自定义函数实现路由
推荐使用自定义函数进行路由:
def route(info):
if "anthropic" in info["topic"].lower():
return anthropic_chain
elif "langchain" in info["topic"].lower():
return langchain_chain
else:
return general_chain
from langchain_core.runnables import RunnableLambda
full_chain = {"topic": chain, "question": lambda x: x["question"]} | RunnableLambda(route)
full_chain.invoke({"question": "how do I use Anthropic?"})
应用场景分析
这种路由技术可以用于多种场景,例如:
- 根据用户输入的具体内容动态调整回答风格。
- 针对不同主题使用不同的语言模型或回答策略。
- 在复杂的对话系统中根据上下文进行动态调整。
实践建议
- 使用自定义函数可以灵活的根据不同条件调整执行路径。
- 定义明确的分类标准以确保路由准确。
- 不妨用测试用例验证路由逻辑是否符合预期。
如果遇到问题欢迎在评论区交流。
---END---