TypeError when you index an OpenAI response like a dictionary
TypeError: 'ChatCompletion' object is not subscriptableShort answer
Since SDK 1.0 the OpenAI Python library returns Pydantic model objects instead of dictionaries, so response['choices'] fails. Read fields as attributes, for example completion.choices[0].message.content. If another library needs a real dict, convert the object with model_dump() or to_dict() first.
Fix it fast
1Find out which cause you have
Print the type of what came back and the names it carries. If it says ChatCompletion, you hold an object and square brackets will never work on it.
r = client.chat.completions.create(model=MODEL_NAME, messages=messages) print(type(r)) print(r.model_dump().keys())2Match what you see, then jump to its fix
- 1
The failing line looks like response['choices'][0]['message']['content'] or response.get('usage').Dictionary-style access from the old SDKFix - 2
json.dumps(response) or a logging, caching or database layer fails with a TypeError about the response type.A function that expects a plain dict gets the objectFix
- 1
What does the error look like?
TypeError: 'ChatCompletion' object is not subscriptable
Cause 1 of 2
Dictionary-style access from the old SDK
1Check
Find every place that reads the response with brackets or .get().
grep -rnE "\[['\"]choices['\"]\]|\.get\(['\"]usage" --include='*.py' .2Fix
Use attribute access. The v1 guide shows the same rewrite for completions: brackets become dots, and .get('usage') becomes a lookup on a dict built from the object.
text = completion.choices[0].message.content
usage = dict(completion).get("usage")3Verify
The text prints and no TypeError is raised.
print(text)Confirmed by github.com
Cause 2 of 2
A function that expects a plain dict gets the object
1Check
Look for the place where the whole response object is handed to code that serialises it.
grep -rn "json.dumps(" --include='*.py' .2Fix
Convert once at the boundary. model_dump() returns a dict, model_dump_json() returns a JSON string, and to_dict() and to_json() are documented helpers on the same objects.
data = completion.model_dump()
as_json = completion.model_dump_json(indent=2)3Verify
Store or print data and confirm it is plain Python types.
print(type(data))Confirmed by github.com
How do I stop it coming back?
- Wrap the SDK call in one small function that returns just the text you need, so brackets never spread through the code.
- Add a test that asserts on completion.choices[0].message.content so an SDK change fails loudly.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- stegnor.comMy company site: 804 pages from a Python and Jinja generator, with 15 free browser tools.
- MenuloA restaurant discovery platform in Germany, kept current by a Python ingestion pipeline.
- ShopGoAn e-commerce aggregator with a Python scraping engine behind its catalog, past 10K Google Play downloads.
Related fixes
AI
Old openai.ChatCompletion or openai.Embedding code breaks on a new SDK
APIRemovedInV1
The Python SDK was rewritten in version 1.0.
2 causes, each with a fixAI
Azure OpenAI says the API deployment for this resource does not exist
The API deployment for this resource does not exist
Azure OpenAI does not take a model name in the model field.
2 causes, each with a fixAI
Azure OpenAI fails with an SSL certificate verification error
httpx.ConnectError: [SSL: CERTIFICATE_VERIFY_FAILED]
The client checks the endpoint's certificate against its CA bundle, which is certifi by default.
2 causes, each with a fixAI
The OpenAI client says the API key is missing
Missing credentials. Please pass an `api_key`
OpenAI() looks for an api_key argument first and then the OPENAI_API_KEY environment variable.
3 causes, each with a fixAI
OpenAI says the model is a chat model and not supported in the v1/completions endpoint
This is a chat model and not supported in the v1/completions endpoint
The v1/completions endpoint accepts completion models such as gpt-3.5-turbo-instruct.
3 causes, each with a fixAI
TypeError: Client.__init__() got an unexpected keyword argument 'proxies'
TypeError: Client.__init__() got an unexpected keyword argument 'proxies'
httpx 0.28.0 removed its deprecated proxies argument.
2 causes, each with a fix