使用 Gradio 开发 ChatBot

Gradio 提供了 ChatInterface 组件,组件包括一个输入框、一个 ChatBox 区域、和一些按钮。同 interface,ChatInterface 通过一个处理函数进行处理,处理函数包括两个参数 message 和 history,message 是当前用户提交的问题,history 是历史聊天记录。
在这里插入图片描述

简单启动输入返回字符串

import gradio as gr

def random_response (message, history):
    return "abcd"


demo = gr.ChatInterface(random_response, title="Qwen2")


demo.launch()

在这里插入图片描述
接入模型,这里使用 LangChain,可以使用任意方式接入模型。

from langchain_community.llms.tongyi import Tongyi
from langchain_community.chat_models import ChatTongyi
import gradio as gr
import json
from dotenv import load_dotenv
import time
load_dotenv()
from langchain.schema import (
    HumanMessage,AIMessage
)


model = ChatTongyi(model_name="llama3.1-70b-instruct")


def random_response (message, history):
    history_langchain_format = []
    for human, ai in history:
        history_langchain_format.append(HumanMessage(content=human))
        history_langchain_format.append(AIMessage(content=ai))
    history_langchain_format.append(HumanMessage(content=message))
    print(history_langchain_format)
    partial_message = ""
    for chunk in model.stream(history_langchain_format):
        time.sleep(0.05)
        partial_message = partial_message +  chunk.content
        yield partial_message
    



demo = gr.ChatInterface(random_response, title="Qwen2")


demo.launch()

启动并测试

在这里插入图片描述

总结

Gradio 接入模型也是比简单的,和 Python 其他的库集成也很容易,上手很快。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值