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

Firebase Functions能否获取第三方EventSource流并返回SSE给客户端?

Firebase Functions 中转SSE流的可行性

Firebase Functions(HTTP触发类型)完全支持从第三方服务商(比如OpenAI)获取SSE流,并将其以SSE形式中转返回给客户端。

关键实现要点

  • 必须使用HTTP触发函数:只有HTTP类型的Firebase Functions支持流式响应,Callable Functions不具备流式输出能力,无法适配这类场景。
  • 响应头配置:需要给客户端返回的响应设置正确的SSE头部:
    • Content-Type: text/event-stream
    • Cache-Control: no-cache
    • Connection: keep-alive
  • 流式转发逻辑:向第三方服务商发起请求时启用流式接收(比如OpenAI API需设置stream: true),然后将上游返回的数据流直接管道转发给客户端,无需缓存全部数据。

代码示例(Node.js)

const functions = require("firebase-functions");
const fetch = require("node-fetch");

exports.proxyOpenAISSE = functions.https.onRequest(async (req, res) => {
  // 配置SSE响应头
  res.setHeader("Content-Type", "text/event-stream");
  res.setHeader("Cache-Control", "no-cache");
  res.setHeader("Connection", "keep-alive");
  // 配置CORS(根据客户端域名调整)
  res.setHeader("Access-Control-Allow-Origin", "*");

  try {
    // 调用OpenAI流式API
    const openAIRes = await fetch("https://api.openai.com/v1/chat/completions", {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${process.env.OPENAI_API_KEY}`,
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        model: "gpt-3.5-turbo",
        messages: [{ role: "user", content: "介绍一下Firebase Functions的流式响应能力" }],
        stream: true
      })
    });

    // 直接将上游流转发给客户端
    openAIRes.body.pipe(res);

    // 监听客户端连接关闭,终止上游请求
    req.on("close", () => {
      openAIRes.body.destroy();
    });
  } catch (err) {
    res.write(`event: error\ndata: ${JSON.stringify({ msg: err.message })}\n\n`);
    res.end();
  }
});

注意事项

  • 超时限制:Firebase Functions默认超时60秒,若需处理长时SSE流,需在控制台将函数超时调整至最大值(9分钟)。
  • 资源成本:流式转发会保持函数实例活跃,需关注实例占用情况,避免不必要的长期连接消耗资源。
  • 错误处理:需捕获上游服务断开、请求失败等异常,及时向客户端发送错误事件并关闭连接。

内容的提问来源于stack exchange,提问作者Danh Đào Thanh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 17:04:57