最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

OpenAI Stream 响应,未按预期工作

网站源码admin42浏览0评论

OpenAI Stream 响应,未按预期工作

OpenAI Stream 响应,未按预期工作

在我的 NodeJS 应用程序上,我设置了一个

POST
方法,如下所示:

exportsplete = async (req, res, next) => {\
    const {prompt} = req.body
    res.writeHead(200, {
      'Content-Type': 'text/plain',
      'Transfer-Encoding': 'chunked'
    })
    const result = await openai.createCompletion(
    {
      model: 'text-davinci-003',
      prompt: prompt,
      temperature: 0.6,
      max_tokens: 700,
      stream: true
    },
    { responseType: 'stream' }
  )

  result.data.on('data', data => {
    const lines = data
      .toString()
      .split('\n')
      .filter(line => line.trim() !== '')
    for (const line of lines) {
      const message = line.replace(/^data: /, '')
      if (message === '[DONE]') {
          res.end()
      }
      try {
        const parsed = JSON.parse(message)
        res.write(parsed.choices[0].text)
      } catch (error) {
        // console.error('Could not JSON parse stream message', message, error)
      }
    }
  })
}

由于 OpenAI Node SDK 本身不支持流式响应,我从一些来源中删除了这段代码。

在某种程度上,我猜它正在起作用。但是当我从 Postman 和命令行(使用

curl
)调用这个端点时,而不是实际获得块中的响应,我在整个
completion
调用完成时得到最终响应。

我不确定我在这里做错了什么。 注意: 上面的代码是 Firebase 函数调用的一部分,我在其中设置了

express
。我不认为它有什么影响,但还是提一下。

编辑 1:

curl
请求

这是我的

curl
要求:

curl --location 'http://localhost:5001/testapp-7aca9/us-central1/api/completion/complete' \
--header 'Content-Type: application/json' \
--data '{
    "message": "Say two random lines"
}'
回答如下:

您可以参考这里发布的解决方案:在 ExpressJS/NestJS 中通过 HTTP 流发送长字符串的正确方法是什么?

可能有2个原因:

  1. curl
    中,您需要添加
    -N
    标志来缓冲响应以直接接收响应
  2. 在浏览器中,直到返回至少 1024 字节(对于 Chrome)才会返回数据,除非您添加
    X-Content-Type-Options
    nosniff
发布评论

评论列表(0)

  1. 暂无评论