问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

LangChain入门:用RouterChain实现智能客服问题分类

创作时间:
作者:
@小白创作中心

LangChain入门:用RouterChain实现智能客服问题分类

引用
CSDN
1.
https://blog.csdn.net/wangjiansui/article/details/137510754

在构建智能客服系统时,准确识别并分类用户的问题至关重要。LangChain的RouterChain提供了一种动态选择下一个处理链的机制,根据用户的问题内容,选择最合适的处理模板进行回答。

任务设定

假设我们的鲜花运营智能客服ChatBot需要处理两大类问题:

  • 鲜花养护:如保持花的健康、浇水、施肥等。
  • 鲜花装饰:如搭配花束、装饰场地等。

我们的目标是根据问题类型,将任务分配给相应的ChatBot A或ChatBot B。

整体框架

RouterChain(路由链)能够根据用户问题动态选择下一个链。它首先使用路由器链确定问题更适合哪个处理模板,然后将问题发送到该处理模板进行回答。如果问题不适合任何已定义的处理模板,它会被发送到默认链。

在这个示例中,我们将使用LLMRouterChain和MultiPromptChain组合实现路由功能。MultiPromptChain会调用LLMRouterChain选择与问题最相关的提示,然后使用该提示回答问题。

具体步骤

  1. 构建处理模板:为鲜花护理和鲜花装饰定义两个字符串模板。
  2. 初始化语言模型:导入并实例化语言模型。
  3. 构建目标链:根据模板构建对应的LLMChain,并存储在一个字典中。
  4. 构建LLM路由链:使用提示信息构建路由模板,并创建LLMRouterChain。
  5. 构建默认链:准备一个默认链,用于处理不适合任何处理模板的问题。
  6. 构建多提示链:使用MultiPromptChain整合路由链、目标链和默认链,形成决策系统。

具体实现

  1. 构建提示信息的模板
flower_care_template = "你是一个经验丰富的园丁,擅长解答关于养花育花的问题。下面是需要你来回答的问题: {input}"
flower_deco_template = "你是一位网红插花大师,擅长解答关于鲜花装饰的问题。下面是需要你来回答的问题: {input}"
prompt_infos = [
    {
        "name": "flower_care",
        "description": "适合回答关于鲜花护理的问题",
        "prompt": flower_care_template
    },
    {
        "name": "flower_deco",
        "description": "适合回答关于鲜花装饰的问题",
        "prompt": flower_deco_template
    }
]
  1. 初始化语言模型
from langchain.chat_models import ChatOpenAI
llm = ChatOpenAI(temperature=0)
  1. 构建目标链
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate

chains = {}
for p_info in prompt_infos:
    prompt = PromptTemplate(
        template=p_info["prompt"],
        input_variables=["input"]
    )
    chain = LLMChain(llm=llm, prompt=prompt)
    chains[p_info["name"]] = chain
  1. 构建LLM路由链
from langchain.chains.router.llm_router import LLMRouterChain, RouterOutputParser
from langchain.chains.router.multi_prompt_prompt import MULTI_PROMPT_ROUTER_TEMPLATE

destinations = [f"{p['name']}: {p['description']}" for p in prompt_infos]
destinations_str = "\n".join(destinations)

router_template = MULTI_PROMPT_ROUTER_TEMPLATE.format(destinations=destinations_str)
router_prompt = PromptTemplate(
    template=router_template,
    input_variables=["input"]
)
router_chain = LLMRouterChain.from_llm(llm, router_prompt)
  1. 构建默认链
from langchain.chains import ConversationChain

default_chain = ConversationChain(llm=llm, output_key="text")
  1. 构建多提示链
from langchain.chains.router import MultiPromptChain

chain = MultiPromptChain(
    router_chain=router_chain,
    destination_chains=chains,
    default_chain=default_chain,
    verbose=True
)

测试

现在我们可以测试一下这个系统:

response = chain.run("如何让玫瑰花保持新鲜?")
print(response)

response = chain.run("如何用玫瑰花装饰客厅?")
print(response)

通过以上步骤,我们就完成了一个简单的基于LangChain的智能客服系统,能够根据用户提问的意图,自动选择合适的处理链进行回答。

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号