我们可以使用 LangChain 中的 RouterChain 来动态引导大模型选择不同的处理链,来回答两类问题。如果后续出现更多种类的问题,只需要按照相同的方法扩展即可。
RouterChain 简介
RouterChain,或称为路由链,能根据给定的输入动态选择最适合的下一个处理链。在这个案例中,首先使用 LLMRouterChain 和 MultiPromptChain 来构建路由功能,再由 LLMRouterChain 自动选择与用户问题最相关的处理模板。
实现步骤
- 构建处理模板:为鲜花护理和装饰分别定义字符串模板。
- 构建提示信息:将两个处理模板组织到提示列表中,供后续选择。
- 初始化语言模型:导入并实例化语言模型。
- 构建目标链:为每个模板构建对应的 LLMChain,并存储到字典中。
- 构建 LLM 路由链:根据提示信息构建路由模板,创建 LLMRouterChain,用于选择最合适的处理链。
- 构建默认链:如果问题不符合已定义的处理模板,使用默认链进行处理。
- 构建多提示链:使用 MultiPromptChain 将 LLM 路由链、目标链和默认链组合起来。
代码实现
- 构建两个场景的模板
flower_care_template = """你是一个经验丰富的园丁,擅长解答关于养花育花的问题。
下面是需要你来回答的问题:
{input}"""
flower_deco_template = """你是一位网红插花大师,擅长解答关于鲜花装饰的问题。
下面是需要你来回答的问题:
{input}"""
prompt_infos = [
{"key": "flower_care", "description": "适合回答关于鲜花护理的问题", "template": flower_care_template},
{"key": "flower_decoration", "description": "适合回答关于鲜花装饰的问题", "template": flower_deco_template}
]
- 初始化语言模型
from langchain.llms import OpenAI
import os
os.environ["OPENAI_API_KEY"] = '你的OpenAI Key'
llm = OpenAI()
- 构建目标链
from langchain.chains.llm import LLMChain
from langchain.prompts import PromptTemplate
chain_map = {}
for info in prompt_infos:
prompt = PromptTemplate(template=info['template'], input_variables=["input"])
chain = LLMChain(llm=llm, prompt=prompt, verbose=True)
chain_map[info["key"]] = chain
- 构建路由链
from langchain.chains.router.llm_router import LLMRouterChain, RouterOutputParser
from langchain.chains.router.multi_prompt_prompt import MULTI_PROMPT_ROUTER_TEMPLATE as RounterTemplate
destinations = [f"{p['key']}: {p['description']}" for p in prompt_infos]
router_template = RounterTemplate.format(destinations="\n".join(destinations))
router_prompt = PromptTemplate(template=router_template, input_variables=["input"], output_parser=RouterOutputParser())
router_chain = LLMRouterChain.from_llm(llm, router_prompt, verbose=True)
- 构建默认链
from langchain.chains import ConversationChain
default_chain = ConversationChain(llm=llm, output_key="text", verbose=True)
- 构建多提示链
from langchain.chains.router import MultiPromptChain
chain = MultiPromptChain(router_chain=router_chain, destination_chains=chain_map, default_chain=default_chain, verbose=True)
- 测试链
print(chain.run("如何为玫瑰浇水?"))
print(chain.run("如何为婚礼场地装饰花朵?"))
print(chain.run("如何考入哈佛大学?"))
总结
LLMRouterChain 和 MultiPromptChain 的组合帮助我们实现了动态路由功能,通过路由链将不同类型的用户问题引导至对应的处理链,解决了鲜花养护和装饰问题的区分处理。每当有新需求时,只需添加新的目标链及其描述即可实现扩展,增强了系统的灵活性。