Angular中如何通过ChatGPT API实现流式响应处理?
解决方案
一、开启流式响应核心配置
调用ChatGPT API时,必须在请求体中设置stream: true参数,这是获取分块响应的基础前提。
二、实现流式响应的代码示例
Angular默认的HttpClient会等待完整响应返回,无法处理流式数据,建议使用原生fetchAPI实现,以下是组件中的完整代码:
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { responseContent = ''; async sendChatRequest(userPrompt: string) { this.responseContent = ''; const apiKey = 'YOUR_API_KEY'; // 建议从环境变量读取,避免硬编码密钥 try { const response = await fetch('https://api.openai.com/v1/chat/completions', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` }, body: JSON.stringify({ model: 'gpt-3.5-turbo', messages: [{ role: 'user', content: userPrompt }], stream: true // 核心配置:开启流式响应 }) }); if (!response.ok) { throw new Error(`请求失败: ${response.status} ${response.statusText}`); } const reader = response.body?.getReader(); const decoder = new TextDecoder('utf-8'); if (!reader) return; while (true) { const { done, value } = await reader.read(); if (done) break; // 解码分块数据并按行分割处理 const chunkContent = decoder.decode(value, { stream: true }); const lines = chunkContent.split('\n').filter(line => line.trim()); for (const line of lines) { if (!line.startsWith('data: ')) continue; const dataStr = line.slice(6); if (dataStr === '[DONE]') return; // 响应结束标记,终止循环 try { const chunk = JSON.parse(dataStr); // 提取增量内容并拼接到结果中 const deltaContent = chunk.choices[0]?.delta?.content; if (deltaContent) { this.responseContent += deltaContent; } } catch (err) { console.error('解析响应块出错:', err); } } } } catch (err) { console.error('请求处理失败:', err); } } }
三、关键注意事项
- SSE格式解析:ChatGPT流式响应采用Server-Sent Events(SSE)格式,每块以
data:开头,最终以data: [DONE]标记响应结束,需逐行过滤处理。 - 增量内容拼接:每个响应块返回的是
delta.content(增量文本),而非完整响应,需持续拼接到结果字符串中。 - Token限制优化:除流式响应外,还可通过以下方式降低token消耗:
- 对历史对话进行摘要压缩,仅保留关键上下文
- 使用支持更长上下文的模型(如gpt-3.5-turbo-16k)
内容的提问来源于stack exchange,提问作者Konstantin Kim
相关产品推荐
相关产品推荐

