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

5

7

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

Clubman answered 21/11, 2022 at 20:26 Comment(0)
A
3
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
Aureomycin answered 21/11, 2022 at 20:30 Comment(0)
G
4

This worked for me:

response.choices[0].message.content

Where response is the return value of:

messages = [
     {
         "role": "system",
         "content": "You are an expert at blah blah"),
     },
]
response = openai.ChatCompletion.create(
      messages=messages + [{"role": "user", "content": prompt}],
      model="gpt-4",
      temperature=0.7,
)
Glottis answered 31/5, 2023 at 11:12 Comment(1)
this is the correct answer - the other answers are doing needless gymnastics to get the response. The choices are a list of objects, and attributes can be accesses via dot notation. This is also the example in the docs: github.com/openai/openai-python#chat-completionsGruver
A
3
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
Aureomycin answered 21/11, 2022 at 20:30 Comment(0)
C
2

None of the previous answers helped me, here is my solution

I am using openai==0.27.4

here is the call

import openai

response = openai.ChatCompletion.create(
  model="gpt-3.5-turbo",
  messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Who won the world series in 2020?"},
        {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
        {"role": "user", "content": "Where was it played?"}
    ]
)

your response will look something like

enter image description here

the response.choices is a list; and you can access the content using

my_openai_obj = list(response.choices)[0]
my_openai_obj.to_dict()['message']['content']
Chophouse answered 24/4, 2023 at 18:37 Comment(1)
The core of your answer is the same as the answer above a month earlier, I guess you oversaw that. Also, the other answer shows that you do not need to make a dictionary, you can also just get the attributes, see the remark there. It is still nice to recall that to_dict() here, even if it is needless. And it is good to show an example for gpt 3.5 which needs system, user and assistant message while the other answer shows it for gpt 4.Pennyweight
A
2

I am using openai==0.27.4:

> chat_response.choices[0]["message"].to_dict()

{'role': 'assistant', 'content': None, 'function_call': <OpenAIObject at 0x7...docs\"}"
}}

> chat_response.choices[0]["message"].to_dict_recursive()

{'role': 'assistant', 'content': None, 'function_call': {'name': 'ls', 'arguments': '{"path": "/docs"}'}}
Astray answered 7/8, 2023 at 20:10 Comment(0)
N
0

You should try:

desired_text = qa.choices[0].text

Nabataean answered 26/1, 2023 at 20:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.