> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sglang.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Sampling Parameters

This doc describes the sampling parameters of the SGLang Runtime. It is the low-level endpoint of the runtime.
If you want a high-level endpoint that can automatically handle chat templates, consider using the [OpenAI Compatible API](https://docs.sglang.io/docs/basic_usage/openai_api_completions.md).

## `/generate` Endpoint

The `/generate` endpoint accepts the following parameters in JSON format. For detailed usage, see the [native API doc](https://docs.sglang.io/docs/basic_usage/native_api.md). The object is defined at `io_struct.py::GenerateReqInput`. You can also read the source code to find more arguments and docs.

<table>
  <colgroup>
    <col />

    <col />

    <col />
  </colgroup>

  <thead>
    <tr>
      <th>Argument</th>
      <th>Type/Default</th>
      <th>Description</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>text</td>
      <td>`Optional[Union[List[str], str]] = None`</td>
      <td>The input prompt. Can be a single prompt or a batch of prompts.</td>
    </tr>

    <tr>
      <td>input\_ids</td>
      <td>`Optional[Union[List[List[int]], List[int]]] = None`</td>
      <td>The token IDs for text; one can specify either text or input\_ids.</td>
    </tr>

    <tr>
      <td>input\_embeds</td>
      <td>`Optional[Union[List[List[List[float]]], List[List[float]]]] = None`</td>
      <td>The embeddings for input\_ids; one can specify either text, input\_ids, or input\_embeds.</td>
    </tr>

    <tr>
      <td>image\_data</td>
      <td>`Optional[Union[List[List[ImageDataItem]], List[ImageDataItem], ImageDataItem]] = None`</td>
      <td>The image input. Supports three formats: (1) **Raw images**: PIL Image, file path, URL, or base64 string; (2) **Processor output**: Dict with `format: "processor_output"` containing HuggingFace processor outputs; (3) **Precomputed embeddings**: Dict with `format: "precomputed_embedding"` and `feature` containing pre-calculated visual embeddings. Can be a single image, list of images, or list of lists of images. See [Multimodal Input Formats](#multimodal) for details.</td>
    </tr>

    <tr>
      <td>audio\_data</td>
      <td>`Optional[Union[List[AudioDataItem], AudioDataItem]] = None`</td>
      <td>The audio input. Can be a file name, URL, or base64 encoded string.</td>
    </tr>

    <tr>
      <td>sampling\_params</td>
      <td>`Optional[Union[List[Dict], Dict]] = None`</td>
      <td>The sampling parameters as described in the sections below.</td>
    </tr>

    <tr>
      <td>rid</td>
      <td>`Optional[Union[List[str], str]] = None`</td>
      <td>The request ID.</td>
    </tr>

    <tr>
      <td>return\_logprob</td>
      <td>`Optional[Union[List[bool], bool]] = None`</td>
      <td>Whether to return log probabilities for tokens.</td>
    </tr>

    <tr>
      <td>logprob\_start\_len</td>
      <td>`Optional[Union[List[int], int]] = None`</td>
      <td>If return\_logprob, the start location in the prompt for returning logprobs. Default is "-1", which returns logprobs for output tokens only.</td>
    </tr>

    <tr>
      <td>top\_logprobs\_num</td>
      <td>`Optional[Union[List[int], int]] = None`</td>
      <td>If return\_logprob, the number of top logprobs to return at each position. Must be an integer in `[0, vocab_size]`, otherwise the request fails with HTTP 400. It is not capped at OpenAI's limit of 20, and it is ignored when `return_logprob` is not set.</td>
    </tr>

    <tr>
      <td>token\_ids\_logprob</td>
      <td>`Optional[Union[List[List[int]], List[int]]] = None`</td>
      <td>If return\_logprob, the token IDs to return logprob for.</td>
    </tr>

    <tr>
      <td>return\_text\_in\_logprobs</td>
      <td>`bool = False`</td>
      <td>Whether to detokenize tokens in text in the returned logprobs.</td>
    </tr>

    <tr>
      <td>stream</td>
      <td>`bool = False`</td>
      <td>Whether to stream output.</td>
    </tr>

    <tr>
      <td>lora\_path</td>
      <td>`Optional[Union[List[Optional[str]], Optional[str]]] = None`</td>
      <td>The path to the LoRA.</td>
    </tr>

    <tr>
      <td>custom\_logit\_processor</td>
      <td>`Optional[Union[List[Optional[str]], str]] = None`</td>
      <td>Custom logit processor for advanced sampling control. Must be a serialized instance of `CustomLogitProcessor` using its `to_str()` method. For usage see below.</td>
    </tr>

    <tr>
      <td>return\_hidden\_states</td>
      <td>`Union[List[bool], bool] = False`</td>
      <td>Whether to return hidden states.</td>
    </tr>

    <tr>
      <td>return\_routed\_experts</td>
      <td>`bool = False`</td>
      <td>Whether to return routed experts for MoE models. Requires `--enable-return-routed-experts` server flag. With the default `routed_experts_start_len=0`, returns the full available sequence `[0, seqlen - 1)` because RL workflows need routed experts for the full sequence. The result is base64-encoded int32 expert IDs as a flattened array with logical shape `[num_tokens, num_layers, top_k]`.</td>
    </tr>

    <tr>
      <td>routed\_experts\_start\_len</td>
      <td>`int = 0`</td>
      <td>If `return_routed_experts`, the absolute start position for returned routed-experts rows. `0` preserves the default full sequence; set it to an accumulated prefix length to return only `[routed_experts_start_len, seqlen - 1)`. For example, in multi-turn RL rollouts, routed experts for tokens from previous turns have already been collected, so setting this value avoids unnecessary transfer that cause bottlenecks. Must be in `[0, prompt_tokens]`.</td>
    </tr>
  </tbody>
</table>

## Sampling parameters

The object is defined at `sampling_params.py::SamplingParams`. You can also read the source code to find more arguments and docs.

### Note on defaults

By default, SGLang initializes several sampling parameters from the model's `generation_config.json` (when the server is launched with `--sampling-defaults model`, which is the default). To use SGLang/OpenAI constant defaults instead, start the server with `--sampling-defaults openai`. You can always override any parameter per request via `sampling_params`.

```bash Command theme={null}
# Use model-provided defaults from generation_config.json (default behavior)
python -m sglang.launch_server --model-path <MODEL> --sampling-defaults model

# Use SGLang/OpenAI constant defaults instead
python -m sglang.launch_server --model-path <MODEL> --sampling-defaults openai
```

### Core parameters

<table>
  <colgroup>
    <col />

    <col />

    <col />
  </colgroup>

  <thead>
    <tr>
      <th>Argument</th>
      <th>Type/Default</th>
      <th>Description</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>max\_new\_tokens</td>
      <td>`int = 128`</td>
      <td>The maximum output length measured in tokens.</td>
    </tr>

    <tr>
      <td>stop</td>
      <td>`Optional[Union[str, List[str]]] = None`</td>
      <td>One or multiple [stop words](https://platform.openai.com/docs/api-reference/chat/create#chat-create-stop). Generation will stop if one of these words is sampled.</td>
    </tr>

    <tr>
      <td>stop\_token\_ids</td>
      <td>`Optional[List[int]] = None`</td>
      <td>Provide stop words in the form of token IDs. Generation will stop if one of these token IDs is sampled. IDs outside `[0, vocab_size)` are ignored because they can never be sampled.</td>
    </tr>

    <tr>
      <td>stop\_regex</td>
      <td>`Optional[Union[str, List[str]]] = None`</td>
      <td>Stop when hitting any of the regex patterns in this list. Patterns are checked before generation: compounding repetitions, repeated alternatives, excessive repeat counts or nesting, look-around, backreferences, and conditional groups are rejected. Ordinary patterns such as `[.!?]\s*$`, `and|or`, and `\d+` are supported. These checks apply to `stop_regex`; the structured-output `regex` parameter has a separate grammar engine.</td>
    </tr>

    <tr>
      <td>temperature</td>
      <td>`float (model default; fallback 1.0)`</td>
      <td>[Temperature](https://platform.openai.com/docs/api-reference/chat/create#chat-create-temperature) when sampling the next token. `temperature = 0` corresponds to greedy sampling, a higher temperature leads to more diversity.</td>
    </tr>

    <tr>
      <td>top\_p</td>
      <td>`float (model default; fallback 1.0)`</td>
      <td>[Top-p](https://platform.openai.com/docs/api-reference/chat/create#chat-create-top_p) selects tokens from the smallest sorted set whose cumulative probability exceeds `top_p`. When `top_p = 1`, this reduces to unrestricted sampling from all tokens.</td>
    </tr>

    <tr>
      <td>top\_k</td>
      <td>`int (model default; fallback -1)`</td>
      <td>[Top-k](https://developer.nvidia.com/blog/how-to-get-better-outputs-from-your-large-language-model/#predictability_vs_creativity) randomly selects from the `k` highest-probability tokens.</td>
    </tr>

    <tr>
      <td>min\_p</td>
      <td>`float (model default; fallback 0.0)`</td>
      <td>[Min-p](https://github.com/huggingface/transformers/issues/27670) samples from tokens with probability larger than `min_p * highest_token_probability`.</td>
    </tr>
  </tbody>
</table>

### Penalizers

<table>
  <colgroup>
    <col />

    <col />

    <col />
  </colgroup>

  <thead>
    <tr>
      <th>Argument</th>
      <th>Type/Default</th>
      <th>Description</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>frequency\_penalty</td>
      <td>`float = 0.0`</td>
      <td>Penalizes tokens based on their frequency in generation so far. Must be between `-2` and `2` where negative numbers encourage repeatment of tokens and positive number encourages sampling of new tokens. The scaling of penalization grows linearly with each appearance of a token.</td>
    </tr>

    <tr>
      <td>presence\_penalty</td>
      <td>`float = 0.0`</td>
      <td>Penalizes tokens if they appeared in the generation so far. Must be between `-2` and `2` where negative numbers encourage repeatment of tokens and positive number encourages sampling of new tokens. The scaling of the penalization is constant if a token occurred.</td>
    </tr>

    <tr>
      <td>repetition\_penalty</td>
      <td>`float = 1.0`</td>
      <td>Scales the logits of previously generated tokens to discourage (values > 1) or encourage (values \< 1) repetition. Valid range is `(0, 2]`; `1.0` leaves probabilities unchanged.</td>
    </tr>

    <tr>
      <td>min\_new\_tokens</td>
      <td>`int = 0`</td>
      <td>Forces the model to generate at least `min_new_tokens` until a stop word or EOS token is sampled. Note that this might lead to unintended behavior, for example, if the distribution is highly skewed towards these tokens.</td>
    </tr>
  </tbody>
</table>

### Constrained decoding

Please refer to our dedicated guide on [constrained decoding](https://docs.sglang.io/docs/advanced_features/structured_outputs.md) for the following parameters.

<table>
  <colgroup>
    <col />

    <col />

    <col />
  </colgroup>

  <thead>
    <tr>
      <th>Argument</th>
      <th>Type/Default</th>
      <th>Description</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>json\_schema</td>
      <td>`Optional[str] = None`</td>
      <td>JSON schema for structured outputs.</td>
    </tr>

    <tr>
      <td>regex</td>
      <td>`Optional[str] = None`</td>
      <td>Regex for structured outputs.</td>
    </tr>

    <tr>
      <td>ebnf</td>
      <td>`Optional[str] = None`</td>
      <td>EBNF for structured outputs.</td>
    </tr>

    <tr>
      <td>structural\_tag</td>
      <td>`Optional[str] = None`</td>
      <td>The structal tag for structured outputs.</td>
    </tr>
  </tbody>
</table>

### Other options

<table>
  <colgroup>
    <col />

    <col />

    <col />
  </colgroup>

  <thead>
    <tr>
      <th>Argument</th>
      <th>Type/Default</th>
      <th>Description</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>n</td>
      <td>`int = 1`</td>
      <td>Specifies the number of output sequences to generate per request. (Generating multiple outputs in one request (n > 1) is discouraged; repeating the same prompts several times offers better control and efficiency.) Must be an integer from 1 to 4096; `SGLANG_MAX_BATCH_REQS_PER_HTTP_REQ` sets the upper bound, and a negative value removes it. Larger, zero, negative, non-integer, or boolean values are rejected before the request is expanded (see [Validation](#validation)). The OpenAI-compatible APIs keep OpenAI's limit of 128, which a setting below 128 lowers further.</td>
    </tr>

    <tr>
      <td>logit\_bias</td>
      <td>`Optional[Dict[str, float]] = None`</td>
      <td>Maps token IDs to a bias added to their logits. Each key must be a token ID in `[0, vocab_size)` and each value a finite number with magnitude at most `1e30` (the sampler divides logits by a temperature of at least `1e-6`, so larger values overflow float32); otherwise the request fails with HTTP 400. Values outside OpenAI's `[-100, 100]` range are accepted.</td>
    </tr>

    <tr>
      <td>ignore\_eos</td>
      <td>`bool = False`</td>
      <td>Don't stop generation when EOS token is sampled.</td>
    </tr>

    <tr>
      <td>skip\_special\_tokens</td>
      <td>`bool = True`</td>
      <td>Remove special tokens during decoding.</td>
    </tr>

    <tr>
      <td>spaces\_between\_special\_tokens</td>
      <td>`bool = True`</td>
      <td>Whether or not to add spaces between special tokens during detokenization.</td>
    </tr>

    <tr>
      <td>no\_stop\_trim</td>
      <td>`bool = False`</td>
      <td>Don't trim stop words or EOS token from the generated text.</td>
    </tr>

    <tr>
      <td>custom\_params</td>
      <td>`Optional[List[Optional[Dict[str, Any]]]] = None`</td>
      <td>Used when employing `CustomLogitProcessor`. For usage, see below.</td>
    </tr>
  </tbody>
</table>

### Validation

Invalid sampling parameters are rejected with HTTP 400 before the request is scheduled. With `stream` set to `true`, the error is instead sent as a `data: {"error": ...}` server-sent event followed by `data: [DONE]`, under HTTP 200. SGLang deliberately does not impose OpenAI's limits of `temperature <= 2` or `top_logprobs <= 20`.

## Examples

### Normal

Launch a server:

```bash Command theme={null}
python -m sglang.launch_server --model-path meta-llama/Meta-Llama-3-8B-Instruct --port 30000
```

Send a request:

```python Example theme={null}
import requests

response = requests.post(
    "http://localhost:30000/generate",
    json={
        "text": "The capital of France is",
        "sampling_params": {
            "temperature": 0,
            "max_new_tokens": 32,
        },
    },
)
print(response.json())
```

Detailed example in [send request](https://docs.sglang.io/docs/basic_usage/send_request.md).

### Streaming

Send a request and stream the output:

```python Example theme={null}
import requests, json

response = requests.post(
    "http://localhost:30000/generate",
    json={
        "text": "The capital of France is",
        "sampling_params": {
            "temperature": 0,
            "max_new_tokens": 32,
        },
        "stream": True,
    },
    stream=True,
)

prev = 0
for chunk in response.iter_lines(decode_unicode=False):
    chunk = chunk.decode("utf-8")
    if chunk and chunk.startswith("data:"):
        if chunk == "data: [DONE]":
            break
        data = json.loads(chunk[5:].strip("\n"))
        output = data["text"].strip()
        print(output[prev:], end="", flush=True)
        prev = len(output)
print("")
```

Detailed example in [openai compatible api](https://docs.sglang.io/docs/basic_usage/openai_api_completions.md).

### Multimodal

Launch a server:

```bash Command theme={null}
python3 -m sglang.launch_server --model-path lmms-lab/llava-onevision-qwen2-7b-ov
```

Download an image:

```bash Command theme={null}
curl -o example_image.png -L https://github.com/sgl-project/sglang/blob/main/examples/assets/example_image.png?raw=true
```

Send a request:

```python Example theme={null}
import requests

response = requests.post(
    "http://localhost:30000/generate",
    json={
        "text": "<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n"
                "<|im_start|>user\n<image>\nDescribe this image in a very short sentence.<|im_end|>\n"
                "<|im_start|>assistant\n",
        "image_data": "example_image.png",
        "sampling_params": {
            "temperature": 0,
            "max_new_tokens": 32,
        },
    },
)
print(response.json())
```

The `image_data` can be a file name, a URL, or a base64 encoded string. See also `python/sglang/srt/utils.py:load_image`.

Streaming is supported in a similar manner as [above](#streaming).

Detailed example in [OpenAI API Vision](https://docs.sglang.io/docs/basic_usage/openai_api_vision.md).

### Structured Outputs (JSON, Regex, EBNF)

You can specify a JSON schema, regular expression or [EBNF](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form) to constrain the model output. The model output will be guaranteed to follow the given constraints. Only one constraint parameter (`json_schema`, `regex`, or `ebnf`) can be specified for a request.

SGLang supports two grammar backends:

* [XGrammar](https://github.com/mlc-ai/xgrammar) (default): Supports JSON schema, regular expression, and EBNF constraints.
  * XGrammar currently uses the [GGML BNF format](https://github.com/ggml-org/llama.cpp/blob/master/grammars/README.md).
* [Outlines](https://github.com/dottxt-ai/outlines): Supports JSON schema and regular expression constraints.

If instead you want to initialize the Outlines backend, you can use `--grammar-backend outlines` flag:

```bash Command theme={null}
python -m sglang.launch_server --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \
--port 30000 --host 0.0.0.0 --grammar-backend [xgrammar|outlines] # xgrammar or outlines (default: xgrammar)
```

```python Example theme={null}
import json
import requests

json_schema = json.dumps({
    "type": "object",
    "properties": {
        "name": {"type": "string", "pattern": "^[\\w]+$"},
        "population": {"type": "integer"},
    },
    "required": ["name", "population"],
})

# JSON (works with both Outlines and XGrammar)
response = requests.post(
    "http://localhost:30000/generate",
    json={
        "text": "Here is the information of the capital of France in the JSON format.\n",
        "sampling_params": {
            "temperature": 0,
            "max_new_tokens": 64,
            "json_schema": json_schema,
        },
    },
)
print(response.json())

# Regular expression (Outlines backend only)
response = requests.post(
    "http://localhost:30000/generate",
    json={
        "text": "Paris is the capital of",
        "sampling_params": {
            "temperature": 0,
            "max_new_tokens": 64,
            "regex": "(France|England)",
        },
    },
)
print(response.json())

# EBNF (XGrammar backend only)
response = requests.post(
    "http://localhost:30000/generate",
    json={
        "text": "Write a greeting.",
        "sampling_params": {
            "temperature": 0,
            "max_new_tokens": 64,
            "ebnf": 'root ::= "Hello" | "Hi" | "Hey"',
        },
    },
)
print(response.json())
```

Detailed example in [structured outputs](https://docs.sglang.io/docs/advanced_features/structured_outputs.md).

### Custom logit processor

Launch a server with `--enable-custom-logit-processor` flag on.

```bash Command theme={null}
python -m sglang.launch_server \
  --model-path meta-llama/Meta-Llama-3-8B-Instruct \
  --port 30000 \
  --enable-custom-logit-processor
```

Define a custom logit processor that will always sample a specific token id.

```python Example theme={null}
from sglang.srt.sampling.custom_logit_processor import CustomLogitProcessor

class DeterministicLogitProcessor(CustomLogitProcessor):
    """A dummy logit processor that changes the logits to always
    sample the given token id.
    """

    def __call__(self, logits, custom_param_list):
        # Check that the number of logits matches the number of custom parameters
        assert logits.shape[0] == len(custom_param_list)
        key = "token_id"

        for i, param_dict in enumerate(custom_param_list):
            # Mask all other tokens
            logits[i, :] = -float("inf")
            # Assign highest probability to the specified token
            logits[i, param_dict[key]] = 0.0
        return logits
```

Send a request:

```python Example theme={null}
import requests

response = requests.post(
    "http://localhost:30000/generate",
    json={
        "text": "The capital of France is",
        "custom_logit_processor": DeterministicLogitProcessor().to_str(),
        "sampling_params": {
            "temperature": 0.0,
            "max_new_tokens": 32,
            "custom_params": {"token_id": 5},
        },
    },
)
print(response.json())
```

Send an OpenAI chat completion request:

```python Example theme={null}
import openai
from sglang.utils import print_highlight

client = openai.Client(base_url="http://127.0.0.1:30000/v1", api_key="None")

response = client.chat.completions.create(
    model="meta-llama/Meta-Llama-3-8B-Instruct",
    messages=[
        {"role": "user", "content": "List 3 countries and their capitals."},
    ],
    temperature=0.0,
    max_tokens=32,
    extra_body={
        "custom_logit_processor": DeterministicLogitProcessor().to_str(),
        "custom_params": {"token_id": 5},
    },
)

print_highlight(f"Response: {response}")
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.