基于网页的大语言模型聊天机器人

代码功能

用户交互界面:

包括聊天历史显示区域和输入框,用户可以输入消息并发送。

消息发送和显示:

用户输入消息后点击"Send"按钮或按下回车键即可发送。

消息发送后显示在聊天记录中,并通过异步请求与后端 AI 模型通信,获取回复。

对话历史存储与管理:

聊天记录保存在 conversationHistory 数组中,用于构建上下文与后端交互。

清空对话功能:

点击"Clear"按钮后,清空页面上的聊天记录以及存储的对话历史。

样式与美观:

通过 CSS 美化了聊天界面,包括消息显示、按钮样式及自动滚动功能。

代码

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Chatbot</title>
    <style>
        /* General body styling */
        body {
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }

        /* Chat container styling */
        .chat-container {
            width: 40%;
            background-color: #ffffff;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            border-radius: 8px;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        /* Header styling */
        .chat-header {
            background-color: #4CAF50;
            color: white;
            padding: 10px;
            text-align: center;
        }

        /* Chat history area */
        .chat-history {
            flex-grow: 1;
            padding: 15px;
            overflow-y: auto;
            background-color: #f9f9f9;
        }

        /* Message styling */
        .message {
            margin-bottom: 10px;
        }

        .message.user {
            text-align: right;
            color: #333;
        }

        .message.assistant {
            text-align: left;
            color: #4CAF50;
        }

        /* Input area styling */
        .chat-input {
            display: flex;
            border-top: 1px solid #ddd;
            padding: 10px;
            background-color: #fff;
        }

        .chat-input input {
            flex-grow: 1;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 10px;
            font-size: 14px;
            outline: none;
        }

        .chat-input button {
            margin-left: 10px;
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            font-size: 14px;
            cursor: pointer;
        }

        #send-button {
            background-color: #4CAF50;
            color: white;
        }

        #clear-button {
            background-color: #f44336;
            color: white;
        }

        #send-button:hover {
            background-color: #45a049;
        }

        #clear-button:hover {
            background-color: #e57373;
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <div class="chat-header">
            <h1>AI Chatbot</h1>
        </div>
        <div id="chat-history" class="chat-history"></div>
        <div class="chat-input">
            <input id="user-input" type="text" placeholder="Type your message..." autocomplete="off">
            <button id="send-button">Send</button>
            <button id="clear-button" class="clear-btn">Clear</button>
        </div>
    </div>
    <script>
        // Select elements
        const chatHistory = document.getElementById('chat-history');
        const userInput = document.getElementById('user-input');
        const sendButton = document.getElementById('send-button');
        const clearButton = document.getElementById('clear-button');

        // Store the conversation history
        const conversationHistory = [];

        // Function to append messages to the chat history
        function appendMessage(role, content) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${role}`;
            messageDiv.textContent = `${role === 'user' ? 'You' : 'AI'}: ${content}`;
            chatHistory.appendChild(messageDiv);
            chatHistory.scrollTop = chatHistory.scrollHeight; // Auto-scroll

            // Add to conversation history
            conversationHistory.push({ role, content });
        }

        // Send message to the server
        async function sendMessage() {
            const message = userInput.value.trim();
            if (message === '') return;

            // Append user message to the chat
            appendMessage('user', message);

            // Clear input field
            userInput.value = '';

            try {
                // Build the message payload including history
                const payload = {
                    model: 'Qwen/Qwen2.5-7B-Instruct',
                    messages: conversationHistory.map(msg => ({
                        role: msg.role === 'user' ? 'user' : 'assistant',
                        content: msg.content
                    }))
                };

                // Send request to the server
                const response = await fetch('https://api.siliconflow.cn/v1/chat/completions', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer sk-boxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxehfvctud'
                    },
                    body: JSON.stringify(payload)
                });

                // Parse the response
                const data = await response.json();
                const assistantMessage = data.choices[0].message.content;

                // Append AI's response to the chat
                appendMessage('assistant', assistantMessage);
            } catch (error) {
                appendMessage('assistant', 'Error: Unable to fetch response.');
                console.error(error);
            }
            // Log the updated conversation history
            // console.log('Current conversation history:', conversationHistory);
        }

        // Clear chat history
        function clearChat() {
            chatHistory.innerHTML = '';
            conversationHistory.length = 0; // Clear history array

            // Log the updated conversation history (should be empty)
            // console.log('Chat cleared. Current conversation history:', conversationHistory);
        }

        // Event listeners
        sendButton.addEventListener('click', sendMessage);
        clearButton.addEventListener('click', clearChat);
        userInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter') sendMessage();
        });
    </script>
</body>
</html>

提醒

需要先在siliconflow上免费注册账户,获得自己的API密钥,并将代码中的sk-boxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxehfvctud替换为自己的API密钥。同时你也可以将代码中的Qwen/Qwen2.5-7B-Instruct替换为自己喜欢的其他模型(siliconflow上有其他可以免费调用的模型)。将上述代码存储到记事本中,将文件后缀修改为.html后,双击即可运行。

相关推荐
只是甲2 小时前
Text2SQL 系列博客 02:技术原理深度剖析 - 从自然语言到 SQL 的完整链路
人工智能·text2sql·nl2sql·ai agent·自助数据分析·data agent·agentic 数据洞察
懷淰メ2 小时前
【AI赋能】基于PyQt+YOLO+DeepSeek水上漂浮物检测系统(详细介绍)
人工智能·yolo·目标检测·计算机视觉·pyqt·漂浮物·水上漂浮物
EQUINOX12 小时前
【论文精读】| CLIP精读
大数据·人工智能
PC2005-cloud2 小时前
博文已索引但不展示:一次 Bing SEO 问题排查记录
服务器·人工智能
weixin_408099672 小时前
2026 图片去文字 API 实战:AI一键去除图片文字(附 Python / Java / PHP / JS 完整代码)
人工智能·api接口·图片去水印·石榴智能·ai图像修复·图片去文字
greenbbLV3 小时前
2026节日慰问品政策解读:合规标准升级与福利行业新趋势
人工智能·节日
奈斯先生Vector3 小时前
告别工具碎片化:基于 Nano Banana 全模态 AI 聚合架构搭建“文本-图像-视频”自动化协同生产线
运维·数据库·人工智能·架构·自动化·aigc·音视频
领麦微红外3 小时前
国产MEMS红外测温传感器:传感器+算法+产品级出厂标定一站式交付模式深度解读
人工智能·硬件工程·产品经理
mingo_敏3 小时前
DeepAgents : 检索(Retrieval)
人工智能·深度学习·langchain
微三云 - 廖会灵 (私域系统开发)3 小时前
消费即资产:积分增值异业联盟商业模式完整拆解(附落地逻辑、合规方案与盈利模型)
大数据·人工智能