http and apis — making the call8 / 9
parsing nested api responses — without crashing on a missing key
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.
Booting Python…
Output
[promptdojo:~]$ _