Search code examples
pythonopenai-apigpt-3

OpenAI GPT-3 API error: "AttributeError: 'builtin_function_or_method' object has no attribute 'text'"


I'm looking for some help in extracting the "text" from ChatGPT's "openai.Completion.create" function.

This the function I'm using to generate the "response":

#Have ChatGPT generate keywords from article
def generate_keywords(article):
    response = openai.Completion.create(
        model="text-davinci-003",
        prompt=article,
        temperature=0.7,
        max_tokens=60,
        top_p=1.0,
        frequency_penalty=0.0,
        presence_penalty=1
    )
    return response
#---

"article" in this case is the text I am feeding ChatGPT.

"response" when printed, provides me with the following output:

{
  "choices": [
    {
      "finish_reason": "length",
      "index": 0,
      "logprobs": null,
      **"text": ", Iraq 2008. Image by Flickr User VABusDriverNow, I can\u2019t speak for all of us, but I know that after the war we were still running. Running from our pasts, guilt, shame, fear, and the unexplainable anger that comes with being a"**
    }
  ],
  "created": 1680666103,
  "id": "cmpl-71oJjQfWtHlTbcVsyfi7zzJRktzVT",
  "model": "text-davinci-003",
  "object": "text_completion",
  "usage": {
    "completion_tokens": 60,
    "prompt_tokens": 1090,
    "total_tokens": 1150
  }
}

I want to extract the "text" from this data structure.

When I run this:

keywords = generate_keywords(article)
print(keywords.values.text)

But I get this:

File "/Users/wolf/Development/OpenAI/generate_medium_story_image/generate_AI_image.py", line 63, in <module>
    print(keywords.values.text)
          ^^^^^^^^^^^^^^^^^^^^
AttributeError: 'builtin_function_or_method' object has no attribute 'text'

Solution

  • Return just the text from the completion like this:

    def generate_keywords(article):
        response = openai.Completion.create(
            model = 'text-davinci-003',
            prompt = article,
            temperature = 0.7,
            max_tokens = 60,
            top_p = 1.0,
            frequency_penalty = 0.0,
            presence_penalty = 1
        )
        return response['choices'][0]['text'] # Change this
    

    Then just print keywords like this:

    keywords = generate_keywords(article)
    print(keywords)