You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React Native(Expo)中实现ChatGPT Turbo API逐词流式响应

实现ChatGPT Turbo流式输出的代码修改步骤

要在React Native(Expo)中实现逐词流式输出,需要对原代码做以下关键修改:

  • 开启流式传输配置:在请求体中添加stream: true,这是OpenAI API启用流式响应的核心参数。
  • 替换响应处理逻辑:不再使用response.json()一次性解析完整响应,而是通过可读流逐块读取并处理数据。
  • 解析SSE格式数据:OpenAI的流式响应采用Server-Sent Events(SSE)格式,需要过滤特定前缀和结束标记,提取有效内容。

修改后的完整代码

fetch(`https://api.openai.com/v1/chat/completions`, {
  body: JSON.stringify({
    model: 'gpt-3.5-turbo',
    messages: [{ role: 'user', content: 'hello' }],
    temperature: 0.3,
    max_tokens: 2000,
    stream: true, // 新增:启用流式传输
  }),
  method: 'POST',
  headers: {
    'content-type': 'application/json',
    Authorization: 'Bearer ' + API_KEY,
  },
}).then(async (response) => {
  if (!response.ok) {
    console.error('请求失败:', response.status);
    return;
  }

  // 创建流阅读器和文本解码器
  const reader = response.body.getReader();
  const decoder = new TextDecoder('utf-8');
  let fullResponse = '';

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;

    // 解码二进制数据为文本
    const chunk = decoder.decode(value, { stream: true });
    // 按换行分割每条SSE消息,过滤空行
    const lines = chunk.split('\n').filter(line => line.trim() !== '');

    for (const line of lines) {
      // 跳过非data开头的行
      if (!line.startsWith('data: ')) continue;
      
      const dataContent = line.slice(6); // 移除"data: "前缀
      if (dataContent === '[DONE]') continue; // 忽略传输结束标记

      try {
        const parsedData = JSON.parse(dataContent);
        // 获取当前流式输出的内容片段(delta中存储增量内容)
        const contentChunk = parsedData.choices[0].delta?.content || '';
        if (contentChunk) {
          fullResponse += contentChunk;
          console.log('当前输出片段:', contentChunk);
          // 此处可更新React Native状态,实现UI实时刷新
          // 例如:setChatResponse(prev => prev + contentChunk)
        }
      } catch (error) {
        console.error('解析流式数据失败:', error);
      }
    }
  }

  console.log('完整响应内容:', fullResponse);
}).catch(error => {
  console.error('请求异常:', error);
});

关键细节说明

  • TextDecoder:用于将二进制流转换为UTF-8文本,{ stream: true }参数确保能正确处理不完整的字符块。
  • SSE格式处理:流式响应的每一行以data: 开头,最后一行是data: [DONE]表示传输完成,需要过滤这些标记以提取有效内容。
  • UI实时更新:在获取到contentChunk后,直接更新组件状态(如使用useState),即可实现逐词/逐段的实时显示效果。

内容的提问来源于stack exchange,提问作者Ibad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 11:35:18