小编sam*_*ang的帖子

如何将 OpenAI 流响应从 Nextjs API 发送到客户端

我尝试了openai-streams + nextjs-openai,它们仅适用于 Node 18+,但是,它们在 Node 17 及更低版本上失败。我仅限于 Node 17 及更低版本,因为 Digital Oceans 应用平台目前不支持 Node 18。

我也尝试过这种方法,它在客户端运行良好,但它暴露了 API 密钥。我想在 NextJS API 路由中实现,但无法将流响应传递给客户端。

使用下面的代码,我只能从 API 路由获取第一块响应,而无法获取具有 ChatGPT 效果的流响应。请帮忙。

// /api/prompt.js

import { Configuration, OpenAIApi } from "openai";
import { Readable } from "readable-stream";

const configuration = new Configuration({
  apiKey: process.env.NEXT_PUBLIC_OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

export default async function handler(req, res) {
  const completion = await openai.createCompletion(
    {
      model: "text-davinci-003",
      prompt: "tell me a story",
      max_tokens: …
Run Code Online (Sandbox Code Playgroud)

javascript node.js next.js openai-api

6
推荐指数
1
解决办法
6737
查看次数

标签 统计

javascript ×1

next.js ×1

node.js ×1

openai-api ×1