What this thread does
Do first: Create sgl.Engine with grammar_backend="xgrammar"; serialize your schema with json.dumps.
Short answer
The offline API passes the schema in sampling parameters to llm.generate. Supply prompts as a list of instructions requesting the desired JSON.
What to do
import json, sglang as sgl
llm = sgl.Engine(model_path="meta-llama/Meta-Llama-3.1-8B-Instruct", grammar_backend="xgrammar")
schema = {"type": "object", "properties": {"name": {"type": "string", "pattern": r"^[\w]+$"}, "population": {"type": "integer"}}, "required": ["name", "population"]}
outputs = llm.generate(prompts, {"temperature": 0.1, "top_p": 0.95, "json_schema": json.dumps(schema)})
llm.shutdown()
| Item | Value / action |
|---|---|
| Engine | sgl.Engine; model_path="meta-llama/Meta-Llama-3.1-8B-Instruct" is the example model |
| Backend | grammar_backend="xgrammar"; XGrammar is the default |
| Schema | json_schema: JSON string; example requires name (string matching ^[\w]+$) and population (integer) |
| Sampling example | temperature=0.1, top_p=0.95 |
| Output | Each result’s text field contains generated text |
| Pydantic alternative | json.dumps(CapitalInfo.model_json_schema()); validate with CapitalInfo.model_validate_json(output["text"]) |
| Other server backends | --grammar-backend outlines supports JSON/regex; --grammar-backend llguidance supports JSON/regex/EBNF; XGrammar supports all three |
Limits and open questions
Only one of json_schema, regex or ebnf may be set per request. These sampling numbers are example values, not defaults. The page gives no minimum SGLang version.
Not for: vLLM structured output APIs.
Sources
- Structured Outputs, SGLang documentation.
- Structured Outputs, Markdown, SGLang documentation.
Checked
2026-11-17; read Structured Outputs (redirected SGLang page), its Markdown rendition; no command was run.
Started from a post by @SGLang documentation, packaged by the editor. Original post