【AI】多窗口流式问答设计(基于dify的前端设计)
需求
同一个标签页多个独立聊天会话
1 2 3
| 窗口 A → conversation_A → Dify 窗口 B → conversation_B → Dify 窗口 C → conversation_C → Dify
|
核心思想:每个聊天窗口维护自己的 conversation_id,每次请求创建独立的 AbortController,每个流式响应只更新对应窗口的消息。
- Dify 负责: 对话上下文、会话标识、模型生成、流式响应。
- 前端负责: 多窗口状态隔离、请求生命周期管理、消息更新、任务取消、切换和恢复。
一、整体设计
纯前端多会话架构

二、Dify 会话机制
Dify 的 Chat API 核心接口是:
请求参数:
1 2 3 4 5 6 7
| { "inputs": {}, "query": "什么是 RAG?", "response_mode": "streaming", "user": "user_001", "conversation_id": "" }
|
其中两个字段特别重要:
| 字段 |
作用 |
user |
标识最终用户,多个窗口使用同一个用户标识 |
conversation_id |
标识具体聊天会话,不同窗口使用不同 ID |
例如:
1 2 3 4 5 6 7 8 9 10
| 用户 user_001 | ├── 窗口 A │ └── conversation_id = conv_A │ ├── 窗口 B │ └── conversation_id = conv_B │ └── 窗口 C └── conversation_id = conv_C
|
第一次发送消息时,不传 conversation_id,Dify 会创建新会话,并在流式事件中返回会话 ID。之后这个窗口的所有问题都使用这个 ID。
注意:不要每次提问都传空字符串,否则每次都可能创建新的会话,上下文就无法连续。
Dify 的接口也提供独立的 task_id,用于停止某一次正在执行的生成任务。
三、前端数据结构设计
会话和生成任务分开管理。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| interface ChatSession { id: string; // 前端会话 ID conversationId: string|null; // Dify 会话 ID title: string; messages: ChatMessage[]; status: 'idle' | 'streaming' | 'error'; }
interface ChatMessage { id: string; role: 'user' | 'assistant'; content: string; status: 'streaming' | 'completed' | 'error'; taskId?: string; }
interface RunningTask { taskId?: string; sessionId: string; messageId: string; controller: AbortController; }
|
同时维护两个 ID:
sessionId:自己前端生成,用于管理聊天窗口。
conversationId:Dify 返回,用于管理 Dify 上下文。
四、核心代码实现
前端技术栈采用 Vue 3 + Pinia + TypeScript
4.1 创建聊天 Store
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| import { defineStore } from 'pinia';
export const useChatStore = defineStore('chat', { state: () => ({ sessions: {} as Record<string, ChatSession>, activeSessionId: '', tasks: {} as Record<string, RunningTask> }),
getters: { currentSession(state) { return state.sessions[state.activeSessionId]; } },
actions: { createSession() { const id = crypto.randomUUID();
this.sessions[id] = { id, conversationId: null, title: '新对话', messages: [], status: 'idle' };
this.activeSessionId = id;
return id; },
switchSession(id: string) { this.activeSessionId = id; },
updateMessage( sessionId: string, messageId: string, content: string ) { const session = this.sessions[sessionId]; if (!session) return;
const message = session.messages.find( m => m.id === messageId );
if (message) { message.content += content; } } } });
|
4.2 调用 Dify 流式接口
将 Dify 请求封装成一个独立的 DifyService。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
| const DIFY_BASE_URL = 'dify地址'; const DIFY_API_KEY = 'app-xxxxxxxx';
async function sendToDify( sessionId: string, query: string ) { const store = useChatStore(); const session = store.sessions[sessionId];
const userMessageId = crypto.randomUUID(); const assistantMessageId = crypto.randomUUID(); const controller = new AbortController();
session.messages.push({ id: userMessageId, role: 'user', content: query, status: 'completed' });
session.messages.push({ id: assistantMessageId, role: 'assistant', content: '', status: 'streaming' });
const task: RunningTask = { sessionId, messageId: assistantMessageId, controller };
store.tasks[assistantMessageId] = task; session.status = 'streaming';
try { const response = await fetch( `${DIFY_BASE_URL}/chat-messages`, { method: 'POST', headers: { 'Authorization': `Bearer ${DIFY_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ inputs: {}, query, response_mode: 'streaming', user: 'user_001', conversation_id: session.conversationId || undefined }), signal: controller.signal } );
if (!response.ok || !response.body) { throw new Error(`Dify 请求失败: ${response.status}`); }
const reader = response.body.getReader(); const decoder = new TextDecoder();
let buffer = '';
while (true) { const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const events = buffer.split('\n\n'); buffer = events.pop() || '';
for (const rawEvent of events) { const dataLine = rawEvent .split('\n') .find(line => line.startsWith('data:'));
if (!dataLine) continue;
const data = JSON.parse( dataLine.slice(5).trim() );
if (data.conversation_id && !session.conversationId) { session.conversationId = data.conversation_id; }
if (data.task_id && !task.taskId) { task.taskId = data.task_id; }
if (data.event === 'message') { store.updateMessage( sessionId, assistantMessageId, data.answer || '' ); }
if (data.event === 'agent_message') { store.updateMessage( sessionId, assistantMessageId, data.answer || '' ); }
if ( data.event === 'message_end' || data.event === 'workflow_finished' ) { const message = session.messages.find( m => m.id === assistantMessageId );
if (message) message.status = 'completed'; }
if (data.event === 'error') { throw new Error(data.message || 'Dify 生成失败'); } } }
} catch (error: any) { const message = session.messages.find( m => m.id === assistantMessageId );
if (error.name === 'AbortError') { if (message) message.status = 'completed'; } else { if (message) message.status = 'error'; console.error(error); }
} finally { delete store.tasks[assistantMessageId];
if ( !session.messages.some(m => m.status === 'streaming') ) { session.status = 'idle'; } } }
|
4.3 停止某个窗口的生成任务
Dify 接口:
1
| POST /v1/chat-messages/{task_id}/stop
|
前端实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| async function stopGeneration(messageId: string) { const store = useChatStore();
const task = store.tasks[messageId]; if (!task) return;
if (task.taskId) { try { await fetch( `${DIFY_BASE_URL}/chat-messages/${task.taskId}/stop`, { method: 'POST', headers: { 'Authorization': `Bearer ${DIFY_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ user: 'user_001' }) } ); } catch (error) { console.error('通知 Dify 停止失败', error); } }
task.controller.abort();
const session = store.sessions[task.sessionId];
const message = session?.messages.find( m => m.id === messageId );
if (message) { message.status = 'completed'; } }
|
注意:Dify 的停止接口需要使用对应应用类型的参数,user 应与创建任务时一致。前端 AbortController.abort() 和 Dify 停止接口是两个不同动作,不能只做前者。
4.4 切换窗口
1 2 3 4 5 6 7 8
| function switchSession(sessionId: string) { const store = useChatStore();
store.activeSessionId = sessionId;
}
|
例如:
1 2 3 4 5 6 7 8 9 10 11 12
| 窗口 A:conversation_id = conv_A task_A 正在生成
窗口 B:conversation_id = conv_B task_B 正在生成
用户从 A 切换到 B:
只改变 activeSessionId
task_A 继续生成 task_B 继续生成
|
这里一定不要在组件销毁时调用 abort()。
五、保存多个窗口的数据
由于后端没有自己的数据库,使用浏览器的 IndexedDB,因为聊天内容可能非常多。
数据结构:
1 2 3 4 5
| interface LocalChatData { sessions: ChatSession[]; activeSessionId: string; lastUpdatedAt: number; }
|
数据关系:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| IndexedDB | ├── Session A │ ├── conversationId │ ├── Messages │ └── Status │ ├── Session B │ ├── conversationId │ ├── Messages │ └── Status │ └── Session C ├── conversationId ├── Messages └── Status
|
注意:
- IndexedDB 保存前端展示的数据。
- Dify 保存实际的会话历史。
- 两者通过
conversation_id 关联。
刷新页面时:
- 从 IndexedDB 恢复会话列表。
- 恢复每个窗口的历史消息。
- 恢复
conversation_id。
- 用户切换到某个窗口时,可以通过 Dify 的会话消息查询 API 同步历史。
- 不要直接假设之前的 SSE 连接还能恢复。
特别提醒:Dify 普通 Chatbot/Chatflow 的流式回答断线后,并没有通用的 Token 级断点续传接口。 可以查询已保存的会话消息,但如果需要无缝恢复尚未完成的生成过程,需要另外设计任务恢复机制。Workflow/Chatflow 的工作流事件重连能力则有所不同。
六、纯前端方案的一个重要安全问题
如果直接在浏览器中调用 Dify:
1
| const DIFY_API_KEY = 'app-xxxxxxxx';
|
那么 API Key 会暴露在浏览器中。
用户可以通过:
- 浏览器开发者工具。
- Network 请求。
- 前端打包后的 JS 文件。
获取这个 Key。
可能造成其他人盗用你的 Dify 应用额度,甚至利用你的应用发起大量请求。
因此有两种部署模式:
| 方案 |
优点 |
缺点 |
| 前端直接调用 Dify |
不需要开发后端,实施简单 |
API Key 暴露 |
| Dify WebApp 嵌入 |
无需自己管理 API Key |
页面定制和交互自由度受限 |
| 前端 + 轻量 API 代理 |
可以保护 Key,控制访问 |
需要一个简单代理服务 |