【狂飙全模态】狂飙AGI-智能答疑助手

狂飙AGI-智能答疑助手

      • 一、项目展示
      • 二、环境准备
        • [1 智谱API Key获取](#1 智谱API Key获取)
          • [1.1 登录官网](#1.1 登录官网)
          • [1.2 添加新的API Key](#1.2 添加新的API Key)
          • [1.3 点击复制API Key(备用)](#1.3 点击复制API Key(备用))
        • [2 虚拟环境配置](#2 虚拟环境配置)
          • [2.1 创建虚拟环境](#2.1 创建虚拟环境)
          • [2.2 安装依赖包](#2.2 安装依赖包)
      • 三、代码实现
          • [3.1 导入依赖包](#3.1 导入依赖包)
          • [3.2 设置API Key](#3.2 设置API Key)
          • [3.3 设置Chatbot类](#3.3 设置Chatbot类)
          • [3.4 定义记忆返回函数及记忆清除函数](#3.4 定义记忆返回函数及记忆清除函数)
          • [3.5 Gradio界面构建](#3.5 Gradio界面构建)
          • [3.6 项目完整代码](#3.6 项目完整代码)
      • 四、效果演示

一、项目展示

二、环境准备

1 智谱API Key获取
1.1 登录官网

官网网址https://bigmodel.cn/

1.2 添加新的API Key
1.3 点击复制API Key(备用)
2 虚拟环境配置
2.1 创建虚拟环境
shell 复制代码
conda create -n KBAGI python=3.10
2.2 安装依赖包
bash 复制代码
pip install openai gradio

三、代码实现

3.1 导入依赖包
python 复制代码
import gradio as gr
from openai import OpenAI
3.2 设置API Key
python 复制代码
Zhipu_API_KEY="XXXXXXXXXX【替换为1.3复制的API Key】XXXXXXXXXXXXXX"
Zhipu_base_url="https://open.bigmodel.cn/api/paas/v4/"
3.3 设置Chatbot类
python 复制代码
class ChatBot:
    def __init__(self):
        self.client = OpenAI(
            api_key=Zhipu_API_KEY,
            base_url=Zhipu_base_url
        )
        self.conversation = [
            {"role": "system", "content": "你是一个有用的AI助手"}
        ]

    def chat(self, user_input: str) -> str:
        # 添加用户消息
        self.conversation.append({"role": "user", "content": user_input})

        # 调用API
        response = self.client.chat.completions.create(
            model="glm-4-air-250414",
            messages=self.conversation,
            temperature=0.7
        )

        # 获取AI回复
        ai_response = response.choices[0].message.content

        # 添加到对话历史
        self.conversation.append({"role": "assistant", "content": ai_response})

        return ai_response

    def clear_history(self):
        """清除对话历史,保留系统提示"""
        self.conversation = self.conversation[:1]

# 创建全局聊天机器人实例
bot = ChatBot()
3.4 定义记忆返回函数及记忆清除函数
python 复制代码
def respond(message, history):
    """
    处理用户输入并返回AI回复
    """
    try:
        response = bot.chat(message)
        # 将新消息添加到历史记录中
        history.append({"role": "user", "content": message})
        history.append({"role": "assistant", "content": response})
        return history
    except Exception as e:
        error_msg = f"抱歉,我遇到了一个错误: {str(e)}"
        history.append({"role": "user", "content": message})
        history.append({"role": "assistant", "content": error_msg})
        return history

def clear_chat_history():
    """
    清除聊天历史
    """
    bot.clear_history()
    return []
3.5 Gradio界面构建
python 复制代码
with gr.Blocks(title="狂飙AGI-智能答疑助手") as demo:
    gr.Markdown("# 🤖狂飙AGI-智能答疑助手")
    gr.Markdown("您的专属AI学习助手,可以回答各种问题")
    
    # 聊天界面
    chatbot = gr.Chatbot(
        label="聊天室",
        height=500,
        type="messages"
    )
    
    # 输入组件
    with gr.Row():
        msg = gr.Textbox(
            label="输入您的问题",
            placeholder="例如:什么是人工智能?",
            container=False,
            scale=9
        )
        clear_btn = gr.Button("清除历史", scale=1)
    
    # 提交按钮
    submit_btn = gr.Button("发送", variant="primary")
    
    # 绑定事件
    # 当用户按下回车或点击发送按钮时提交
    msg.submit(respond, [msg, chatbot], [chatbot]).then(
        lambda: "", None, msg, queue=False
    )
    submit_btn.click(respond, [msg, chatbot], [chatbot]).then(
        lambda: "", None, msg, queue=False
    )
    
    # 清除历史按钮
    clear_btn.click(clear_chat_history, None, chatbot, queue=False)

if __name__ == "__main__":
    demo.launch()
3.6 项目完整代码
python 复制代码
import gradio as gr
from openai import OpenAI

Zhipu_API_KEY="XXXXXXXXXX【替换为1.3复制的API Key】XXXXXXXXXXXXXX"
Zhipu_base_url="https://open.bigmodel.cn/api/paas/v4/"

class ChatBot:
    def __init__(self):
        self.client = OpenAI(
            api_key=Zhipu_API_KEY,
            base_url=Zhipu_base_url
        )
        self.conversation = [
            {"role": "system", "content": "你是一个有用的AI助手"}
        ]

    def chat(self, user_input: str) -> str:
        # 添加用户消息
        self.conversation.append({"role": "user", "content": user_input})

        # 调用API
        response = self.client.chat.completions.create(
            model="glm-4-air-250414",
            messages=self.conversation,
            temperature=0.7
        )

        # 获取AI回复
        ai_response = response.choices[0].message.content

        # 添加到对话历史
        self.conversation.append({"role": "assistant", "content": ai_response})

        return ai_response

    def clear_history(self):
        """清除对话历史,保留系统提示"""
        self.conversation = self.conversation[:1]

# 创建全局聊天机器人实例
bot = ChatBot()

def respond(message, history):
    """
    处理用户输入并返回AI回复
    """
    try:
        response = bot.chat(message)
        # 将新消息添加到历史记录中
        history.append({"role": "user", "content": message})
        history.append({"role": "assistant", "content": response})
        return history
    except Exception as e:
        error_msg = f"抱歉,我遇到了一个错误: {str(e)}"
        history.append({"role": "user", "content": message})
        history.append({"role": "assistant", "content": error_msg})
        return history

def clear_chat_history():
    """
    清除聊天历史
    """
    bot.clear_history()
    return []

with gr.Blocks(title="狂飙AGI-智能答疑助手") as demo:
    gr.Markdown("# 🤖狂飙AGI-智能答疑助手")
    gr.Markdown("您的专属AI学习助手,可以回答各种问题")
    
    # 聊天界面
    chatbot = gr.Chatbot(
        label="聊天室",
        height=500,
        type="messages"
    )
    
    # 输入组件
    with gr.Row():
        msg = gr.Textbox(
            label="输入您的问题",
            placeholder="例如:什么是人工智能?",
            container=False,
            scale=9
        )
        clear_btn = gr.Button("清除历史", scale=1)
    
    # 提交按钮
    submit_btn = gr.Button("发送", variant="primary")
    
    # 绑定事件
    # 当用户按下回车或点击发送按钮时提交
    msg.submit(respond, [msg, chatbot], [chatbot]).then(
        lambda: "", None, msg, queue=False
    )
    submit_btn.click(respond, [msg, chatbot], [chatbot]).then(
        lambda: "", None, msg, queue=False
    )
    
    # 清除历史按钮
    clear_btn.click(clear_chat_history, None, chatbot, queue=False)

if __name__ == "__main__":
    demo.launch(server_name="127.0.0.1", server_port=7860)

四、效果演示

相关推荐
tap.AI6 分钟前
RAG系列(二)数据准备与向量索引
开发语言·人工智能
老蒋新思维1 小时前
知识IP的长期主义:当AI成为跨越增长曲线的“第二曲线引擎”|创客匠人
大数据·人工智能·tcp/ip·机器学习·创始人ip·创客匠人·知识变现
货拉拉技术1 小时前
出海技术挑战——Lalamove智能告警降噪
人工智能·后端·监控
wei20231 小时前
汽车智能体Agent:国务院“人工智能+”行动意见 对汽车智能体领域 革命性重塑
人工智能·汽车·agent·智能体
QQ14220784491 小时前
没有这个数据库账户,难道受到了sql注入式攻击?
数据库·sql
LinkTime_Cloud1 小时前
快手遭遇T0级“黑色闪电”:一场教科书式的“协同打击”,披上了AI“智能外衣”的攻击
人工智能
PPIO派欧云1 小时前
PPIO上线MiniMax-M2.1:聚焦多语言编程与真实世界复杂任务
人工智能
隔壁阿布都1 小时前
使用LangChain4j +Springboot 实现大模型与向量化数据库协同回答
人工智能·spring boot·后端
残 风1 小时前
pg兼容mysql框架之语法解析层(openHalo开源项目解析)
数据库·mysql·开源
勇往直前plus2 小时前
MyBatis/MyBatis-Plus类型转换器深度解析:从基础原理到自定义实践
数据库·oracle·mybatis