# XGrammar

> Grammar-constrained decoding that guarantees structurally correct LLM output

- Category: App Orchestration / Structured Output
- Language: Python
- Repository: https://github.com/mlc-ai/xgrammar
- Website: https://xgrammar.mlc.ai/
- Canonical page: https://ai-tldr.dev/tools/xgrammar/

## In short

XGrammar is an open-source library for structured generation from large language models. It uses constrained decoding to guarantee that a model's output follows a given structure, so the result is always valid against the format you ask for. It sits in the Structured Output category of the App Orchestration tools and is open-source, written in Python.

## Overview

XGrammar is an open-source library for structured generation from large language models. It uses constrained decoding to guarantee that a model's output follows a given structure, so the result is always valid against the format you ask for. It supports JSON, regex, and general context-free grammars.

It is built for developers and teams running LLM inference who need outputs they can parse and trust, such as JSON for tool calls or fixed schemas. Because it constrains the tokens a model can emit, the structure is correct by construction rather than fixed up after the fact, and it is designed to add very little overhead to JSON generation.

In the LLM orchestration space, XGrammar sits at the structured-output layer. It is the default structured generation backend for several inference engines, including vLLM, SGLang, TensorRT-LLM, and MLC-LLM, and runs across Linux, macOS, and Windows on CPU and GPU hardware.

## What it does

- Constrained decoding that ensures 100% structurally correct output
- Supports JSON, regex, and general context-free grammars for custom structures
- Low overhead, with near-zero overhead reported for JSON generation
- Universal deployment across Linux, macOS, and Windows on CPU, NVIDIA/AMD GPU, Apple Silicon, and TPU
- Python, C++, JavaScript, and Swift APIs
- Default structured generation backend in vLLM, SGLang, TensorRT-LLM, and MLC-LLM

## Getting started

Install XGrammar with pip and import it, then follow the official docs for full quickstart usage.

1. Install XGrammar

   Install the package from PyPI.

```bash
pip install xgrammar
```

2. Install for Apple Silicon (optional)

   For use with MPS on Apple Silicon, install the metal extra.

```bash
pip install "xgrammar[metal]"
```

3. Import XGrammar

   Import the library in Python; see the official documentation for the full quick start.

```python
import xgrammar as xgr
```

## When to use it

- Forcing an LLM to return valid JSON that matches a schema for tool calling or API responses
- Constraining output to a custom context-free grammar or regex for a domain-specific format
- Adding structured generation to an inference server such as vLLM or SGLang
- Generating parseable output reliably without post-hoc validation and retries
