Structuring the Output as JSON

parsing structured captions

Part of: Caption & Alt-Text Generator

Two separate calls, one for a caption and one for alt text, means two round trips: twice the latency and twice the cost. This lesson merges them into one call that returns both fields as JSON, then builds a parser that survives the model's habit of wrapping JSON in extra text. Asking for both fields at once What actually comes back Models are inconsistent about "return no other text." Sometimes you get clean JSON: Other times the object arrives wrapped in a markdown fence: three backticks, the word json, a newline, the object, then three backticks again. Call json.loads() on that wrapped text and it crashes, because the backticks aren't valid JSON. The defensive parser Rather than trust the wrapper, find the outermost braces and parse only what's between them. index("{") finds the first opening brace no matter what came before it, whether a fence or a sentence of preamble. rindex("}") finds the last closing brace, so nested structure inside the JSON doesn't throw it off. Why one call beats two Every request pays a fixed cost for the image tokens. Send the same picture twice, once for a caption and again for alt text, and you pay that cost twice for no reason. One structured reply w

Challenge: Extract Caption and Alt Text from JSON