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

Question:

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.nnWhere was Malcolm X born?nMalcolm X was born in Omaha, Nebraska.nnWhat was the profession of Malcolm X's father?nMalcolm X's father was a Baptist minister.nnWhat 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

Asked By: Katie Melosto

||

Answers:

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
Answered By: hybrid1337

You should try:

desired_text = qa.choices[0].text

Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.