使用Gradio搭建聊天UI实现质谱AI智能问答

一、调用智谱 AI API

1、获取api_key

智谱AI开放平台网址:
https://open.bigmodel.cn/overview
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

2、安装库pip install zhipuai
3、执行一下代码,调用质谱api进行问答

from zhipuai import ZhipuAI

client = ZhipuAI(api_key="xxxxx")  # 填写您自己的APIKey
while True:
    prompt = input("user:")
    response = client.chat.completions.create(
        model="glm-4",  # 填写需要调用的模型名称
        messages=[
            {"role": "user", "content": prompt}
        ],
    )
    answer = response.choices[0].message.content
    print("ZhipuAI:", answer)

二、使用Gradio搭建聊天UI

import gradio as gr
import random
import time

from langchain_community.chat_models import ChatZhipuAI
from zhipuai import ZhipuAI

import configure

llm = configure.chat
client = ZhipuAI(api_key="xxx")  # 填写您自己的APIKey

with gr.Blocks() as demo:
    chatbot = gr.Chatbot()
    msg = gr.Textbox()
    clear = gr.Button("清除")


    def respond(message, chat_history):
        response = client.chat.completions.create(
            model="glm-4",  # 填写需要调用的模型名称
            messages=[
                {"role": "user", "content": message}
            ],
        )
        chat_history.append((message, response.choices[0].message.content))
        return "", chat_history


    msg.submit(respond, [msg, chatbot], [msg, chatbot])
    clear.click(lambda: None, None, chatbot, queue=False)

demo.launch()
  • Gradio的Textbox模块允许用户输入字符串并显示字符串输出。它创建一个文本区域,用户可以在其中输入文本或显示输出结果。
  • Button组件是Gradio中的一个模块,用于创建一个按钮,并可以为其分配任意的click()事件。按钮的标签(value)可以作为输入使用,或者通过函数的输出来设置。
  • chatbot模块是Gradio中的一个组件,用于展示聊天机器人的输出,包括用户提交的消息和机器人的回复。它支持一些Markdown语法,包括粗体、斜体、代码和图片等。Chatbot模块的输入不接受用户输入,而是通过函数返回的列表来设置聊天内容。返回的列表应包含多个内部列表,每个内部列表包含两个元素:用户消息和机器人回复。消息可以是字符串、元组或None。如果消息是字符串,可以包含Markdown格式的文本。如果消息是元组,应包含文件路径和可选的替代文本。值为None的消息将不会显示在聊天界面上。

三、将流式处理添加到交互式聊天机器人

import gradio as gr
import time

from zhipuai import ZhipuAI
from typing import *

client = ZhipuAI(api_key="your api key")  # 填写您自己的APIKey
# https://blog.csdn.net/sinat_26917383/article/details/133950480
# https://open.bigmodel.cn/dev/api#glm-4
# https://www.cnblogs.com/ddsuifeng/p/17989484
with gr.Blocks(title="智小优") as demo:
    gr.HTML("""<h1 align="center">智小优</h1>""")
    gr.Markdown("<h1><center>Welcome to my personal AI-OR assistant (powered by zhipu)</center></h1>")

    chatbot = gr.Chatbot(render=True)
    msg = gr.Textbox(placeholder="请输入你的问题")
    with gr.Row():
        submit = gr.Button('Submit')
        clear = gr.Button("Clear")


    def user(user_message: str, history: List[List]) -> Tuple:
        """
        Args:
            user_message: 用户输入
            history: 历史问答
        Returns:
        """
        return "", history + [[user_message, None]]


    def bot(history: List[List]) -> None:
        response = client.chat.completions.create(
            model="glm-4",  # 填写需要调用的模型名称
            messages=[
                {"role": "user", "content": history[-1][0]}
            ],
            stream=True
        )

        history[-1][1] = ""

        for chunk in response:
            for choice in chunk.choices:
                # content = choice.delta.content
                if content := choice.delta.content: 
                    history[-1][1] += content
                    time.sleep(0.05)
                    yield history


    msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
        bot, chatbot, chatbot
    )
    # 触发事件监听
    submit.click(user, [msg, chatbot], [msg, chatbot], queue=False).then(bot, chatbot, chatbot)
    clear.click(lambda: None, None, chatbot, queue=False)

if __name__ == '__main__':
    demo.queue().launch()

参考:

  • https://blog.csdn.net/sinat_26917383/article/details/133950480
  • https://zhuanlan.zhihu.com/p/681207328
  • https://blog.csdn.net/Alexa_/article/details/134485161
  • https://blog.csdn.net/u013558123/article/details/136118024
  • https://zhuanlan.zhihu.com/p/678228971
  • https://open.bigmodel.cn/dev/api#glm-4
  • https://www.cnblogs.com/ddsuifeng/p/17989484
  • 10
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值