aiStreamSession.js
4.38 KB
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
import { DEMO_STREAM_MARKDOWN } from './demoStreamMarkdown.js'
import {
USE_AI_STREAM_MOCK,
STREAM_MOCK_CHARS_PER_TICK,
STREAM_MOCK_INTERVAL_MS,
STREAM_WAIT_TIMEOUT_MS
} from './constants.js'
import AiChatWsService from './AiChatWsService.js'
const STREAM_DELTA_TYPES = new Set([
'text',
'delta',
'chunk',
'markdown',
'content',
'message',
'answer'
])
const STREAM_DONE_TYPES = new Set(['done', 'end', 'complete', 'finished', 'stop'])
function extractDelta(data) {
if (!data || typeof data !== 'object') return ''
if (STREAM_DONE_TYPES.has(data.type)) return null
if (data.type === 'receiving' || data.type === 'processing') return ''
if (STREAM_DELTA_TYPES.has(data.type)) {
return data.content ?? data.text ?? data.delta ?? data.markdown ?? data.message ?? ''
}
if (typeof data.content === 'string' && data.type !== 'error') {
return data.content
}
return ''
}
function isDoneMessage(data) {
return data && STREAM_DONE_TYPES.has(data.type)
}
function isErrorMessage(data) {
return data && (data.type === 'error' || data.error)
}
class AiStreamSession {
constructor() {
this._active = false
this._markdown = ''
this._callbacks = null
this._prevOnMessage = null
this._mockTimer = null
this._timeoutTimer = null
this._mockIndex = 0
this._useMock = false
}
get isActive() {
return this._active
}
get markdown() {
return this._markdown
}
/**
* @param {{ onUpdate?: Function, onDone?: Function, onError?: Function, useMock?: boolean }} callbacks
*/
start(callbacks = {}) {
this.cancel()
this._active = true
this._markdown = ''
this._callbacks = callbacks
this._useMock = callbacks.useMock ?? USE_AI_STREAM_MOCK
if (this._useMock) {
this._startMockStream(DEMO_STREAM_MARKDOWN)
} else {
this._bindWsListener()
this._timeoutTimer = setTimeout(() => {
if (this._active) {
this._finish(new Error('等待 AI 回复超时'))
}
}, STREAM_WAIT_TIMEOUT_MS)
}
return this
}
cancel() {
this._active = false
this._unbindWsListener()
this._clearTimers()
this._callbacks = null
this._mockIndex = 0
}
handleWsMessage(data) {
if (!this._active) return
if (isErrorMessage(data)) {
const msg = data.message || data.content || data.error || 'AI 返回错误'
this._finish(new Error(msg))
return
}
if (isDoneMessage(data)) {
this._finish()
return
}
const delta = extractDelta(data)
if (delta === null) {
this._finish()
return
}
if (delta) {
this._append(delta)
}
}
_append(chunk) {
if (!chunk) return
this._markdown += chunk
this._callbacks?.onUpdate?.({
markdown: this._markdown,
delta: chunk
})
}
_finish(err) {
if (!this._active) return
this._active = false
this._clearTimers()
this._unbindWsListener()
if (err) {
this._callbacks?.onError?.(err)
} else {
this._callbacks?.onDone?.({
markdown: this._markdown
})
}
this._callbacks = null
}
_bindWsListener() {
const client = AiChatWsService.getInstance().getClient()
this._prevOnMessage = client.onMessage
client.onMessage = (data) => {
this.handleWsMessage(data)
this._prevOnMessage && this._prevOnMessage(data)
}
}
_unbindWsListener() {
const client = AiChatWsService.getInstance().getClient()
if (client.onMessage && this._prevOnMessage !== undefined) {
client.onMessage = this._prevOnMessage
}
this._prevOnMessage = null
}
_clearTimers() {
if (this._mockTimer) {
clearInterval(this._mockTimer)
this._mockTimer = null
}
if (this._timeoutTimer) {
clearTimeout(this._timeoutTimer)
this._timeoutTimer = null
}
}
_startMockStream(fullText) {
this._mockIndex = 0
this._mockTimer = setInterval(() => {
if (!this._active) return
if (this._mockIndex >= fullText.length) {
this._finish()
return
}
const chunk = fullText.slice(this._mockIndex, this._mockIndex + STREAM_MOCK_CHARS_PER_TICK)
this._mockIndex += STREAM_MOCK_CHARS_PER_TICK
this._append(chunk)
}, STREAM_MOCK_INTERVAL_MS)
}
}
let _instance = null
export function getAiStreamSession() {
if (!_instance) {
_instance = new AiStreamSession()
}
return _instance
}
export default AiStreamSession