basforge

Search titles, text and the “If it doesn’t work” cases.

    RU

    Need JSON? Give a schema instead of asking “answer in JSON”

    “Answer in JSON format” sometimes gives JSON wrapped in explanations, with a stray comma or a missing field. Structured output (output_config.format on Claude, response_format on OpenAI) guarantees an answer strictly by a JSON schema: a script parses it without checking “what if there’s text in there”.

    What it looks like

    Parsing an order email into fields:

    "output_config": {
      "format": {
        "type": "json_schema",
        "schema": {
          "type": "object",
          "properties": {
            "customer": { "type": "string" },
            "email":    { "type": ["string", "null"] },
            "plan":     { "type": "string", "enum": ["basic", "pro", "enterprise", "unknown"] },
            "urgent":   { "type": "boolean" }
          },
          "required": ["customer", "email", "plan", "urgent"],
          "additionalProperties": false
        }
      }
    }

    The answer is exactly that object, as the first and only text: jq -r '.content[] | select(.type == "text") | .text' answer.json | jq .plan.

    What to look at in the schema

    • null for empty. Without ["string", "null"] the model has to write something — and it will write something invented.
    • enum for labels. A closed list instead of free text: "unknown" is the way out for a case that fits no label.
    • additionalProperties: false — no extra fields to break the parsing.
    • Field descriptions. "description": "the email from the signature, not the sender address" works as an instruction.

    Why it beats the old ways

    Method What breaks
    “answer only with JSON” in the prompt an explanation before or after, a code-block wrapper, a cut-off answer
    prefilling { 400 on Claude 4.6 and newer
    calling a tool just for the JSON works, but forcing it with tool_choice on Opus 5.5 and Sonnet 5.5 returns 400
    structured output nothing: the answer is checked against the schema before it’s sent

    A schema guarantees the shape, not the truth: the email field will be a string, but it may be the wrong address. Check values the same way as any model answer (Repeatable answers).