skip to content

How do you make LM Studio's /v1/chat/completions return JSON matching a schema, and what should the client still check?

level: middleimportance: nice to knowfreq 4%

answer

  1. the hosted structured-output shape
  2. a field beside messages
  3. json_schema inside response_format
  4. the result is still a string
  5. small models and cut-offs

basics

~20 s

Send response_format with type json_schema and the schema under json_schema.schema; LM Studio constrains GGUF models with llama.cpp grammars and MLX models with Outlines. The JSON still arrives as a string in choices[0].message.content, so parse and validate it.

solid answer

~40 s

LM Studio accepts the OpenAI structured-output shape on `/v1/chat/completions`: `response_format` with `type: "json_schema"` and a `json_schema` object holding a `name` and the `schema`. Every other chat parameter is still honoured. The engine enforces it: GGUF models use llama.cpp's grammar-based sampling, MLX models use Outlines. The JSON comes back as a **string** in `choices[0].message.content`, so the client must parse it. Still check: the docs warn that not all models handle structured output, particularly those below 7B parameters, so test the model you ship; a `max_tokens` cut-off can end the text before the JSON closes; and schema-valid is not correct, so validate the values your code depends on.

code

python · 26 lines
python
import json
from openai import OpenAI

client = OpenAI(base_url="http://localhost:1234/v1", api_key="lm-studio")

ticket_format = {
    "type": "json_schema",
    "json_schema": {
        "name": "ticket",
        "schema": {
            "type": "object",
            "properties": {
                "title": {"type": "string"},
                "priority": {"type": "string", "enum": ["low", "high"]},
            },
            "required": ["title", "priority"],
        },
    },
}

reply = client.chat.completions.create(
    model="your-model",
    messages=[{"role": "user", "content": "File a ticket: the login page is down."}],
    response_format=ticket_format,
)
ticket = json.loads(reply.choices[0].message.content)  # a string until parsed

go deeper

for a junior

Recall the response_format shape with type json_schema, and that the JSON comes back as a string to parse.

for a middle

Explain which engine enforces the schema for GGUF and for MLX builds, and how finish_reason reveals a truncated reply.

for a senior

Show that you test structured output per model and per build, validate values rather than trusting shape, and size max_tokens for the output.

for a principal

Decide where validation and retries belong when a team swaps local models often, so a weaker model fails loudly instead of silently.

## The request field **Structured output** means asking the model for a reply that is valid JSON matching a **JSON Schema** you supply. LM Studio's local server supports it on the OpenAI-compatible **`/v1/chat/completions`** route using the same request shape as the hosted structured-output API, so an OpenAI SDK client pointed at `http://localhost:1234/v1` works unchanged: - `response_format.type` is `"json_schema"`. - `response_format.json_schema` holds a `name` for the format and the `schema` itself. - All other parameters the route recognises (`messages`, `temperature`, `max_tokens`, `stream` and the rest) are honoured as usual. Since LM Studio 0.3.18 the route also accepts `response_format.type` set to `"text"`, which asks for ordinary free text, so clients that always send the field do not break. ## What enforces the schema LM Studio does not just paste the schema into the prompt and hope. The engine that runs the model constrains generation: | Model build | Engine | How the schema is enforced | |---|---|---| | GGUF | LM Studio's llama.cpp engine | llama.cpp's grammar-based sampling APIs | | MLX (on a Mac) | LM Studio's MLX engine | Outlines | Because GGUF and MLX builds of the same model go through different implementations, test the build you actually ship; a schema that behaves on one is not automatically identical on the other. How grammar-constrained decoding works internally is a foundations topic; here it is enough to know which engine does it. ## Reading the result 1. Send the request with `response_format` set. 2. Read `choices[0].message.content`. It is a **string** containing the JSON, not a parsed object; the docs say the client must parse it. 3. Parse it (`json.loads` in Python, `JSON.parse` in TypeScript). 4. Check `finish_reason`: a value of `length` means generation hit `max_tokens`, and the string may stop before the JSON closes. 5. Validate the parsed values your code depends on before acting on them. ## What can still go wrong - **Model capability.** LM Studio's docs warn that not all models are capable of structured output, particularly models below 7B parameters, and suggest checking the model card. A small model can return JSON that fits the shape and still says nothing useful. - **Truncation.** A low `max_tokens` can end generation before the closing brace, and the parse fails. - **Schema-valid is not correct.** The schema constrains the shape, not the truth: a `priority` limited to `low` or `high` will be one of them even when the model guessed. - **Optional fields.** A property not listed in `required` may simply be left out, so code that reads it must handle its absence. - **A model swap.** A different model, or another build of the same one, can follow the schema better or worse; re-run your structured-output tests after every swap. - **The wrong route.** The structured-output page documents `response_format` for `/v1/chat/completions`; do not assume another route reads the same field unless its page says so. - **Tools mixed in.** Function calling uses a separate `tools` parameter. Putting a schema in a tool definition asks the model to call a tool, which is a different contract from shaping the reply. ## Structured output against the alternatives | Approach | Route | What it gives you | |---|---|---| | `response_format` with `json_schema` | `/v1/chat/completions` | output constrained by the engine to the schema | | `response_format` with `text` | `/v1/chat/completions` | ordinary text; nothing constrained | | A `tools` definition | `/v1/chat/completions`, `/v1/responses`, `/v1/messages` | a tool call whose arguments your code receives and runs | | Instructions in the prompt only | any route | nothing enforced; the model may or may not comply | A **streamed** structured reply (`stream: true`) arrives as text chunks like any other completion. Concatenate the chunks and parse once the stream ends; a partial object is not valid JSON. ## When it is the right tool Use the schema whenever code consumes the answer: classification labels, extracted fields, a ticket to file. Keep the schema small, mark the fields your code needs as `required`, and pair it with a short instruction in the messages describing what each field means, since the schema fixes the shape but the prompt still has to explain the task. Keep the parse and the validation in your client, so that a model swap, or a move between GGUF and MLX builds, shows up as a failed check rather than a silent wrong value.

  • The same request behaves differently with the GGUF and the MLX build of one model. Why can that happen?
    LM Studio enforces the schema in the engine: llama.cpp's grammar-based sampling for GGUF builds and Outlines for MLX builds. Two implementations can treat the same schema differently, so test structured output with the build you deploy.
  • json.loads fails on a reply although response_format was set. What do you check first?
    `finish_reason`. If it is `length`, generation stopped at `max_tokens` before the JSON closed; raise the limit or shrink the requested output. If it is `stop`, look at the model: the docs warn that not all models, especially below 7B parameters, handle structured output well.

  • LM Studio returns the parsed object in a separate field of the response.
  • LM Studio enforces the schema only by adding it to the prompt.
  • Any model, however small, gives useful schema-shaped output on LM Studio.
  • The schema goes straight into response_format without a json_schema wrapper.
  • A schema-valid reply is guaranteed to contain correct values.