-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathsse.ts
More file actions
82 lines (68 loc) · 1.97 KB
/
sse.ts
File metadata and controls
82 lines (68 loc) · 1.97 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
import type {
CompletionRequest,
SSEMessage,
} from '../types/message';
import { resolveApiUrl } from './config';
export type SSEMessageHandler = (message: SSEMessage) => void;
export class SSEClient {
private abortController: AbortController | null = null;
async sendMessage(
request: CompletionRequest,
onMessage: SSEMessageHandler
): Promise<void> {
this.abortController = new AbortController();
try {
const response = await fetch(resolveApiUrl('/chat/completion'), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(request),
signal: this.abortController.signal,
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const reader = response.body?.getReader();
if (!reader) {
throw new Error('No response body');
}
const decoder = new TextDecoder();
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) {
if (line.startsWith('data: ')) {
const data = line.slice(6);
try {
const message = JSON.parse(data) as SSEMessage;
onMessage(message);
} catch (e) {
console.error('Failed to parse SSE message:', e, data);
}
}
}
}
} catch (error: any) {
if (error.name === 'AbortError') {
console.log('SSE connection aborted');
} else {
throw error;
}
}
}
cancel() {
if (this.abortController) {
this.abortController.abort();
this.abortController = null;
}
}
}
export const sseClient = new SSEClient();