# AIChat 流式接口重构实施计划 > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. **Goal:** 将知识问答功能模块重构为真实的AIChat模块流式接口,实现SSE实时数据传输、消息实时接收展示、对话上下文正确维护,并形成完整的功能流程检查报告。 **Architecture:** 采用前端SSE(Server-Sent Events)技术对接后端 `/api/ai/chat/stream` 接口,使用 EventSource 或 fetch API 实现流式数据传输;通过响应式状态管理实现消息的实时渲染;通过维护 chat_history 数组确保对话上下文的连续性。 **Tech Stack:** Vue 3 Composition API, SSE (EventSource/fetch), Ant Design Vue, JavaScript ES6+ --- ## 📋 文件结构规划 ``` src/ ├── api/ │ └── ai.js (新建) - AI Chat API 定义 ├── composables/ │ └── useSSE.js (新建) - SSE Hook 封装 ├── components/ │ └── QAModule.vue (修改) - 知识问答主组件 ``` --- ### Task 1: 创建 AI Chat API 模块 **Files:** - Create: `c:\Users\33520\Desktop\制度文件管理学习AI智能体 vue版本\src\api\ai.js` - [ ] **Step 1: 创建 AI API 基础文件** ```javascript // src/api/ai.js import axios from 'axios' import { message } from 'ant-design-vue' const BASE_URL = '/api' export const aiAPI = { /** * 发送消息并获取SSE流式响应 * @param {string} messageContent - 用户输入的消息 * @param {Array} chatHistory - 对话历史记录 * @param {function} onMessage - 接收到消息时的回调 * @param {function} onError - 错误回调 * @param {function} onComplete - 完成回调 * @returns {AbortController} 用于取消请求 */ sendMessage: async (messageContent, chatHistory = [], onMessage, onError, onComplete) => { const token = localStorage.getItem('token') if (!token) { onError?.('用户未登录,请先登录') return null } try { const response = await fetch(`${BASE_URL}/ai/chat/stream?message=${encodeURIComponent(messageContent)}`, { method: 'POST', headers: { 'Authorization': `Bearer ${token}`, 'Accept': 'text/event-stream', 'Cache': 'no-cache', }, }) if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`) } const reader = response.body.getReader() const decoder = new TextDecoder() let buffer = '' while (true) { const { done, value } = await reader.read() if (done) { onComplete?.() break } buffer += decoder.decode(value, { stream: true }) const lines = buffer.split('\n') buffer = lines.pop() || '' for (const line of lines) { if (line.startsWith('data:')) { const data = line.slice(5).trim() if (data === '[DONE]') { onComplete?.() return } try { const parsed = JSON.parse(data) if (parsed.type === 'error') { onError?.(parsed.message || '服务器错误') } else if (parsed.type === 'content' || parsed.content || parsed.message) { onMessage?.(parsed.content || parsed.message || data) } else { // 兼容不同格式的响应 onMessage?.(typeof parsed === 'string' ? parsed : JSON.stringify(parsed)) } } catch (e) { // 如果不是JSON格式,直接作为文本处理 if (data && data !== '') { onMessage?.(data) } } } if (line.startsWith('event:error')) { onError?.('服务器返回错误事件') } } } return null } catch (error) { console.error('AI Chat API Error:', error) onError?.(error.message || '网络连接失败') return null } }, /** * 取消当前请求(备用方案) */ cancelRequest: (controller) => { if (controller) { controller.abort() } } } export default aiAPI ``` - [ ] **Step 2: 验证文件创建成功** 检查文件是否存在于指定路径,并确认代码无语法错误。 - [ ] **Step 3: 提交代码** ```bash git add src/api/ai.js git commit -m "feat(ai): 创建AI Chat API模块" ``` --- ### Task 2: 重构 QAModule.vue - 核心逻辑改造 **Files:** - Modify: `c:\Users\33520\Desktop\制度文件管理学习AI智能体 vue版本\src\components\QAModule.vue:370-423` - [ ] **Step 1: 导入新的 AI API** 在 `