PythiloLesson 1 of 3 · progress kept in this browser

Structured output

A language model returns text. To use a reply in a program, you ask for JSON and then treat that reply as untrusted input, the same way you would treat a form submission.

Replies go wrong in predictable ways:

  • The JSON is wrapped in a code fence, with a sentence around it.
  • A field is missing, or has the wrong type.
  • A number arrives as a string, or falls outside the allowed range.
  • There are extra fields you did not ask for.

So parse first, then check every field, and report all the problems at once. That message can go back to the model for another attempt.

import json

data = json.loads('{"score": 3}')
if not isinstance(data, dict):
    raise ValueError("not an object")

Note that bool is a subclass of int, so isinstance(True, int) is true. Test for it separately when you need a real number.

Your task

Write parse_reply(text). Strip one optional code fence, parse the JSON, and return only title (non-empty string), priority (int from 1 to 5, not a bool) and tags (list of strings, default []). Otherwise raise ValueError naming every invalid field.

Next: Tool calling