Search code examples
pythonpython-requestsopenai-apigpt-3

How to get th content of a string inside a request response?


I was coding a webapp based on GPT-2 but it was not good so I decided to switch to official OpenAI GPT-3. So I make that request:

response = openai.Completion.create(
  engine="davinci",
  prompt="Hello",
  temperature=0.7,
  max_tokens=64,
  top_p=1,
  frequency_penalty=0,
  presence_penalty=0
)

And when I print the response I get this:

{
  "choices": [
    {
      "finish_reason": "length",
      "index": 0,
      "logprobs": null,
      "text": ", everyone, and welcome to the first installment of the new opening"
    }
  ],
  "created": 1624033807,
  "id": "cmpl-3CBfb8yZAFEUIVXfZO90m77dgd9V4",
  "model": "davinci:2020-05-03",
  "object": "text_completion"
}

But I only want to print the text, so how can I do to print the "text" value in the response list. Thank you in advance and have a good day.


Solution

  • Using the dict indexing by key, and the list indexing by index

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