Search code examples
pythonopenai-apigpt-3

How to get the items inside of an OpenAIobject in Python?


I would like to get the text inside this data structure that is outputted via GPT3 OpenAI. I'm using Python. When I print the object I get:

<OpenAIObject text_completion id=cmpl-6F7ScZDu2UKKJGPXTiTPNKgfrikZ at 0x7f7648cacef0> JSON: {
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "text": "\nWhat was Malcolm X's original name?\nMalcolm X's original name was Malcolm Little.\n\nWhere was Malcolm X born?\nMalcolm X was born in Omaha, Nebraska.\n\nWhat was the profession of Malcolm X's father?\nMalcolm X's father was a Baptist minister.\n\nWhat did Malcolm X do after he stopped attending school?\nMalcolm X became involved in petty criminal activities."
    }
  ],
  "created": 1669061618,
  "id": "cmpl-6F7ScZDu2gJJHKZSPXTiTPNKgfrikZ",
  "model": "text-davinci-002",
  "object": "text_completion",
  "usage": {
    "completion_tokens": 86,
    "prompt_tokens": 1200,
    "total_tokens": 1286
  }
}

How do I get the 'text' component of this? For example, if this object is called: qa ... I can output

qa['choices']

And I get the same items as above... but adding a .text or ['text'] to this does not do it, and gets an error.

But not sure how to isolate the 'text' I've read the docs, but cannot find this... https://beta.openai.com/docs/api-reference/files/delete?lang=python


Solution

  • x = {&quot;choices&quot;: [{&quot;finish_reason&quot;: &quot;length&quot;,
                      &quot;text&quot;: &quot;, everyone, and welcome to the first installment of the new opening&quot;}], }
    
    text = x['choices'][0]['text']
    print(text)  # , everyone, and welcome to the first installment of the new opening