Parsing nested API responses — without crashing on a missing key — step 8 of 9
Write a function extract_content(response) that pulls the
assistant's reply text out of an OpenAI/Anthropic-shaped response.
The chain you want is roughly:
response["choices"][0]["message"]["content"]
Make it defensive:
- If
choicesis missing or empty, return the string"(no choices)". - If
messageis missing on the first choice, return"(no message)". - If
contentis missing, return"(no content)". - Otherwise return the actual content string.
The starter has three test responses. Print the result for each.
Expected output:
hello world
(no choices)
(no content)
⌘↵ runs the editor.read, then continue.
Write a function extract_content(response) that pulls the
assistant's reply text out of an OpenAI/Anthropic-shaped response.
The chain you want is roughly:
response["choices"][0]["message"]["content"]
Make it defensive:
- If
choicesis missing or empty, return the string"(no choices)". - If
messageis missing on the first choice, return"(no message)". - If
contentis missing, return"(no content)". - Otherwise return the actual content string.
The starter has three test responses. Print the result for each.
Expected output:
hello world
(no choices)
(no content)
this step needs the editor
on desktop today; in the app (coming soon). save your spot and we'll bring you back here when you're ready.