Skip to content
Optimal Lab

AI native · interactive

Force valid JSON

A schema does not ask the model to "please return JSON". It refuses any next token that would break the shape.

Schema on — only legal tokens emit

Step 1 of 4

  1. 1

    Ask for the facts

    The question is ordinary. The constraint comes next.

    What is the capital of Pakistan, and which country is it in?

  2. 2

    Attach a schema, or don't

    With a schema, the only legal output is an object with city and country. Without one, a sentence is fine.

    {
      "city": string,
      "country": string
    }
  3. 3

    Propose the next token

    The model still scores tokens. The schema decides which of those scores are even legal.

    • The
    • {
    • "city"
    • :
    • "Islamabad"
    • ,
    • "country"
    • :
    • "Pakistan"
    • }

    "The" is the token a sentence wants. It is crossed out because an object cannot start that way.

  4. 4

    Emit only what the schema allows

    Your code can parse the result. A sentence would have thrown.

    { "city": "Islamabad", "country": "Pakistan" }

    Parses as JSON.

    Use Generate in the bar above to walk the steps.