首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >OpenAI响应文本提取

OpenAI响应文本提取
EN

Stack Overflow用户
提问于 2022-10-14 12:20:15
回答 1查看 119关注 0票数 1

我正试图修复打开Ai GPT 3 davinci-text-002给我的回复。在控制台中,我得到以下响应文本:

代码语言:javascript
复制
{
  "id": "cmpl-61dshxu43ecbrqir187yilz9mdhsj",
  "object": "text_completion",
  "created": 1665749707,
  "model": "text-davinci-002",
  "choices": [{
    "text": "?\n\nthere is no simple answer to these questions. each person's individual experiences and perspectives will shape their understanding of who they are and what life is. in general, however, people often think of themselves as unique individuals with specific talents, interests, and goals. they may also think of life as a journey full of challenges and opportunities for growth.",
    "index": 0,
    "logprobs": null,
    "finish_reason": "stop"
  }],
  "usage": {
    "prompt_tokens": 7,
    "completion_tokens": 71,
    "total_tokens": 78
  }
}

文本似乎从\n\n开始,以","index"结尾。分离这个文本作为输出的最好方法是什么?以下是我的当前代码:

代码语言:javascript
复制
let open_ai_response;

openai_test();

async function openai_test() {
  var prompt_text = "who am i?"
  var prompt_text2 = "what is life"
  var url = "https://api.openai.com/v1/engines/text-davinci-002/completions";

  var xhr = new XMLHttpRequest();
  xhr.open("POST", url);
  xhr.setRequestHeader("Content-Type", "application/json");
  xhr.setRequestHeader("Authorization", "Bearer sk-00x0x0x0x0x0x0x0x0x0x0x0x0x");

  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      console.log(xhr.status);
      console.log(xhr.responseText);
      var open_ai_response = xhr.responseText;
      console.log(open_ai_response);
      var edit = open_ai_response[0].toUpperCase() + open_ai_response.slice(1).toLowerCase();
      console.log(edit)
    }
  };

  var data = `{
    "prompt": "${prompt_text + prompt_text2}",
    "temperature": 0.7,
    "max_tokens": 256,
    "top_p": 1,
    "frequency_penalty": 0.75,
    "presence_penalty": 0
  }`;

  xhr.send(data);
}

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-14 12:23:36

您收到的响应是JSON格式的。您需要在onreadystatechange处理程序中使用JSON.parse(xhr.responseText)解析它,然后可以通过访问choices[0].text属性检索文本。

代码语言:javascript
复制
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
    var response = JSON.parse(xhr.responseText);
    let text = response.choices[0].text
    console.log(text);    
  }
};

注意,这只会从text数组中的第一个元素读取choices。如果您想处理数组中的所有内容,那么您可以修改上面的逻辑来循环它们。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74069129

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档