Appearance
stream — SSE 流式解析
前后端事件契约统一的 SSE 客户端,用 Web Streams(浏览器 + Node 18+ 均可)。
导出
| 导出 | 说明 |
|---|---|
createSseParser(callbacks) | 解析 SSE 事件流 |
dispatchEvent(parser, type, data) | 派发事件 |
XStream | 流式数据类 |
splitStream | 按 \n\n 分隔 SSE 事件 |
splitPart | 按 \n 解析 key:value |
XRequest | SSE / fetch 请求类 |
事件契约
start → intent → sources → thinking → content → result / error (以 [DONE] 结束)服务端 AI 接口(如 ai-server + 你自己的聊天接口)与前端解析共用这套契约。
createSseParser
ts
import { createSseParser, dispatchEvent } from '@flowporr/ai-core'
const events = createSseParser({
start: () => setLoading(true),
intent: ({ intent, params }) => showIntent(intent, params),
sources: ({ sources }) => showSources(sources),
thinking: ({ text }) => appendThinking(text),
content: ({ text }) => appendContent(text),
result: () => setLoading(false),
error: ({ message }) => showError(message),
})
// 派发(服务端推送时由调用方触发)
dispatchEvent(events, 'content', { text: 'hello' })管道实现
useXStream(ai-chat-vue 的 Hook)内部用 ReadableStream + TransformStream 管道:
ReadableStream<Uint8Array>
→ TextDecoderStream (Uint8Array → string)
→ splitStream (按 \n\n 分隔 SSE 事件)
→ splitPart (按 \n 解析 key:value)
→ SSEOutput[]XRequest — SSE/Fetch 请求类
ts
import { XRequest } from '@flowporr/ai-core'
const xreq = new XRequest<string>({
baseURL: '/api',
type: 'fetch', // 'fetch' | 'sse' | 'sip'
transformer: JSON.parse,
onMessage: (msg) => console.log(msg),
onFinish: (all) => console.log('done', all),
})
xreq.send('/chat/stream', { method: 'POST', body: formData })
xreq.abort() // 中断请求