5.2 SSE 协议实现

OpenAI 流式 API

1
2
3
4
5
6
7
8
9
10
const stream = await openai.chat.completions.create({
model: 'deepseek-chat',
messages: messages,
stream: true // 启用流式输出
});

for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || '';
process.stdout.write(content);
}

解析流式响应

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
interface StreamChunk {
choices: Array<{
delta: {
content?: string;
};
finish_reason?: string;
}>;
}

async function* streamResponse(messages: Message[]) {
const stream = await openai.chat.completions.create({
model: 'deepseek-chat',
messages,
stream: true
});

for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content;
const done = chunk.choices[0]?.finish_reason === 'stop';

yield { content, done };
}
}

导航

上一篇: 5.1 流式输出的优势

下一篇: 5.3 流式输出处理