一.前言

  • 本文章代码基于该系列前文章,如果是0基础小白建议先学习之前文章,至少把python环境配置完成
  • 之前我们调用大模型API,与模型在终端交互,不太美观,之后我们将构建基于网页的web交互,我的打算是先从gradio入手,之后再加入前端三件套,逐渐优化UI。

二.Gradio环境配置

1.grado简介

Gradio 是一个 Python 库,官方界面是:Gradio,用于快速创建机器学习模型的 Web 界面。它的主要特点是:

  • 简单易用:几行代码即可创建界面
  • 实时交互:支持实时预览和流式输出
  • 可分享:生成临时链接,方便分享给他人使用

2.gradio下载

在终端输入以下命令,等待下载即可

pip install gradio

在终端输入:pip show gradio,出现gradio的版本,证明安装成功。

关于gradio的系统讲解,有兴趣的朋友可以学习官方文档,有详细的教程。

三.代码完善

import openai
import gradio as gr#导入gradio的包

openai.api_key = "sk***77"
openai.api_base = "https://api.deepseek.com"


def chat_with_llm(message, history):
    history = history or []
    # 构建完整的对话历史
    prompt = []
    for human, assistant in history:
        # 确保跳过 None 值,并且内容一定是字符串类型
        if human is not None:
            prompt.append({"role": "user", "content": str(human)})
        if assistant is not None:
            prompt.append({"role": "assistant", "content": str(assistant)})
    
    # 添加当前用户消息
    prompt.append({"role": "user", "content": str(message)})
    
    try:
        response = openai.ChatCompletion.create(
            model="deepseek-chat",
            messages=prompt,
            temperature=0.7,
            stream=True
        )

        assistant_response = ""
        for chunk in response:
            if chunk and chunk.choices[0].delta.content:
                assistant_response += chunk.choices[0].delta.content
                yield history + [[message, assistant_response]]

    except Exception as e:
        error_message = f"发生错误: {str(e)}"
        print(error_message)  # 打印错误信息以便调试
        yield history + [[message, error_message]]

# 创建一个支持流式输出的Gradio界面
with gr.Blocks() as demo:
    
    gr.Markdown("# 智能助手")
    
    chatbot = gr.Chatbot(
        height=600,
        show_copy_button=True,
    )
    
    msg = gr.Textbox(
        placeholder="请输入您的问题...",
        container=False
    )
    clear = gr.Button("清空对话")

    def user(user_message, history):
        return "", history + [[user_message, None]]

    def clear_history():
        # 返回一个空的聊天记录列表和一个空的消息框
        return None, []

    # 当用户提交消息时的处理流程
    msg.submit(  # msg.submit 用于处理文本框提交事件
        user,  # 第一步调用 user 函数
        [msg, chatbot],  # 输入参数:消息框和聊天记录
        [msg, chatbot],  # 输出参数:更新后的消息框和聊天记录
        queue=False  # 不进入队列,立即执行
    ).then(  # 链式调用,在 user 函数执行完后
        chat_with_llm,  # 调用 AI 对话函数
        [msg, chatbot],  # 输入参数:消息和聊天记录
        chatbot  # 输出参数:更新聊天记录
    )

    # 当点击清空按钮时的处理
    clear.click(  # clear.click 处理按钮点击事件
        clear_history,  # 调用清空历史记录函数
        None,  # 不需要输入参数
        [msg, chatbot],  # 输出参数:更新消息框和聊天记录
        queue=False  # 不进入队列,立即执行
    )

if __name__ == "__main__":
    demo.launch(share=True)

运行该代码后,出现以下输出:

其中http://127.0.0.1:7862是本地运行网址,我们在浏览器输入这个网址就可以看到一个聊天界面,我们可以输入文问题与我们后端调用的模型进行聊天(支持多轮对话和流式输出)

码字不易,请多多支持~

ps:之后会完善前端代码,并且将历史消息存储到后端知识库,到时候我们就算打通一个全栈的AI应用了~

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐