langchain RunableBranch 分类判断选择不同链

本文介绍了如何使用Python编程构建一个基于LangChain的模型,该模型可以对用户的问题进行分类(关于LangChain或其他),然后针对不同类别提供相应的详细回答或一般性答案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import os
from dotenv import load_dotenv
from langchain_community.llms import Tongyi
load_dotenv('key.env')  # 指定加载 env 文件
key = os.getenv('DASHSCOPE_API_KEY')  # 获得指定环境变量
DASHSCOPE_API_KEY = os.environ["DASHSCOPE_API_KEY"]  # 获得指定环境变量
model = Tongyi(temperature=1)

from langchain_core.prompts import PromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnableBranch

# 构建分类判断链:识别用户的问题应该属于哪个(指定的)分类
chain = (
        PromptTemplate.from_template(
            """Given the user question below, classify it as either being about `LangChain` or `Other`.
    
    Do not respond with more than one word.
    
    <question>
    {question}
    </question>
    
    Classification:"""
        )
        | model
        | StrOutputParser()
)

# 构建内容问答链和默认应答链
langchain_chain = (
        PromptTemplate.from_template(
            """You are an expert in LangChain. Respond to the following question in one sentence:
    
    Question: {question}
    Answer:"""
        )
        | model
)
general_chain = (
        PromptTemplate.from_template(
            """Respond to the following question in one sentence:
    
    Question: {question}
    Answer:"""
        )
        | model
)

# 通过 RunnableBranch 构建条件分支并附加到主调用链上
branch = RunnableBranch(
    (lambda x: "langchain" in x["topic"].lower(), langchain_chain),
    general_chain,
)
full_chain = {"topic": chain, "question": lambda x: x["question"]} | branch

print(full_chain.invoke({"question": "什么是 LangChain?"}))
print(full_chain.invoke({"question": "1 + 2 = ?"}))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值