OpenAI GPT-4API ERROR "AttributeError: content"

When I use OpenAI GPT-4 API, an error “AttributeError: content” occurs in completion.choices[0].message.content. How should I solve it? :rage:openai version is 0.28.1
The following is the code and error message:

completion = openai.ChatCompletion.create(model=‘gpt-4’, temperature=1.0, messages=message_history, presence_penalty=0.5, frequency_penalty=0.5)
return completion.choices[0].message.content

Traceback (most recent call last):
File “xxx/.local/lib/python3.10/site-packages/openai/”, line 59, in getattr
return self[k]
KeyError: ‘content’

File “/home/azure-yx/.local/lib/python3.10/site-packages/openai/”, line 61, in getattr
raise AttributeError(*err.args)
AttributeError: content

Consider your extraction of only one key from the response object:

return completion.choices[0].message.content

Where would a “content” error come from? It would come from the key being missing within messages. You can’t extract “content” from the “completion” object if there is no content key returned.

What would cause there to be no content? This response might explain:

    "error": {
        "message": "The response was filtered due to the prompt triggering Azure Content management policy. 
                   Please modify your prompt and retry. To learn more about our content filtering policies
                   please read our documentation:",
        "type": null,
        "param": "prompt",
        "code": "content_filter",
        "status": 400,
        "innererror": {
            "code": "ResponsibleAIPolicyViolation",
            "content_filter_result": {
                "hate": {
                    "filtered": true,
                    "severity": "high"
                "self-harm": {
                    "filtered": true,
                    "severity": "high"
                "sexual": {
                    "filtered": false,
                    "severity": "safe"
                "violence": {
                    "severity": "medium"

You need to capture the full response with json.loads(str(completion)), and then look for the data and handle different responses.


Okay, maybe that’s what’s causing the error I’m having.
I will modify the prompt. Thanks! :grinning:

1 Like

And in python, the way that you would get the content,


after you make sure there’s not an error, and there is a choices, and there is an index 0 with messages…

1 Like

You are right :grinning: I have modified the prompt.