Home > Software engineering >  OpenAI Response Text Extraction
OpenAI Response Text Extraction

Time:10-15

I'm trying to fix the response that Open Ai GPT 3 davinci-text-002 is giving me. In the console I am getting the following response text:

{
  "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
  }
}

The text seems to start at \n\n and end at ","index". What would be the best way to isolate this text to use as an output? Here is my current code:

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);
}

CodePudding user response:

The response you're receiving is JSON formatted. You need to parse it in the onreadystatechange handler using JSON.parse(xhr.responseText), then you can retrieve the text by accessing the choices[0].text property.

xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
    var response = JSON.parse(xhr.responseText);
    let text = response.choices[0].text
    console.log(text);    
  }
};

Note that this only reads the text from the first element in the choices array. If you want to handle all content in that array, then you can amend the above logic to loop through them instead.

  • Related