AttributeError
builtins.AttributeError
Stack trace
AttributeError: 'NoneType' object has no attribute 'get'
File "app.py", line 42, in <module>
data = response.choices[0].message.parsed # This returns None and causes error
Why it happens
The OpenAI SDK's message.parsed attribute is None when the LLM response is not valid JSON or does not conform to the expected structured output format. This often happens if the model returns text with markdown fences, extra commentary, or formatting that prevents automatic JSON parsing.
Detection
Check if response.choices[0].message.parsed is None before accessing its fields, and log the raw response content to detect format mismatches early.
Causes & fixes
The LLM response includes markdown fences or extra text around the JSON output.
Modify your prompt to instruct the model to return only raw JSON without markdown fences, or use a parser that strips fences automatically.
The model used is not instruction-tuned and ignores output format instructions.
Switch to an instruction-tuned model like gpt-4o-mini or claude-3-5-haiku-20241022 that reliably follows output format instructions.
The response_format parameter is not set to 'json' or a structured format in the OpenAI chat completion call.
Set response_format={"type": "json_object"} in the chat.completions.create() call to ensure the SDK parses the response automatically.
Code: broken vs fixed
from openai import OpenAI
import os
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Give me JSON data."}]
)
# This line causes AttributeError because parsed is None
data = response.choices[0].message.parsed # Broken: parsed is None
print(data) from openai import OpenAI
import os
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Give me JSON data."}],
response_format={"type": "json_object"} # Added to get parsed JSON
)
data = response.choices[0].message.parsed # Now parsed is a dict
print(data) # Prints the parsed JSON object Workaround
Wrap access to message.parsed in a try/except or if-check; if None, parse response.choices[0].message.content manually with json.loads() after stripping markdown fences.
Prevention
Use the OpenAI SDK's response_format parameter to enforce structured JSON output at the API level, avoiding parsing errors and None values in message.parsed.