bots-garden/razorbillpublic Fork
⑂ v1.0.0
Commits
⬇ Clone ▾
git clone https://git.rickub.com/bots-garden/razorbill.git
git clone ssh://git@rickub.com/bots-garden/razorbill.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP
get-structured-output.md · 70 lines · 2.9 KBmarkdown
Blame HistoryOpen raw

How to get structured output

This guide makes a model answer with JSON that follows a schema, so your program can parse it without checks. It assumes a server running with a chat model; the examples use mlx-community/Qwen3-4B-4bit (models below 1B parameters follow schemas, but often fill them poorly).

With the openai Python library and a Pydantic class

from openai import OpenAI
from pydantic import BaseModel

class City(BaseModel):
    name: str
    country: str
    population: int
    landmarks: list[str]

client = OpenAI(base_url="http://127.0.0.1:7920/v1", api_key="unused")
completion = client.beta.chat.completions.parse(
    model="mlx-community/Qwen3-4B-4bit",
    messages=[{"role": "user", "content": "Describe Lyon, France."}],
    response_format=City,
)
city = completion.choices[0].message.parsed   # a City instance

Run it with uv run --with openai --with pydantic python city.py. Recent versions of the library also offer client.chat.completions.parse(...).

With any client: a JSON Schema

Send response_format with the schema:

"response_format": {
  "type": "json_schema",
  "json_schema": {
    "name": "city",
    "strict": true,
    "schema": {
      "type": "object",
      "additionalProperties": false,
      "required": ["name", "country"],
      "properties": {"name": {"type": "string"}, "country": {"type": "string"}}
    }
  }
}

The answer's content is a JSON string valid against the schema; parse it with your language's JSON library.

Any JSON object, without a schema

"response_format": {"type": "json_object"}

Say in your prompt which keys you want: only the syntax is guaranteed.

Variants

  • Streaming: add "stream": true; the JSON arrives in pieces in delta.content. Join them before parsing.
  • Reasoning models: with thinking on ("reasoning_effort": "low"), the model thinks freely, then writes the JSON; the reasoning is in reasoning_content. Leave room in max_tokens for both. For simple extractions, "reasoning_effort": "none" is faster.
  • Order of the keys: properties come out in the order of the schema. Put a field such as reasoning before answer if you want the model to write it first.
  • A 400 naming a keyword (uniqueItems, multipleOf, not, if…): with "strict": true the server refuses keywords it cannot enforce. Remove the keyword, or set "strict": false and check that rule in your code.
  • Your own system message: keep it. The server appends one sentence asking for JSON (with the schema) to it.
  • Tools and structured output together: response_format cannot be combined with a forced tool call (tool_choice required or named); with tool_choice: "auto" it applies to the text answer.

See also

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# How to get structured output

This guide makes a model answer with JSON that follows a schema, so your program can parse it without checks. It assumes a server running with a chat model; the examples use `mlx-community/Qwen3-4B-4bit` (models below 1B parameters follow schemas, but often fill them poorly).

## With the openai Python library and a Pydantic class

```python
from openai import OpenAI
from pydantic import BaseModel

class City(BaseModel):
    name: str
    country: str
    population: int
    landmarks: list[str]

client = OpenAI(base_url="http://127.0.0.1:7920/v1", api_key="unused")
completion = client.beta.chat.completions.parse(
    model="mlx-community/Qwen3-4B-4bit",
    messages=[{"role": "user", "content": "Describe Lyon, France."}],
    response_format=City,
)
city = completion.choices[0].message.parsed   # a City instance
```

Run it with `uv run --with openai --with pydantic python city.py`. Recent versions of the library also offer `client.chat.completions.parse(...)`.

## With any client: a JSON Schema

Send `response_format` with the schema:

```json
"response_format": {
  "type": "json_schema",
  "json_schema": {
    "name": "city",
    "strict": true,
    "schema": {
      "type": "object",
      "additionalProperties": false,
      "required": ["name", "country"],
      "properties": {"name": {"type": "string"}, "country": {"type": "string"}}
    }
  }
}
```

The answer's `content` is a JSON string valid against the schema; parse it with your language's JSON library.

## Any JSON object, without a schema

```json
"response_format": {"type": "json_object"}
```

Say in your prompt which keys you want: only the syntax is guaranteed.

## Variants

- **Streaming**: add `"stream": true`; the JSON arrives in pieces in `delta.content`. Join them before parsing.
- **Reasoning models**: with thinking on (`"reasoning_effort": "low"`), the model thinks freely, then writes the JSON; the reasoning is in `reasoning_content`. Leave room in `max_tokens` for both. For simple extractions, `"reasoning_effort": "none"` is faster.
- **Order of the keys**: properties come out in the order of the schema. Put a field such as `reasoning` before `answer` if you want the model to write it first.
- **A 400 naming a keyword** (`uniqueItems`, `multipleOf`, `not`, `if`…): with `"strict": true` the server refuses keywords it cannot enforce. Remove the keyword, or set `"strict": false` and check that rule in your code.
- **Your own system message**: keep it. The server appends one sentence asking for JSON (with the schema) to it.
- **Tools and structured output together**: `response_format` cannot be combined with a forced tool call (`tool_choice` `required` or named); with `tool_choice: "auto"` it applies to the text answer.

## See also

- Every field of `response_format`: [HTTP API reference](../reference/http-api.md#structured-output).
- How the constraint works, and its limits: [constrained decoding](../explanation/constrained-decoding.md).