http and apis — making the call7 / 9
parsing nested api responses — without crashing on a missing key
AI wrote a parser that uses chained .get without defaults. When a
field is missing, the chain returns None and the function quietly
returns None. The caller has no idea anything went wrong, so the
bug surfaces somewhere unrelated.
Fix the function to raise ValueError(f"missing field: {field}")
whenever the field can't be found. Specifically:
- If
choicesis missing or the list is empty, raise with field"choices". - If
messageis missing on the first choice, raise with field"message". - If
contentis missing, raise with field"content".
The starter has a response missing content. Wrap the call in
try/except ValueError as err: print(err).
Expected output:
missing field: content
The break is on lines 2, 3, 4, 5, 6, 11 — but read the whole snippet first.
⌘↵ runs the editor.
Booting Python…
Output
[promptdojo:~]$ _