typescript 如何从完成响应返回OpenAI的文本?

inkz8wg9  于 2022-12-24  发布在  TypeScript
关注(0)|答案(2)|浏览(315)
const gptResponse = await openai
      .createCompletion({
        model: "davinci",
        prompt,
        max_tokens: 60,
        temperature: 0.9,
        presence_penalty: 0,
        frequency_penalty: 0.5,
        best_of: 1,
        n: 1,
        stream: false,
        stop: ["\n", "\n\n"]
      })
      .catch((err) => {
        console.log(err); 

        return { data: { choices: [{ text: "" }] } };
      });

    const response = gptResponse.data.choices[0]?.text;

为什么我得到错误'gptResponse.data.choices'可能是'未定义'. ts(18048)?

mzaanser

mzaanser1#

我做了些调查找到了你问题的答案:

const { Configuration, OpenAIApi } = require("openai");

const configuration = new Configuration({
  apiKey: "your_key",
});
const openai = new OpenAIApi(configuration);

const response = openai.createCompletion({
  model: "text-davinci-002",
  prompt: "#JavaScript to Python:\nJavaScript: \ndogs = [\"bill\", \"joe\", \"carl\"]\ncar = []\ndogs.forEach((dog) >  temperature: 0",
  max_tokens: 64,
  top_p: 1.0,
  frequency_penalty: 0.0,
  presence_penalty: 0.0,
}).then((res) => {console.log(res.data.choices[0].text)});

只需使用.then()

ws51t4hk

ws51t4hk2#

我遇到过类似的错误,系统无法从数据中提取文本。choices[0]。我只在两种情况下遇到过这种错误,第一种情况是未在openai中设置起始文本。createCompletion({promt:“text”})设置,在第二种情况下,openai.createCompletion({流:true})已在true模式下打开,因此data.choices[0]中的文本已拆分为符号和单词。

相关问题