> ## 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.

# Qwen4-35B-A3B

> Deploy Qwen4-35B-A3B with SGLang — day-0 recipes for Qwen's next-generation hybrid GDN + QSA Mixture-of-Experts model on NVIDIA, AMD, PPU, and local devices.

## Deployment

> [accordion] Install SGLang
>
> For all methods and hardware platforms, see the [official SGLang installation guide](https://docs.sglang.io/docs/get-started/install.md). The **Python** and **Docker** tabs match the toggle in the command panel; Zhenwu PPU runs the **Python** command inside the SAIL container.
>
> > [tab] Python (source)
> >
> > Qwen4 support is not in an SGLang release yet. Install from the pull-request branch:
> >
> > ```bash Command theme={null}
> > git clone https://github.com/sgl-project/sglang.git
> > cd sglang
> > git fetch origin pull/<PR_NUMBER>/head:qwen4
> > git checkout qwen4
> > pip install --upgrade pip
> > pip install -e "python"
> > ```
> >
> > Then run the **Python** output of the command panel below in that environment.
>
> > [tab] Docker
> >
> > ```bash NVIDIA theme={null}
> > docker pull lmsysorg/sglang:qwen4
> > ```
> >
> > ```bash AMD (MI350X / MI355X) theme={null}
> > docker pull lmsysorg/sglang-rocm:v0.5.23-rocm10-mi35x-qwen4
> > ```
> >
> > For how to launch the image, see [Install → Method 3: Using Docker](https://docs.sglang.io/docs/get-started/install.md#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces.
>
> > [tab] PPU (M890 / 810E)
> >
> > Use the PPU image `egslingjun-registry.cn-wulanchabu.cr.aliyuncs.com/egslingjun-tmp/sglang:sail-qwen4-35b-a3b-ppu2.2.1` with a prepared [SAIL environment](https://docs.sglang.io/docs/hardware-platforms/sail.md), and run the command panel's **Python** output inside the container.

Pick your hardware, checkpoint precision, and strategy to generate a single-node launch command. NVIDIA, AMD, and Zhenwu PPU recipes cover the BF16 and FP8 checkpoints (Zhenwu PPU FP8 is currently unverified), and NVFP4 recipes cover data-center Blackwell, DGX Spark, and the RTX cards. **Strategy** selects speculative decoding: **None**, **MTP** (the in-checkpoint multi-token-prediction head), or **DFlash2** (block-diffusion draft `RadixArk/Qwen4-35B-A3B-Dflash2`). With **NVFP4**, the [RTX PRO 6000 recipes](#nvfp4-on-rtx-pro-6000) keep all weights on the GPU, and the [desktop RTX 5090 recipes](#nvfp4-on-rtx-5090) keep all experts on the GPU while offloading only the PLE table to host RAM.

For a system with 16 GB of VRAM and 64 GB of host RAM, see the [experimental paged experts recipe](#paged-experts-16gb).

## Playground

The Deploy panel shows the verification status of the selected recipe. Use the Playground to try additional SGLang features with that configuration.

## 1. Model Introduction

**Qwen4-35B-A3B** is a model from Qwen4, the next generation of the Qwen model family. It continues the hybrid architecture line previewed by [Qwen3.8-Flash-Next](https://docs.sglang.io/cookbook/autoregressive/Qwen/Qwen3.8-Flash-Next.md): Gated DeltaNet (GDN) linear attention interleaved with full attention using Qwen Sparse Attention (QSA), hyper-connections, n-gram embeddings, and in-checkpoint multi-token prediction (MTP) layers.

<table>
  <colgroup>
    <col />

    <col />

    <col />
  </colgroup>

  <thead>
    <tr>
      <th>Variant</th>
      <th>Total / active params</th>
      <th>Architecture</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>**[Qwen4-35B-A3B](https://huggingface.co/Qwen/Qwen4-35B-A3B)**</td>
      <td>35B / \~3B</td>
      <td>MoE, 256 routed experts (top-8) plus a shared expert</td>
    </tr>

    <tr>
      <td>**[Qwen4-35B-A3B-FP8](https://huggingface.co/Qwen/Qwen4-35B-A3B-FP8)**</td>
      <td>35B / \~3B</td>
      <td>FP8 checkpoint of Qwen4-35B-A3B</td>
    </tr>

    <tr>
      <td>**[RadixArk/Qwen4-35B-A3B-NVFP4](https://huggingface.co/RadixArk/Qwen4-35B-A3B-NVFP4)**</td>
      <td>35B / \~3B</td>
      <td>NVFP4 checkpoint of Qwen4-35B-A3B (NVFP4 routed experts + FP8 PLE)</td>
    </tr>
  </tbody>
</table>

The approximate checkpoint weight sizes, including the PLE embedding table, are **106 GiB for BF16**, **56 GiB for FP8**, and **44 GiB for NVFP4**. The amount that occupies VRAM depends on where you place the experts and PLE. Allow additional memory for the KV cache, runtime workspaces, and any separate draft model.

**Architecture details:** 40 layers with a 3:1 GDN / full-attention cadence, QSA on the full-attention layers (indexer budget 2048, compress ratio 4), hyper-connections (4 streams), head dimension 256, and MoE intermediate size 512.

**Context length:** up to 1,048,576 tokens natively. Set `--context-length` lower to cap it when your workload does not need the full window.

**License:** Apache 2.0.

**Supported platforms:** NVIDIA H200, B200, B300, and GB300; AMD MI350X and MI355X; Zhenwu PPU M890 and 810E; and the local devices DGX Spark, RTX PRO 6000, and RTX 5090.

**Recommended generation:** follow the sampling defaults in the checkpoint's `generation_config.json`; leave sampling unset in requests to inherit them.

**Resources:** HuggingFace — [BF16](https://huggingface.co/Qwen/Qwen4-35B-A3B), [FP8](https://huggingface.co/Qwen/Qwen4-35B-A3B-FP8), [NVFP4](https://huggingface.co/RadixArk/Qwen4-35B-A3B-NVFP4), [DFlash2 draft](https://huggingface.co/RadixArk/Qwen4-35B-A3B-Dflash2).

## 2. Configuration Tips

### 2.1 BF16 and FP8 on NVIDIA H200 / B200 / B300 / GB300 / RTX PRO 6000

* **QSA indexer.** `--qsa-indexer-dtype fp8_e4m3` stores the compressed QSA indexer cache in FP8 and scores blocks with FP8 GEMMs. It requires CUDA SM90, SM100, or SM12x; the main KV cache is unaffected.
* **GDN backends.** `--linear-attn-prefill-backend flashinfer` and `--linear-attn-decode-backend flashinfer` run the Gated DeltaNet layers on FlashInfer; `--mamba-ssm-dtype bfloat16` keeps the recurrent state in BF16.
* **Speculative decoding.** **MTP** uses the in-checkpoint MTP head through `--speculative-algorithm NEXTN` (3 steps / top-k 1 / 4 draft tokens); **DFlash2** uses `RadixArk/Qwen4-35B-A3B-Dflash2` (`block_size=8`, `--speculative-draft-kv-cache-dtype bf16`, `--speculative-use-block-verification`); **None** runs without speculative decoding.

### 2.2 NVIDIA DGX Spark (GB10)

* **Unified memory sizing.** DGX Spark shares a single 128 GB unified memory pool between GPU allocations and the offloaded n-gram PLE table.
  * **BF16** (\~106 GiB total weights including the \~38 GiB PLE table) adds `--ple-offload-backend file` to map the sparse PLE table from local NVMe (with an 8 GiB resident-set cap) alongside `--mem-fraction-static 0.70`.
  * **FP8** (\~56 GiB total weights including the \~19 GiB PLE table) keeps PLE in unified memory with `--mem-fraction-static 0.60` for **None** / **MTP** and `--mem-fraction-static 0.65` for **DFlash2** (leaving \~29 GiB free RAM headroom).
  * **NVFP4** (\~44 GiB total weights including the \~19 GiB PLE table) passes `--no-ple-offload-embedding` to keep PLE directly in GPU memory alongside `--mem-fraction-static 0.65` across **None**, **MTP**, and **DFlash2** (\~27–31 GiB free RAM headroom).
* **Same QSA / GDN / speculative stack.** All quantizations use `--qsa-indexer-dtype fp8_e4m3`, FlashInfer GDN prefill/decode with `--mamba-ssm-dtype bfloat16`, optional NEXTN `3/1/4` MTP, and (for FP8 and NVFP4) optional DFlash2 (`block_size=8`, `--speculative-draft-kv-cache-dtype bf16`, `--speculative-use-block-verification`).

### 2.3 AMD MI350X / MI355X

* **AITER stack.** The recipe sets `SGLANG_USE_AITER=1`, `SGLANG_USE_AITER_UNIFIED_ATTN=1`, `AITER_FLYDSL_FORCE=1`, and `AITER_ONLINE_TUNE=0`, plus `--attention-backend aiter` and `--linear-attn-verify-backend aiter`, so both the full-attention and GDN verify paths run on AITER. `SGLANG_MAMBA_SSM_DTYPE=bfloat16` keeps the GDN recurrent state in BF16.
* **Tuned MoE / FlyDSL tables.** If you have a tuned AITER fused-MoE table and a precompiled FlyDSL cache for this checkpoint's BF16 MoE shape, point `AITER_CONFIG_FMOE` and `FLYDSL_RUNTIME_CACHE_DIR` at them. Without them, AITER falls back to its online defaults, which can pick slightly different MoE GEMM kernels.
* **Serving limits.** The recipe sets `--max-running-requests 32` with a matching CUDA-graph decode batch of 32, disables the radix cache, and caps the context at 262,144 tokens. Drop `--disable-radix-cache` if your workload reuses prefixes.
* **Working directory.** A working directory that contains an `aiter/` or `sglang/` checkout shadows the installed packages. Start the server from an empty directory such as `/tmp`.
* **Speculative decoding.** The recipe ships with the **MTP** strategy only, using the in-checkpoint MTP head through `--speculative-algorithm EAGLE` (3 steps / top-k 1 / 4 draft tokens).

### 2.4 Zhenwu PPU (M890 / 810E)

* **Container & SAIL environment.** Run inside `egslingjun-registry.cn-wulanchabu.cr.aliyuncs.com/egslingjun-tmp/sglang:sail-qwen4-35b-a3b-ppu2.2.1` on a host with a prepared [SAIL environment](https://docs.sglang.io/docs/hardware-platforms/sail.md). Both M890 and 810E share the same single-device (`--tp-size 1`) launch command for `Qwen/Qwen4-35B-A3B` (BF16) and `Qwen/Qwen4-35B-A3B-FP8` (FP8, currently unverified).
* **Runtime environment & backends.** `SGLANG_JIT_DEEPGEMM_PRECOMPILE=0` and `SGLANG_SAIL_PLA_CUDA=1` configure the SAIL runtime; `--attention-backend fa3` selects the attention backend and `--reasoning-parser auto` enables reasoning parsing.
* **Speculative decoding.** The recipe ships with the **MTP** strategy only, using the in-checkpoint MTP head through `--speculative-algorithm NEXTN` (3 steps / top-k 1 / 4 draft tokens).
* **Accuracy.** Verified on `Qwen/Qwen4-35B-A3B` (BF16) with GSM8K 5-shot at temperature 0: **96.51%** on both M890 and 810E.

### 2.5 NVFP4 and DFlash2 on RTX PRO 6000

On a 96 GB RTX PRO 6000 Blackwell, keep all NVFP4 experts and the FP8 PLE embedding table on the GPU (`--no-ple-offload-embedding`, `--mem-fraction-static 0.85`, `--chunked-prefill-size 8192`). All three NVFP4 strategies (**None**, **MTP**, and **DFlash2**) and **FP8 + DFlash2** use FlashInfer GDN (`--linear-attn-prefill-backend flashinfer`, `--linear-attn-decode-backend flashinfer`), `--qsa-indexer-dtype fp8_e4m3`, radix cache enabled, and full decode CUDA graphs; both DFlash2 cells enable `--speculative-use-block-verification`.

On SM12x, SGLang auto-selects **Marlin** for ModelOpt NVFP4 routed experts (NVFP4 weights, BF16 activations), which delivers the highest single-request and DFlash2 decode throughput (320.3 tok/s at `temp=0.6` `c=1`, 1,167.8 tok/s at `c=8`, and 1,757.2 tok/s at `c=32` on ShareGPT with NVFP4 + DFlash2). For long-prompt TTFT (-9 to 10% at 8K input) or high-concurrency NEXTN (`c=32`), you can pass `--moe-runner-backend flashinfer_cutlass` to run W4A4 NVFP4 activations as well as weights.

### 2.6 NVFP4 on RTX 5090 (32 GB)

RTX 5090 (32 GB) serves the **NVFP4** checkpoint (`RadixArk/Qwen4-35B-A3B-NVFP4`) across **None**, **MTP**, and **DFlash2** (BF16 and FP8 weights do not fit in 32 GB VRAM and are disabled). All routed experts stay on the GPU while only the FP8 PLE embedding table is offloaded to host RAM (`--ple-offload-embedding`, \~25 GiB host RAM required; allow extra host RAM for startup and the OS).

* **None** and **DFlash2** (with `--speculative-use-block-verification`) run with `--mem-fraction-static 0.90`, `--max-total-tokens 32768`, and radix cache enabled (`~27.9–29.6 GiB` VRAM).
* **MTP** with FlashInfer GDN + NEXTN `3/1/4` peaks at `~28.8 GiB` VRAM and sets `--mem-fraction-static 0.93 --disable-radix-cache --max-total-tokens 16384 --max-running-requests 4 --cuda-graph-max-bs-decode 4`.

### 2.7 NVFP4 throughput with 8K input and 1K output

Each row below uses the NVFP4 checkpoint on one GPU with Triton attention/GDN backends (`c=1`, NEXTN 3/1/4). After one full-length warmup, each configuration served the same ten synthetic prompts one at a time. The SGLang benchmark used `--dataset-name random-ids --tokenize-prompt --random-input-len 8192 --random-output-len 1024 --random-range-ratio 1 --num-prompts 10 --max-concurrency 1 --seed 42`. Each timed request used 8,192 input tokens and generated 1,024 output tokens. On the PRO 6000, the measured command also ran its default 32-output-token warmup before timing.

<table>
  <colgroup>
    <col />

    <col />

    <col />

    <col />

    <col />

    <col />

    <col />
  </colgroup>

  <thead>
    <tr>
      <th>GPU</th>
      <th>PLE placement</th>
      <th>End-to-end output (tok/s)</th>
      <th>Accept length (tokens/step)</th>
      <th>Median decode (tok/s)</th>
      <th>Median TTFT (s)</th>
      <th>Peak VRAM (GiB)</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>RTX PRO 6000 (96 GB)</td>
      <td>GPU</td>
      <td>204.17</td>
      <td>3.49</td>
      <td>400.91</td>
      <td>2.096</td>
      <td>46.89</td>
    </tr>

    <tr>
      <td>RTX PRO 6000 (96 GB)</td>
      <td>Host RAM</td>
      <td>199.75</td>
      <td>3.37</td>
      <td>381.53</td>
      <td>2.094</td>
      <td>27.86</td>
    </tr>

    <tr>
      <td>Desktop RTX 5090 (32 GB)</td>
      <td>Host RAM</td>
      <td>248.74</td>
      <td>3.30</td>
      <td>—</td>
      <td>1.381</td>
      <td>27.72</td>
    </tr>
  </tbody>
</table>

End-to-end output throughput divides 10,240 generated tokens by total elapsed time, including prefill. Median decode speed measures generation after the first streamed token for each request. Accept length is the stock SGLang benchmark’s `Accept length` field, the average number of output tokens advanced per speculative verification step, including the target token. It uses the server’s cumulative reported counters, which can include warmup. The RTX 5090 benchmark also reported a median time per output token of **2.25 ms**. The synthetic prompts often produced repetitive output, which can affect speculative decoding speed.

### 2.8 Paged experts on a 16 GB GPU (Experimental)

In the **Local Devices** row, select [16 GB GPU (Experimental)](#hw=gpu-16gb\&variant=35b-a3b\&quant=nvfp4\&strategy=mtp) to get the NVFP4 MTP command. The target is one NVIDIA GPU with 16 GB of VRAM and a system with 64 GB of host RAM. The FP8 QSA indexer in this command requires CUDA SM90, SM100, or SM120. The installation also needs Marlin for NVFP4 experts and FlashInfer for GDN prefill and decode. Validation on a physical 16 GB GPU is pending.

The command keeps 30 of 256 routed experts per layer on the GPU. The backing store for the experts has a 24 GiB host RAM budget. The PLE embedding, the rest of the server, and the OS also use host RAM. One request can use up to 16,384 tokens of KV cache. NEXTN `3/1/4` can route four verification positions to as many as 32 distinct experts per layer. Disabling the decode CUDA graph lets SGLang load them in multiple passes through the 30 GPU slots.

**Preliminary performance.** On one 96 GB RTX PRO 6000, an earlier NVFP4 checkpoint with the same 30 resident experts reached **101.62 tok/s median decode** after the first output chunk. Three warmed requests each used 17–18 input tokens and generated 160 tokens. GPU memory peaked at **11.86 GiB** during those requests, and the server process tree used **43.53 GiB of host RAM** after warmup (proportional set size). This run used one NEXTN step (`1/1/2`), a BF16 QSA indexer, and Triton GDN.

## 3. Advanced Usage

> [!NOTE]
>
> The `model` argument in the examples below is the BF16 repo id. Each precision is a **separate repo**, so `model` has to be the checkpoint the server was actually launched with (for example `Qwen/Qwen4-35B-A3B-FP8`). The Deploy panel's cURL snippet always shows the right id for the cell you have selected.

### 3.1 Reasoning

Qwen4-35B-A3B **thinks by default** (`reasoning_effort=high`, `preserve_thinking` on). Launch with `--trust-remote-code` and `--reasoning-parser qwen4` (toggle **Reasoning Parser** in the **Parsers** card of the [Playground above](#playground)) to separate thinking into `reasoning_content`; `--reasoning-parser auto` resolves to the same parser for Qwen4 checkpoints.

**Why `qwen4` and not `qwen3` / `qwen3-thinking`.** Qwen4-35B-A3B needs its own parser:

* `</think>` is a special token in Qwen4's tokenizer. The `qwen4` parser keeps special tokens in the decoded output (`skip_special_tokens=False` is applied for you), so the end of the thinking block is never stripped before parsing.
* The generation prompt already opens the thinking block, so the output never opens one itself. The model may also judge a task simple enough to skip thinking and emit `</think>` right away; the answer then lands in `content` and `reasoning_content` is empty.
* Only `</think>` ends the thinking. A literal `<tool_call>` or `<think>` written inside the reasoning stays reasoning text instead of closing it early.

**Reasoning effort.** Set the depth per request with the top-level `reasoning_effort` field, or with `"chat_template_kwargs": {"reasoning_effort": ...}`. Qwen4-35B-A3B defines four levels, and the OpenAI-compatible tiers are mapped onto them:

<table>
  <colgroup>
    <col />

    <col />

    <col />
  </colgroup>

  <thead>
    <tr>
      <th>Qwen4 level</th>
      <th>Meaning</th>
      <th>Also accepted as</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>`xhigh`</td>
      <td>Complex tasks where quality matters most</td>
      <td>`max`, `ultra`</td>
    </tr>

    <tr>
      <td>`high`</td>
      <td>Common tasks (default)</td>
      <td>`medium`</td>
    </tr>

    <tr>
      <td>`low`</td>
      <td>Fast responses with minimal thinking</td>
      <td>`minimal`</td>
    </tr>

    <tr>
      <td>`off`</td>
      <td>Thinking disabled</td>
      <td>`none`</td>
    </tr>
  </tbody>
</table>

**Disabling thinking.** Any of these turns thinking off for a request: `reasoning_effort="off"`, `"chat_template_kwargs": {"enable_thinking": false}`, or `"thinking": {"type": "disabled"}`. Use one of them per request. If a request does combine them, the inputs are resolved rather than ranked: a top-level `thinking` only fills `chat_template_kwargs.enable_thinking` when the request did not set it there (so `"thinking": {"type": "disabled"}` does not override an explicit `enable_thinking: true`), and server defaults from `--default-chat-template-kwargs` only fill what the request leaves unset. The resolved `enable_thinking` is then checked against a `reasoning_effort` given in `chat_template_kwargs`, and a contradictory pair — one that resolves to `enable_thinking: false` with `reasoning_effort: "high"`, for example — is rejected with an error, whether both were written there or the toggle was filled from a top-level field. With no effort in `chat_template_kwargs`, a resolved `enable_thinking: false` turns thinking off even if a top-level `reasoning_effort` tier is also sent.

**Preserving thinking across turns.** `preserve_thinking` defaults to `true`, so the thinking of earlier assistant turns is carried forward in the prompt, which is what multi-turn agentic workloads want. Send the previous assistant turn back with its reasoning — `reasoning_content` on Chat Completions, `thinking` blocks on the Anthropic-compatible `/v1/messages` — and it is rendered as that turn's thinking block. Set `"chat_template_kwargs": {"preserve_thinking": false}` to opt out of carrying historical thinking forward; SGLang passes the flag to the tokenizer unchanged.

> [accordion] Reasoning Example (Python)
>
> ```python Example theme={null}
> from openai import OpenAI
>
> client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY")
> messages = [{"role": "user", "content": "What is 15% of 240?"}]
>
> # Thinking mode (default). reasoning_effort: "xhigh" | "high" (default) | "low" | "off"
> resp = client.chat.completions.create(
>     model="Qwen/Qwen4-35B-A3B",
>     messages=messages,
>     reasoning_effort="high",
>     temperature=1.0,
>     top_p=0.95,
>     presence_penalty=0.0,
>     extra_body={
>         "top_k": 20,
>         "chat_template_kwargs": {"preserve_thinking": True},  # on by default
>     },
> )
> msg = resp.choices[0].message
> print("Reasoning:", getattr(msg, "reasoning_content", None))
> print("Answer:", msg.content)
>
> # Multi-turn: send the reasoning back so it is preserved in the next prompt.
> messages.append(
>     {
>         "role": "assistant",
>         "content": msg.content,
>         "reasoning_content": getattr(msg, "reasoning_content", None),
>     }
> )
> messages.append({"role": "user", "content": "And 15% of 360?"})
>
> # Non-thinking mode: the whole output is the answer.
> resp = client.chat.completions.create(
>     model="Qwen/Qwen4-35B-A3B",
>     messages=messages,
>     reasoning_effort="off",  # same as chat_template_kwargs={"enable_thinking": False}
>     temperature=0.7,
>     top_p=0.8,
>     presence_penalty=1.5,
>     extra_body={"top_k": 20},
> )
> print("Answer:", resp.choices[0].message.content)
> ```

> [accordion] Example Output
>
> ```text Output theme={null}
> Pending update...
> ```

> [!NOTE]
>
> **Tokenizer.** The checkpoint ships a native `Qwen4Tokenizer`, loaded with `--trust-remote-code`, and it is the recommended path: prompts are built directly in token space, so control-token text typed inside a message (for example a literal `<think>`) stays ordinary text and can never become a control token. A conventional Jinja chat template is also provided under `tokenizer-compat/` for backward compatibility only; it is intended to render the same text apart from a few documented exceptions (tool results are only reordered to match the call order when every result in a run is text-only and carries a matching `tool_call_id`; runs with media or missing/unknown ids keep their input order, and there is no fallback to a legacy `id` field), and even where the text matches, the resulting token ids can differ. See the tokenizer README in the model repository for details. When serving with that template, `--reasoning-parser auto` / `qwen4` and `--tool-call-parser auto` / `qwen4` still resolve to the Qwen4 parsers and keep `</think>` intact.

### 3.2 Tool Calling

Launch with `--tool-call-parser qwen4` alongside `--reasoning-parser qwen4` and `--trust-remote-code` (toggle **Tool Call Parser** in the **Parsers** card of the [Playground above](#playground)) to surface structured tool calls via `message.tool_calls`; `--tool-call-parser auto` resolves to the same parser for Qwen4 checkpoints.

The dedicated `qwen4` tool-call parser reads Qwen4's native XML call format:

```text Format theme={null}
<tool_call>
<function=NAME>
<parameter=KEY>
VALUE
</parameter>
</function>
</tool_call>
```

* **Streaming and non-streaming parity.** One scanner serves both paths. Markers only count on their own line, so `<function=...>`, `<parameter=...>`, or `</tool_call>` appearing in prose or inside a parameter value (for example an XML snippet in a code string) stay text. A call is emitted whole once its closing lines arrive.
* **Schema-aware arguments.** Each parameter value is decoded with its JSON Schema in view, including type unions, `enum` / `const`, `anyOf` / `oneOf` / `allOf`, and local `$ref`. A pure `type: "string"` parameter keeps its wire text verbatim, so the literal string `"null"` or `"123"` is not turned into `null` or a number. For a function that is not strict, a value that does not parse to its declared type is returned as the raw string rather than rejected; validation against the schema is only guaranteed for strict tools (below).
* **`tool_choice` and parallel calls.** `"auto"`, `"none"`, `"required"`, and a named function are supported, along with multiple calls in one turn (`parallel_tool_calls`). `"required"` and named choices are enforced with an XGrammar structural tag written for Qwen4's own format, so constrained calls look exactly like unconstrained ones: zero-argument calls have no blank line, and parameters need not follow the schema's order.
* **Strict tools.** With `"strict": true` on a function, the same grammar also applies under `tool_choice="auto"`: each required parameter is written exactly once, values follow the schema, and a call is only returned when its decoded arguments validate against that schema. Parameters may come in any order while the grammar stays within its size budget; for larger schemas (many required parameters) the grammar falls back to the schema's declaration order.
* **Fail-closed on broken calls.** A closing-tag slip that can be recovered without losing anything — a missing `</parameter>` line, or a misspelled one such as `</parameter1>` — is repaired and the call is returned. An unclosed or otherwise unrecoverable `<tool_call>` block is never returned as a tool call and never leaks as raw markup into `content`. If the output was cut by `max_tokens`, the response keeps `finish_reason="length"` and the content before the call. If the model ended the turn itself, the request fails with a typed error — `incomplete_tool_call` or `malformed_tool_call` (HTTP 500, or an error event when streaming) — instead of silently returning a turn with no call, so clients can retry.

With thinking on (the default), a generation that stops inside the reasoning block — for example at the `max_tokens` cap — leaves `content` empty and puts the partial reasoning in `reasoning_content`. Print both so a bare `None` doesn't mislead you.

> [accordion] Tool Calling Example (Python)
>
> ```python Example theme={null}
> import json
>
> from openai import OpenAI
>
> client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY")
>
> tools = [
>     {
>         "type": "function",
>         "function": {
>             "name": "get_weather",
>             "description": "Get the current weather for a location",
>             "strict": True,  # optional: enforce the schema on the generated call
>             "parameters": {
>                 "type": "object",
>                 "properties": {
>                     "location": {"type": "string", "description": "The city name"},
>                     "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
>                 },
>                 "required": ["location"],
>                 "additionalProperties": False,
>             },
>         },
>     }
> ]
> sampling = dict(
>     temperature=1.0,
>     top_p=0.95,
>     presence_penalty=0.0,
>     extra_body={"top_k": 20},
> )
> messages = [{"role": "user", "content": "What's the weather in Beijing?"}]
>
> resp = client.chat.completions.create(
>     model="Qwen/Qwen4-35B-A3B",
>     messages=messages,
>     tools=tools,
>     tool_choice="auto",  # "auto" | "required" | "none" | {"type": "function", "function": {"name": "get_weather"}}
>     **sampling,
> )
> msg = resp.choices[0].message
> print("Reasoning:", getattr(msg, "reasoning_content", None))
> print("Content:", repr(msg.content))
> print("Tool calls:", [
>     (tc.function.name, tc.function.arguments)
>     for tc in (msg.tool_calls or [])
> ])
>
> # Run the tools, then return the results together with the assistant turn
> # (including its reasoning, so preserve_thinking can keep it).
> if msg.tool_calls:
>     messages.append(
>         {
>             "role": "assistant",
>             "content": msg.content,
>             "reasoning_content": getattr(msg, "reasoning_content", None),
>             "tool_calls": [tc.model_dump() for tc in msg.tool_calls],
>         }
>     )
>     for tc in msg.tool_calls:
>         args = json.loads(tc.function.arguments)
>         result = {"location": args["location"], "temperature": 22, "unit": "celsius"}  # your tool here
>         messages.append(
>             {"role": "tool", "tool_call_id": tc.id, "content": json.dumps(result)}
>         )
>     final = client.chat.completions.create(
>         model="Qwen/Qwen4-35B-A3B", messages=messages, tools=tools, **sampling
>     )
>     print("Answer:", final.choices[0].message.content)
> ```

> [accordion] Example Output
>
> ```text Output theme={null}
> Pending update...
> ```

### 3.3 Recommended Sampling Parameters

The Qwen team recommends different sampling settings for the two modes:

<table>
  <colgroup>
    <col />

    <col />

    <col />
  </colgroup>

  <thead>
    <tr>
      <th>Parameter</th>
      <th>Thinking (default)</th>
      <th>Non-thinking\
      `reasoning_effort="off"`</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>`temperature`</td>
      <td>1.0</td>
      <td>0.7</td>
    </tr>

    <tr>
      <td>`top_p`</td>
      <td>0.95</td>
      <td>0.80</td>
    </tr>

    <tr>
      <td>`top_k`</td>
      <td>20</td>
      <td>20</td>
    </tr>

    <tr>
      <td>`min_p`</td>
      <td>0.0</td>
      <td>0.0</td>
    </tr>

    <tr>
      <td>`presence_penalty`</td>
      <td>0.0</td>
      <td>1.5</td>
    </tr>

    <tr>
      <td>`repetition_penalty`</td>
      <td>1.0</td>
      <td>1.0</td>
    </tr>
  </tbody>
</table>

* `temperature`, `top_p`, and `presence_penalty` are standard Chat Completions fields. `top_k`, `min_p`, and `repetition_penalty` are SGLang extensions; with the OpenAI Python SDK, pass them through `extra_body`, for example `extra_body={"top_k": 20}`.
* `presence_penalty` can be adjusted between 0 and 2 to reduce endless repetition; higher values may occasionally cause language mixing and a slight drop in quality.
* Leave enough output budget for agentic tasks: thinking tokens and the final answer both count toward `max_tokens`.
* In multi-turn agentic tasks, a lower `reasoning_effort` does not always reduce total completion time: faster turns can come with more failures and retries.

> [accordion] Sampling Example (Python)
>
> ```python Example theme={null}
> resp = client.chat.completions.create(
>     model="Qwen/Qwen4-35B-A3B",
>     messages=[{"role": "user", "content": "Write a Python function to merge two sorted linked lists."}],
>     temperature=1.0,
>     top_p=0.95,
>     presence_penalty=0.0,
>     extra_body={"top_k": 20, "min_p": 0.0, "repetition_penalty": 1.0},
> )
> ```

> [accordion] Example Output
>
> ```text Output theme={null}
> Pending update...
> ```


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