跳到正文

科技·工程

我能在不下载任何软件的情况下接上 LLM API 吗?

Misty_Post约 68 分钟
原文
文章信息与版本

文章信息

发布
2026年7月14日
收录
2026年7月15日
更新
2026年11月16日
篇幅
约 68 分钟

版本

  1. v1当前

我们假设现在你已经有了 API。

只需要新建一个 html 文件,把下面代码放进去,用浏览器,填入 API Base URL,API Key 和模型名称即可在本地直接开始对话了!

全程无需任何网站和软件,所有信息只会保存在本地,方便快捷。

HTML
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes, maximum-scale=1.5">
  <title>ChatUI</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
  <style>
    :root {
      --bg-primary: #ffffff;
      --bg-secondary: #f7f7f8;
      --bg-sidebar: #f9fafb;
      --text-primary: #1f2937;
      --text-secondary: #4b5563;
      --border-color: #e5e7eb;
      --user-bubble: #2563eb;
      --user-text: #ffffff;
      --assistant-bubble: #f3f4f6;
      --assistant-text: #111827;
      --input-bg: #ffffff;
      --shadow: 0 2px 6px rgba(0,0,0,0.05);
      --hover-bg: #f3f4f6;
      --accent: #2563eb;
      --danger: #ef4444;
      --success: #10b981;
    }

    body.dark {
      --bg-primary: #1e1e2e;
      --bg-secondary: #2d2d3f;
      --bg-sidebar: #252537;
      --text-primary: #e5e7eb;
      --text-secondary: #9ca3af;
      --border-color: #3f3f5a;
      --user-bubble: #3b82f6;
      --user-text: #ffffff;
      --assistant-bubble: #343454;
      --assistant-text: #f1f5f9;
      --input-bg: #2d2d3f;
      --shadow: 0 4px 12px rgba(0,0,0,0.3);
      --hover-bg: #3f3f5a;
    }

    * { margin: 0; padding: 0; box-sizing: border-box; }

    body {
      font-family: 'Inter', system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
      background: var(--bg-primary);
      color: var(--text-primary);
      height: 100vh;
      display: flex;
      transition: background 0.3s ease, color 0.2s ease;
      overflow: hidden;
    }

    /* 侧边栏 */
    .sidebar {
      width: 280px;
      background: var(--bg-sidebar);
      border-right: 1px solid var(--border-color);
      display: flex;
      flex-direction: column;
      padding: 1.2rem;
      gap: 1rem;
      box-shadow: var(--shadow);
      transition: all 0.3s;
      z-index: 10;
      overflow-y: auto;
    }

    .sidebar h2 {
      font-size: 1.25rem;
      font-weight: 600;
      display: flex;
      align-items: center;
      gap: 0.5rem;
      color: var(--text-primary);
      margin-bottom: 0.2rem;
    }

    .sidebar-section {
      background: var(--bg-primary);
      border-radius: 0.8rem;
      padding: 1rem;
      border: 1px solid var(--border-color);
    }

    .sidebar-section h3 {
      font-size: 0.85rem;
      font-weight: 600;
      color: var(--text-secondary);
      margin-bottom: 0.8rem;
      text-transform: uppercase;
      letter-spacing: 0.5px;
    }

    .setting-group {
      display: flex;
      flex-direction: column;
      gap: 0.4rem;
      margin-bottom: 0.8rem;
    }

    .setting-group label {
      font-size: 0.75rem;
      font-weight: 600;
      text-transform: uppercase;
      letter-spacing: 0.5px;
      color: var(--text-secondary);
    }

    .setting-group input {
      background: var(--input-bg);
      border: 1px solid var(--border-color);
      border-radius: 0.5rem;
      padding: 0.6rem 0.8rem;
      font-size: 0.85rem;
      color: var(--text-primary);
      outline: none;
      transition: border 0.2s, box-shadow 0.2s;
      font-family: inherit;
    }

    .setting-group input:focus {
      border-color: var(--accent);
      box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.2);
    }

    .api-key-wrapper { position: relative; }
    .api-key-wrapper input { width: 100%; padding-right: 2.8rem; }
    .toggle-visibility {
      position: absolute;
      right: 8px;
      top: 50%;
      transform: translateY(-50%);
      background: transparent;
      border: none;
      color: var(--text-secondary);
      cursor: pointer;
      font-size: 0.9rem;
      padding: 0.3rem;
    }

    .btn {
      background: var(--accent);
      color: white;
      border: none;
      border-radius: 0.5rem;
      padding: 0.6rem 0.9rem;
      font-weight: 600;
      font-size: 0.85rem;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 0.4rem;
      transition: background 0.2s, opacity 0.2s;
      width: 100%;
    }
    .btn:hover { opacity: 0.9; }
    .btn-outline {
      background: transparent;
      border: 1px solid var(--border-color);
      color: var(--text-primary);
    }
    .btn-outline:hover { background: var(--hover-bg); }
    .btn-new-chat {
      background: var(--success);
      margin-bottom: 0.5rem;
    }

    .dark-mode-row {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .toggle-switch { position: relative; width: 44px; height: 24px; }
    .toggle-switch input { opacity: 0; width: 0; height: 0; }
    .slider {
      position: absolute;
      cursor: pointer;
      top: 0; left: 0; right: 0; bottom: 0;
      background-color: #ccc;
      border-radius: 34px;
      transition: 0.3s;
    }
    .slider:before {
      position: absolute;
      content: "";
      height: 18px; width: 18px;
      left: 3px; bottom: 3px;
      background-color: white;
      border-radius: 50%;
      transition: 0.3s;
    }
    input:checked + .slider { background-color: var(--accent); }
    input:checked + .slider:before { transform: translateX(20px); }

    /* 主聊天区域 */
    .main {
      flex: 1;
      display: flex;
      flex-direction: column;
      background: var(--bg-primary);
      height: 100vh;
    }

    .chat-header {
      padding: 0.8rem 1.5rem;
      border-bottom: 1px solid var(--border-color);
      font-weight: 600;
      background: var(--bg-secondary);
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .chat-header-left {
      display: flex;
      align-items: center;
      gap: 0.5rem;
    }

    .conversation-title {
      font-size: 0.9rem;
      color: var(--text-secondary);
      max-width: 300px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .chat-messages {
      flex: 1;
      overflow-y: auto;
      padding: 1.2rem 1.5rem;
      display: flex;
      flex-direction: column;
      gap: 1rem;
      scroll-behavior: smooth;
      background: var(--bg-primary);
    }

    .message-row {
      display: flex;
      gap: 0.7rem;
      max-width: 85%;
      animation: fadeIn 0.2s ease;
      position: relative;
    }
    .message-row.user { align-self: flex-end; flex-direction: row-reverse; }
    .message-row.assistant { align-self: flex-start; }

    .message-row:hover .message-actions {
      opacity: 1;
    }

    .message-actions {
      position: absolute;
      top: -8px;
      display: flex;
      gap: 4px;
      opacity: 0;
      transition: opacity 0.2s;
      z-index: 5;
    }
    .message-row.user .message-actions {
      left: -60px;
    }
    .message-row.assistant .message-actions {
      right: -60px;
    }

    .message-action-btn {
      width: 26px;
      height: 26px;
      border-radius: 50%;
      border: 1px solid var(--border-color);
      background: var(--bg-primary);
      color: var(--text-secondary);
      cursor: pointer;
      font-size: 0.7rem;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.2s;
    }
    .message-action-btn:hover {
      background: var(--hover-bg);
      color: var(--accent);
    }

    .avatar {
      width: 30px; height: 30px;
      border-radius: 4px;
      background: var(--border-color);
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 0.9rem;
      color: white;
      flex-shrink: 0;
    }
    .user .avatar { background: var(--user-bubble); }
    .assistant .avatar { background: #10b981; }

    .bubble {
      padding: 0.7rem 0.9rem;
      border-radius: 0.9rem;
      line-height: 1.5;
      word-wrap: break-word;
      white-space: pre-wrap;
      font-size: 0.9rem;
    }
    .user .bubble {
      background: var(--user-bubble);
      color: var(--user-text);
      border-bottom-right-radius: 0.3rem;
    }
    .assistant .bubble {
      background: var(--assistant-bubble);
      color: var(--assistant-text);
      border-bottom-left-radius: 0.3rem;
    }

    .input-area {
      padding: 0.8rem 1.5rem 1rem;
      background: var(--bg-secondary);
      border-top: 1px solid var(--border-color);
      display: flex;
      gap: 0.6rem;
      align-items: center;
    }

    .input-area textarea {
      flex: 1;
      background: var(--input-bg);
      border: 1px solid var(--border-color);
      border-radius: 0.7rem;
      padding: 0.7rem 0.9rem;
      font-size: 0.9rem;
      color: var(--text-primary);
      resize: none;
      outline: none;
      font-family: inherit;
      max-height: 120px;
      min-height: 42px;
    }

    .send-btn {
      background: var(--accent);
      border: none;
      color: white;
      width: 40px; height: 40px;
      border-radius: 0.7rem;
      font-size: 1rem;
      cursor: pointer;
      transition: 0.2s;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
    }
    .send-btn:disabled { opacity: 0.5; cursor: not-allowed; }

    /* 编辑模式输入框 */
    .edit-input {
      width: 100%;
      min-width: 250px;
      background: var(--input-bg);
      border: 2px solid var(--accent);
      border-radius: 0.7rem;
      padding: 0.6rem 0.8rem;
      font-size: 0.9rem;
      color: var(--text-primary);
      outline: none;
      font-family: inherit;
      resize: none;
    }

    .edit-actions {
      display: flex;
      gap: 4px;
      margin-top: 4px;
    }
    .edit-actions button {
      padding: 4px 10px;
      border-radius: 4px;
      border: 1px solid var(--border-color);
      background: var(--bg-primary);
      color: var(--text-primary);
      cursor: pointer;
      font-size: 0.75rem;
    }
    .edit-actions button.save-edit {
      background: var(--accent);
      color: white;
      border-color: var(--accent);
    }

    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(5px); }
      to { opacity: 1; transform: translateY(0); }
    }

    /* 滚动条美化 */
    .chat-messages::-webkit-scrollbar { width: 6px; }
    .chat-messages::-webkit-scrollbar-track { background: transparent; }
    .chat-messages::-webkit-scrollbar-thumb { background: var(--border-color); border-radius: 3px; }
  </style>
</head>
<body>
  <!-- 侧边栏 -->
  <div class="sidebar" id="sidebar">
    <h2><i class="fas fa-comments"></i> ChatUI</h2>
    
    <!-- 新建对话按钮 -->
    <button class="btn btn-new-chat" id="newChatBtn">
      <i class="fas fa-plus"></i> 新建对话
    </button>

    <!-- 对话历史 -->
    <div class="sidebar-section" id="historySection">
      <h3><i class="fas fa-history"></i> 对话历史</h3>
      <div id="conversationList" style="display: flex; flex-direction: column; gap: 4px;">
        <div style="color: var(--text-secondary); font-size: 0.8rem; text-align: center; padding: 1rem;">
          暂无历史对话
        </div>
      </div>
    </div>

    <!-- API 设置 -->
    <div class="sidebar-section">
      <h3><i class="fas fa-cog"></i> API 设置</h3>
      <div class="setting-group">
        <label>API Base URL</label>
        <input type="text" id="apiBaseUrl" placeholder="https://api.deepseek.com/v1" value="https://api.deepseek.com/v1">
      </div>
      <div class="setting-group">
        <label>API Key</label>
        <div class="api-key-wrapper">
          <input type="password" id="apiKey" placeholder="sk-..." autocomplete="off">
          <button class="toggle-visibility" id="toggleKeyBtn" type="button">
            <i class="fas fa-eye"></i>
          </button>
        </div>
      </div>
      <div class="setting-group">
        <label>模型名称</label>
        <input type="text" id="modelName" placeholder="deepseek-v4-flash" value="deepseek-v4-flash">
      </div>
      <div class="dark-mode-row">
        <span><i class="fas fa-moon"></i> 深色模式</span>
        <label class="toggle-switch">
          <input type="checkbox" id="darkModeToggle">
          <span class="slider"></span>
        </label>
      </div>
      <button class="btn btn-outline" id="saveSettingsBtn" style="margin-top: 0.5rem;">
        <i class="fas fa-save"></i> 保存设置
      </button>
    </div>
  </div>

  <!-- 主聊天区域 -->
  <div class="main">
    <div class="chat-header">
      <div class="chat-header-left">
        <i class="fas fa-robot" style="color: var(--accent);"></i>
        <span class="conversation-title" id="conversationTitle">新对话</span>
      </div>
      <button class="btn btn-outline" id="clearChatBtn" style="width: auto; padding: 0.4rem 0.8rem; font-size: 0.8rem;">
        <i class="fas fa-trash-alt"></i> 清空
      </button>
    </div>
    
    <div class="chat-messages" id="chatMessages">
      <div class="message-row assistant">
        <div class="avatar"><i class="fas fa-robot"></i></div>
        <div class="bubble">你好!已默认配置 DeepSeek API。填入 API Key 即可开始对话 🚀<br>你可以编辑任何一条历史消息来重新组织对话上下文。</div>
      </div>
    </div>

    <div class="input-area">
      <textarea id="userInput" rows="1" placeholder="输入消息... (Shift+Enter 换行)"></textarea>
      <button class="send-btn" id="sendBtn" title="发送"><i class="fas fa-paper-plane"></i></button>
    </div>
  </div>

  <script>
    (function() {
      // ============ DOM 元素 ============
      const darkModeToggle = document.getElementById('darkModeToggle');
      const apiBaseUrlInput = document.getElementById('apiBaseUrl');
      const apiKeyInput = document.getElementById('apiKey');
      const modelNameInput = document.getElementById('modelName');
      const toggleKeyBtn = document.getElementById('toggleKeyBtn');
      const saveSettingsBtn = document.getElementById('saveSettingsBtn');
      const clearChatBtn = document.getElementById('clearChatBtn');
      const newChatBtn = document.getElementById('newChatBtn');
      const chatMessages = document.getElementById('chatMessages');
      const userInput = document.getElementById('userInput');
      const sendBtn = document.getElementById('sendBtn');
      const conversationTitle = document.getElementById('conversationTitle');
      const conversationList = document.getElementById('conversationList');

      // ============ 状态变量 ============
      let isStreaming = false;
      let abortController = null;
      
      // 当前对话的所有消息记录 { role: 'user'|'assistant', content: '...' }
      let currentMessages = [];
      
      // 所有已保存的对话
      let conversations = [];
      let currentConversationId = null;

      // ============ 对话管理 ============
      function generateId() {
        return 'conv_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
      }

      function createNewConversation() {
        if (isStreaming && abortController) {
          abortController.abort();
          isStreaming = false;
        }
        
        const newConv = {
          id: generateId(),
          title: '新对话',
          messages: [],
          createdAt: new Date().toISOString()
        };
        
        conversations.unshift(newConv);
        currentConversationId = newConv.id;
        currentMessages = [];
        
        renderChatMessages();
        renderConversationList();
        updateConversationTitle();
        saveConversationsToStorage();
        
        conversationTitle.textContent = '新对话';
      }

      function switchConversation(convId) {
        if (isStreaming && abortController) {
          abortController.abort();
          isStreaming = false;
        }
        
        const conv = conversations.find(c => c.id === convId);
        if (!conv) return;
        
        currentConversationId = convId;
        currentMessages = JSON.parse(JSON.stringify(conv.messages));
        
        renderChatMessages();
        updateConversationTitle();
      }

      function deleteConversation(convId) {
        conversations = conversations.filter(c => c.id !== convId);
        
        if (currentConversationId === convId) {
          // 如果删除的是当前对话,切换到最新对话或创建新对话
          if (conversations.length > 0) {
            switchConversation(conversations[0].id);
          } else {
            createNewConversation();
          }
        }
        
        renderConversationList();
        saveConversationsToStorage();
      }

      function updateConversationTitle() {
        const conv = conversations.find(c => c.id === currentConversationId);
        if (!conv) return;
        
        // 用第一条用户消息作为标题
        const firstUserMsg = conv.messages.find(m => m.role === 'user');
        if (firstUserMsg) {
          conv.title = firstUserMsg.content.substring(0, 30) + (firstUserMsg.content.length > 30 ? '...' : '');
        } else {
          conv.title = '新对话';
        }
        conversationTitle.textContent = conv.title;
        renderConversationList();
        saveConversationsToStorage();
      }

      function saveCurrentConversation() {
        const conv = conversations.find(c => c.id === currentConversationId);
        if (conv) {
          conv.messages = JSON.parse(JSON.stringify(currentMessages));
          updateConversationTitle();
          saveConversationsToStorage();
        }
      }

      // ============ 渲染 ============
      function renderChatMessages() {
        chatMessages.innerHTML = '';
        
        if (currentMessages.length === 0) {
          chatMessages.innerHTML = `
            <div class="message-row assistant">
              <div class="avatar"><i class="fas fa-robot"></i></div>
              <div class="bubble">开始新对话吧!输入消息发送即可 🚀</div>
            </div>
          `;
          return;
        }
        
        currentMessages.forEach((msg, index) => {
          appendMessageToDOM(msg.role, msg.content, index);
        });
        
        scrollToBottom();
      }

      function appendMessageToDOM(role, content, index) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message-row ${role}`;
        messageDiv.dataset.index = index;
        messageDiv.dataset.role = role;
        
        const avatarIcon = role === 'user' ? 'fa-user' : 'fa-robot';
        
        messageDiv.innerHTML = `
          <div class="message-actions">
            <button class="message-action-btn edit-msg-btn" title="编辑此消息">
              <i class="fas fa-pen"></i>
            </button>
          </div>
          <div class="avatar"><i class="fas ${avatarIcon}"></i></div>
          <div class="bubble">${escapeHtml(content)}</div>
        `;
        
        // 绑定编辑按钮事件
        const editBtn = messageDiv.querySelector('.edit-msg-btn');
        editBtn.addEventListener('click', (e) => {
          e.stopPropagation();
          enterEditMode(messageDiv, index);
        });
        
        chatMessages.appendChild(messageDiv);
      }

      function renderConversationList() {
        if (conversations.length === 0) {
          conversationList.innerHTML = `
            <div style="color: var(--text-secondary); font-size: 0.8rem; text-align: center; padding: 1rem;">
              暂无历史对话
            </div>
          `;
          return;
        }
        
        conversationList.innerHTML = conversations.map(conv => {
          const isActive = conv.id === currentConversationId;
          const firstUserMsg = conv.messages.find(m => m.role === 'user');
          const title = firstUserMsg 
            ? firstUserMsg.content.substring(0, 25) + (firstUserMsg.content.length > 25 ? '...' : '')
            : '新对话';
          const date = new Date(conv.createdAt).toLocaleDateString('zh-CN');
          
          return `
            <div class="conversation-item" data-conv-id="${conv.id}" 
                 style="
                   padding: 0.6rem 0.8rem;
                   border-radius: 0.5rem;
                   cursor: pointer;
                   display: flex;
                   align-items: center;
                   justify-content: space-between;
                   gap: 0.5rem;
                   font-size: 0.8rem;
                   background: ${isActive ? 'var(--hover-bg)' : 'transparent'};
                   border: 1px solid ${isActive ? 'var(--accent)' : 'transparent'};
                 ">
              <span style="flex:1; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;" title="${escapeHtml(title)}">
                ${escapeHtml(title)}
              </span>
              <button class="delete-conv-btn" data-conv-id="${conv.id}" 
                      style="
                        background: none; border: none; color: var(--text-secondary);
                        cursor: pointer; padding: 2px 4px; font-size: 0.7rem;
                        opacity: 0.6; flex-shrink: 0;
                      " title="删除此对话">
                <i class="fas fa-times"></i>
              </button>
            </div>
          `;
        }).join('');
        
        // 绑定切换对话事件
        conversationList.querySelectorAll('.conversation-item').forEach(item => {
          item.addEventListener('click', (e) => {
            if (e.target.closest('.delete-conv-btn')) return; // 不触发切换
            const convId = item.dataset.convId;
            if (convId !== currentConversationId) {
              switchConversation(convId);
            }
          });
        });
        
        // 绑定删除对话事件
        conversationList.querySelectorAll('.delete-conv-btn').forEach(btn => {
          btn.addEventListener('click', (e) => {
            e.stopPropagation();
            const convId = btn.dataset.convId;
            if (confirm('确定删除这个对话吗?')) {
              deleteConversation(convId);
            }
          });
        });
      }

      function escapeHtml(text) {
        return String(text)
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/"/g, '&quot;')
          .replace(/'/g, '&#039;');
      }

      function scrollToBottom() {
        chatMessages.scrollTop = chatMessages.scrollHeight;
      }

      // ============ 编辑消息功能 ============
      function enterEditMode(messageDiv, index) {
        if (isStreaming) {
          alert('请等待当前回复完成后再编辑。');
          return;
        }
        
        const role = currentMessages[index].role;
        const originalContent = currentMessages[index].content;
        const bubble = messageDiv.querySelector('.bubble');
        
        // 用 textarea 替换气泡内容
        bubble.innerHTML = `
          <textarea class="edit-input" rows="2">${escapeHtml(originalContent)}</textarea>
          <div class="edit-actions">
            <button class="save-edit">保存并重新发送</button>
            <button class="cancel-edit">取消</button>
          </div>
        `;
        
        const editTextarea = bubble.querySelector('.edit-input');
        editTextarea.focus();
        editTextarea.setSelectionRange(editTextarea.value.length, editTextarea.value.length);
        
        // 保存按钮
        bubble.querySelector('.save-edit').addEventListener('click', () => {
          const newContent = editTextarea.value.trim();
          if (!newContent) {
            alert('消息内容不能为空。');
            return;
          }
          applyEdit(index, newContent);
        });
        
        // 取消按钮
        bubble.querySelector('.cancel-edit').addEventListener('click', () => {
          bubble.textContent = originalContent;
        });
        
        // Enter 保存,Shift+Enter 换行,Escape 取消
        editTextarea.addEventListener('keydown', (e) => {
          if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            const newContent = editTextarea.value.trim();
            if (newContent) applyEdit(index, newContent);
          } else if (e.key === 'Escape') {
            bubble.textContent = originalContent;
          }
        });
      }

      function applyEdit(index, newContent) {
        // 关键逻辑:只保留编辑位置之前的所有消息(不包括被编辑的消息本身及其之后的内容)
        // 保留的消息 = index 之前的所有消息
        const preservedMessages = currentMessages.slice(0, index);
        
        // 添加编辑后的用户消息
        preservedMessages.push({ role: 'user', content: newContent });
        
        // 更新当前消息记录
        currentMessages = preservedMessages;
        
        // 保存到当前对话
        saveCurrentConversation();
        
        // 重新渲染
        renderChatMessages();
        
        // 自动发送以获取新的 AI 回复
        sendWithCurrentMessages(newContent);
      }

      // ============ API 调用 ============
      async function sendWithCurrentMessages(userMessageContent) {
        const baseUrl = apiBaseUrlInput.value.trim();
        const apiKey = apiKeyInput.value.trim();
        const model = modelNameInput.value.trim() || 'deepseek-v4-flash';
        
        if (!baseUrl || !apiKey) {
          alert('请先设置 API Base URL 和 API Key。');
          return;
        }

        let endpoint = baseUrl.replace(/\/+$/, '') + '/chat/completions';
        
        // 创建流式消息气泡
        const streamingBubble = createStreamingMessage();
        let fullContent = '';
        
        isStreaming = true;
        sendBtn.disabled = true;
        abortController = new AbortController();

        try {
          const response = await fetch(endpoint, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${apiKey}`,
            },
            body: JSON.stringify({
              model: model,
              messages: currentMessages,
              stream: true,
            }),
            signal: abortController.signal,
          });

          if (!response.ok) {
            const errorText = await response.text();
            throw new Error(`HTTP ${response.status}: ${errorText}`);
          }

          const reader = response.body.getReader();
          const decoder = new TextDecoder('utf-8');
          let buffer = '';

          while (true) {
            const { done, value } = await reader.read();
            if (done) break;
            
            buffer += decoder.decode(value, { stream: true });
            const lines = buffer.split('\n');
            buffer = lines.pop() || '';

            for (const line of lines) {
              const trimmed = line.trim();
              if (!trimmed || !trimmed.startsWith('data: ')) continue;
              
              const dataStr = trimmed.slice(6).trim();
              if (dataStr === '[DONE]') break;

              try {
                const parsed = JSON.parse(dataStr);
                const delta = parsed.choices?.[0]?.delta?.content;
                if (delta) {
                  fullContent += delta;
                  streamingBubble.textContent = fullContent;
                  scrollToBottom();
                }
              } catch (e) {}
            }
          }

          // 处理 buffer 中剩余数据
          if (buffer.trim()) {
            for (const line of buffer.split('\n')) {
              const trimmed = line.trim();
              if (trimmed.startsWith('data: ') && trimmed.slice(6).trim() !== '[DONE]') {
                try {
                  const parsed = JSON.parse(trimmed.slice(6).trim());
                  const delta = parsed.choices?.[0]?.delta?.content;
                  if (delta) {
                    fullContent += delta;
                    streamingBubble.textContent = fullContent;
                  }
                } catch(e) {}
              }
            }
          }

          // 将 AI 回复添加到消息记录
          if (fullContent.trim()) {
            currentMessages.push({ role: 'assistant', content: fullContent.trim() });
          } else {
            currentMessages.push({ role: 'assistant', content: '(无响应内容)' });
          }
          
          saveCurrentConversation();

        } catch (error) {
          if (error.name === 'AbortError') {
            fullContent += '\n[流式传输已取消]';
            currentMessages.push({ role: 'assistant', content: fullContent });
          } else {
            fullContent += `\n\n❌ 错误: ${error.message}`;
            currentMessages.push({ role: 'assistant', content: fullContent });
          }
          streamingBubble.textContent = fullContent;
          saveCurrentConversation();
        } finally {
          finalizeStreamingMessage(streamingBubble);
          isStreaming = false;
          sendBtn.disabled = false;
          abortController = null;
          scrollToBottom();
        }
      }

      function createStreamingMessage() {
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message-row assistant';
        messageDiv.innerHTML = `
          <div class="avatar"><i class="fas fa-robot"></i></div>
          <div class="bubble" id="streamingBubble"></div>
        `;
        chatMessages.appendChild(messageDiv);
        scrollToBottom();
        return document.getElementById('streamingBubble');
      }

      function finalizeStreamingMessage(bubbleElement) {
        if (bubbleElement && bubbleElement.id === 'streamingBubble') {
          bubbleElement.removeAttribute('id');
        }
      }

      // ============ 发送消息 ============
      async function handleSendMessage() {
        const messageText = userInput.value.trim();
        if (!messageText || isStreaming) return;

        const baseUrl = apiBaseUrlInput.value.trim();
        const apiKey = apiKeyInput.value.trim();
        
        if (!baseUrl || !apiKey) {
          alert('请先设置 API Base URL 和 API Key。');
          return;
        }

        // 添加用户消息到记录
        currentMessages.push({ role: 'user', content: messageText });
        
        // 添加用户消息到 DOM
        appendMessageToDOM('user', messageText, currentMessages.length - 1);
        
        userInput.value = '';
        userInput.style.height = 'auto';
        scrollToBottom();
        
        saveCurrentConversation();
        
        // 发送并获取 AI 回复
        await sendWithCurrentMessages(messageText);
      }

      // ============ 事件绑定 ============
      sendBtn.addEventListener('click', handleSendMessage);
      
      userInput.addEventListener('keydown', (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
          e.preventDefault();
          if (!isStreaming && userInput.value.trim()) handleSendMessage();
        }
      });
      
      userInput.addEventListener('input', () => {
        userInput.style.height = 'auto';
        userInput.style.height = Math.min(userInput.scrollHeight, 120) + 'px';
      });

      newChatBtn.addEventListener('click', createNewConversation);

      clearChatBtn.addEventListener('click', () => {
        if (confirm('确定清空当前对话吗?')) {
          currentMessages = [];
          renderChatMessages();
          saveCurrentConversation();
        }
      });

      // 深色模式
      darkModeToggle.addEventListener('change', (e) => {
        document.body.classList.toggle('dark', e.target.checked);
        saveSettingsToStorage();
      });

      // 密钥可见性
      toggleKeyBtn.addEventListener('click', () => {
        const input = apiKeyInput;
        const icon = toggleKeyBtn.querySelector('i');
        if (input.type === 'password') {
          input.type = 'text';
          icon.classList.replace('fa-eye', 'fa-eye-slash');
        } else {
          input.type = 'password';
          icon.classList.replace('fa-eye-slash', 'fa-eye');
        }
      });

      // 保存设置
      saveSettingsBtn.addEventListener('click', () => {
        saveSettingsToStorage();
        alert('设置已保存!');
      });

      // ============ 存储 ============
      function saveSettingsToStorage() {
        localStorage.setItem('chatui_api_base_url', apiBaseUrlInput.value.trim());
        localStorage.setItem('chatui_api_key', apiKeyInput.value.trim());
        localStorage.setItem('chatui_model_name', modelNameInput.value.trim());
        localStorage.setItem('chatui_dark_mode', document.body.classList.contains('dark'));
      }

      function loadSettings() {
        const savedBaseUrl = localStorage.getItem('chatui_api_base_url');
        const savedApiKey = localStorage.getItem('chatui_api_key');
        const savedModel = localStorage.getItem('chatui_model_name');
        const savedDarkMode = localStorage.getItem('chatui_dark_mode');
        
        if (savedBaseUrl) apiBaseUrlInput.value = savedBaseUrl;
        if (savedApiKey) apiKeyInput.value = savedApiKey;
        if (savedModel) modelNameInput.value = savedModel;
        
        if (savedDarkMode === 'true') {
          document.body.classList.add('dark');
          darkModeToggle.checked = true;
        }
      }

      function saveConversationsToStorage() {
        localStorage.setItem('chatui_conversations', JSON.stringify(conversations));
        localStorage.setItem('chatui_current_conv_id', currentConversationId);
      }

      function loadConversations() {
        const saved = localStorage.getItem('chatui_conversations');
        if (saved) {
          try {
            conversations = JSON.parse(saved);
          } catch(e) {
            conversations = [];
          }
        }
        
        const savedConvId = localStorage.getItem('chatui_current_conv_id');
        if (savedConvId && conversations.find(c => c.id === savedConvId)) {
          currentConversationId = savedConvId;
          const conv = conversations.find(c => c.id === savedConvId);
          currentMessages = JSON.parse(JSON.stringify(conv.messages));
        } else if (conversations.length > 0) {
          currentConversationId = conversations[0].id;
          currentMessages = JSON.parse(JSON.stringify(conversations[0].messages));
        } else {
          createNewConversation();
          return;
        }
        
        renderChatMessages();
        renderConversationList();
        updateConversationTitle();
      }

      // ============ 初始化 ============
      function init() {
        loadSettings();
        loadConversations();
      }

      init();
    })();
  </script>
</body>
</html>
原文