Text Generation
MLX
Safetensors
qwen3_next
apple-silicon
quantized
mixed-precision
axquant
axq
development
qwen3-next
MXFP4
conversational
4-bit precision
Instructions to use AutomatosX/AX-Qwen3-Coder-Next-MLX-AXQ-MXFP4 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MLX
How to use AutomatosX/AX-Qwen3-Coder-Next-MLX-AXQ-MXFP4 with MLX:
# Make sure mlx-lm is installed # pip install --upgrade mlx-lm # Generate text with mlx-lm from mlx_lm import load, generate model, tokenizer = load("AutomatosX/AX-Qwen3-Coder-Next-MLX-AXQ-MXFP4") prompt = "Write a story about Einstein" messages = [{"role": "user", "content": prompt}] prompt = tokenizer.apply_chat_template( messages, add_generation_prompt=True ) text = generate(model, tokenizer, prompt=prompt, verbose=True) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- LM Studio
- Pi
How to use AutomatosX/AX-Qwen3-Coder-Next-MLX-AXQ-MXFP4 with Pi:
Start the MLX server
# Install MLX LM: uv tool install mlx-lm # Start a local OpenAI-compatible server: mlx_lm.server --model "AutomatosX/AX-Qwen3-Coder-Next-MLX-AXQ-MXFP4"
Configure the model in Pi
# Install Pi: npm install -g @mariozechner/pi-coding-agent # Add to ~/.pi/agent/models.json: { "providers": { "mlx-lm": { "baseUrl": "http://localhost:8080/v1", "api": "openai-completions", "apiKey": "none", "models": [ { "id": "AutomatosX/AX-Qwen3-Coder-Next-MLX-AXQ-MXFP4" } ] } } }Run Pi
# Start Pi in your project directory: pi
- MLX LM
How to use AutomatosX/AX-Qwen3-Coder-Next-MLX-AXQ-MXFP4 with MLX LM:
Generate or start a chat session
# Install MLX LM uv tool install mlx-lm # Interactive chat REPL mlx_lm.chat --model "AutomatosX/AX-Qwen3-Coder-Next-MLX-AXQ-MXFP4"
Run an OpenAI-compatible server
# Install MLX LM uv tool install mlx-lm # Start the server mlx_lm.server --model "AutomatosX/AX-Qwen3-Coder-Next-MLX-AXQ-MXFP4" # Calling the OpenAI-compatible server with curl curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "AutomatosX/AX-Qwen3-Coder-Next-MLX-AXQ-MXFP4", "messages": [ {"role": "user", "content": "Hello"} ] }' - Hermes Agent
How to use AutomatosX/AX-Qwen3-Coder-Next-MLX-AXQ-MXFP4 with Hermes Agent:
Start the MLX server
# Install MLX LM: uv tool install mlx-lm # Start a local OpenAI-compatible server: mlx_lm.server --model "AutomatosX/AX-Qwen3-Coder-Next-MLX-AXQ-MXFP4"
Configure Hermes
# Install Hermes: curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash hermes setup # Point Hermes at the local server: hermes config set model.provider custom hermes config set model.base_url http://127.0.0.1:8080/v1 hermes config set model.default AutomatosX/AX-Qwen3-Coder-Next-MLX-AXQ-MXFP4
Run Hermes
hermes
- Atomic Chat
- OpenClaw
How to use AutomatosX/AX-Qwen3-Coder-Next-MLX-AXQ-MXFP4 with OpenClaw:
Start the MLX server
# Install MLX LM: uv tool install mlx-lm # Start a local OpenAI-compatible server: mlx_lm.server --model "AutomatosX/AX-Qwen3-Coder-Next-MLX-AXQ-MXFP4"
Configure OpenClaw
# Install OpenClaw: npm install -g openclaw@latest # Register the local server and set it as the default model: openclaw onboard --non-interactive --mode local \ --auth-choice custom-api-key \ --custom-base-url http://127.0.0.1:8080/v1 \ --custom-model-id "AutomatosX/AX-Qwen3-Coder-Next-MLX-AXQ-MXFP4" \ --custom-provider-id mlx-lm \ --custom-compatibility openai \ --custom-text-input \ --accept-risk \ --skip-health
Run OpenClaw
openclaw agent --local --agent main --message "Hello from Hugging Face"
Publish AX-Qwen3-Coder-Next-MLX-AXQ-MXFP4 factory convert
Browse files- .gitattributes +3 -0
- README.md +184 -0
- axquant_manifest.json +231 -0
- axquant_plan.json +3 -0
- axquant_quantizer_execution.json +3 -0
- axquant_runtime.json +58 -0
- chat_template.jinja +117 -0
- config.json +0 -0
- generation_config.json +13 -0
- model-00001-of-00009.safetensors +3 -0
- model-00002-of-00009.safetensors +3 -0
- model-00003-of-00009.safetensors +3 -0
- model-00004-of-00009.safetensors +3 -0
- model-00005-of-00009.safetensors +3 -0
- model-00006-of-00009.safetensors +3 -0
- model-00007-of-00009.safetensors +3 -0
- model-00008-of-00009.safetensors +3 -0
- model-00009-of-00009.safetensors +3 -0
- model.safetensors.index.json +0 -0
- qwen3_coder_detector_sgl.py +474 -0
- qwen3coder_tool_parser_vllm.py +690 -0
- tokenizer.json +3 -0
- tokenizer_config.json +31 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
axquant_plan.json filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
axquant_quantizer_execution.json filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
library_name: mlx
|
| 4 |
+
base_model: Qwen/Qwen3-Coder-Next
|
| 5 |
+
base_model_relation: quantized
|
| 6 |
+
pipeline_tag: text-generation
|
| 7 |
+
tags:
|
| 8 |
+
- mlx
|
| 9 |
+
- apple-silicon
|
| 10 |
+
- quantized
|
| 11 |
+
- mixed-precision
|
| 12 |
+
- axquant
|
| 13 |
+
- axq
|
| 14 |
+
- development
|
| 15 |
+
- qwen3-next
|
| 16 |
+
- MXFP4
|
| 17 |
+
- MXFP4
|
| 18 |
+
---
|
| 19 |
+
|
| 20 |
+
# AX-Qwen3-Coder-Next-MLX-AXQ-MXFP4 — 4.32 BPW measured main
|
| 21 |
+
|
| 22 |
+
An **AXQuant (AXQ)** mixed-precision MLX checkpoint for Apple Silicon, converted directly from
|
| 23 |
+
the BF16 source model. The language path is quantized under AXQuant protection floors (embeddings, norms, and other protected tensors remain higher precision).
|
| 24 |
+
|
| 25 |
+
> **Checkpoint Tier 1 certified** on `df-macstudio-m2` (2026-08-18) for this exact
|
| 26 |
+
> revision — measured size against a matched uniform baseline, quality retention, and
|
| 27 |
+
> conversion integrity. Tier 1 is a checkpoint claim, **not** a speed claim: MTP
|
| 28 |
+
> acceleration is **not certified**; no MTP speedup claim for this checkpoint.
|
| 29 |
+
> See the [checkpoint Tier 1 certificate](https://github.com/defai-digital/axquant/blob/main/docs/certifications/qwen3-coder-next-axq-mxfp4-tier1.md) for the bound evidence and thresholds.
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
## Model details
|
| 33 |
+
|
| 34 |
+
| Property | Value |
|
| 35 |
+
| --- | --- |
|
| 36 |
+
| Base model | [Qwen/Qwen3-Coder-Next](https://huggingface.co/Qwen/Qwen3-Coder-Next/tree/a7fbcb5c0e12d62a448eaa0e260346bf5dcc0feb) |
|
| 37 |
+
| Source revision | `a7fbcb5c0e12d62a448eaa0e260346bf5dcc0feb` |
|
| 38 |
+
| Product family | `qwen3-next` |
|
| 39 |
+
| Source architecture | `Qwen3NextForCausalLM` (mixture of experts (MoE)); text path optimized |
|
| 40 |
+
| Main-model parameters | 79.67B logical parameters |
|
| 41 |
+
| Quantizer | AXQuant `1.9.0` |
|
| 42 |
+
| Hub budget class | `MXFP4` |
|
| 43 |
+
| AXQuant base precision class | `5p6bpw` |
|
| 44 |
+
| Planned storage-adjusted BPW | 5.0590 |
|
| 45 |
+
| Measured main-model BPW | 4.3154 |
|
| 46 |
+
| Measured total BPW | **4.3154** |
|
| 47 |
+
| Safetensors weight size | 42.98 GB |
|
| 48 |
+
| Approximate complete download | 43.08 GB |
|
| 49 |
+
| Configured maximum context | 262,144 tokens; practical limits depend on unified memory |
|
| 50 |
+
| Primary MLX runtime | MLX-LM |
|
| 51 |
+
| AX Engine native execution | Not established; no validated native manifest is included |
|
| 52 |
+
| MTP present | `False` |
|
| 53 |
+
| Vision present | `False` |
|
| 54 |
+
| Audio present | `False` |
|
| 55 |
+
|
| 56 |
+
This repository contains MLX Safetensors. It does **not** contain PyTorch or GGUF weights.
|
| 57 |
+
|
| 58 |
+
## Choosing an AXQ pack
|
| 59 |
+
|
| 60 |
+
AXQ names describe a **storage-budget product class**, not one uniform precision applied to every
|
| 61 |
+
tensor. Protected tensors remain at higher precision, so the exact measured BPW is authoritative.
|
| 62 |
+
In particular, a `6bit`-named mixed plan may retain `4bit` as its base precision while selecting
|
| 63 |
+
6-bit, 8-bit, or BF16 for other tensors to meet an approximately 6-BPW total budget. Protection
|
| 64 |
+
floors can also raise a `4bit`-named pack close to (or above) a `6bit` budget on small or heavily
|
| 65 |
+
protected models. When that collapse happens, AutomatosX does **not** publish a separate
|
| 66 |
+
misleading `4bit` sibling for that base.
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
| Sibling | Intended trade-off |
|
| 70 |
+
| --- | --- |
|
| 71 |
+
| [4bit sibling](https://huggingface.co/AutomatosX/AX-Qwen3-Coder-Next-MLX-AXQ-4bit) | Lower-storage AXQ budget; check its exact BPW |
|
| 72 |
+
| [6bit sibling](https://huggingface.co/AutomatosX/AX-Qwen3-Coder-Next-MLX-AXQ-6bit) | Higher average precision near the 6-BPW budget |
|
| 73 |
+
|
| 74 |
+
See the [AutomatosX collections](https://huggingface.co/AutomatosX/collections)
|
| 75 |
+
for the family catalog, or the [complete index](https://huggingface.co/collections/AutomatosX/automatosx-mlx-model-catalog).
|
| 76 |
+
|
| 77 |
+
## Download
|
| 78 |
+
|
| 79 |
+
```bash
|
| 80 |
+
python -m pip install -U huggingface_hub
|
| 81 |
+
hf download AutomatosX/AX-Qwen3-Coder-Next-MLX-AXQ-MXFP4 --local-dir ./AX-Qwen3-Coder-Next-MLX-AXQ-MXFP4
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
Allow at least 43.08 GB of free disk space. Pin the resulting Hub commit in reproducible
|
| 85 |
+
deployments rather than relying indefinitely on `main`.
|
| 86 |
+
|
| 87 |
+
## Run with MLX-LM
|
| 88 |
+
|
| 89 |
+
```bash
|
| 90 |
+
python -m pip install -U mlx-lm
|
| 91 |
+
mlx_lm.generate \
|
| 92 |
+
--model AutomatosX/AX-Qwen3-Coder-Next-MLX-AXQ-MXFP4 \
|
| 93 |
+
--prompt "Explain mixed-precision quantization in three sentences." \
|
| 94 |
+
--max-tokens 128 \
|
| 95 |
+
--temp 0.0
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
MLX-LM compatibility covers standard **text/backbone inference**. It may ignore AXQuant runtime
|
| 99 |
+
metadata and optional sidecars (`vision.safetensors`, `mtp.safetensors`); this command therefore
|
| 100 |
+
does not establish MTP acceleration or vision-language quality. The artifact records MLX
|
| 101 |
+
`0.32.0` and MLX-LM `0.31.3` from conversion.
|
| 102 |
+
|
| 103 |
+
## AX Engine status
|
| 104 |
+
|
| 105 |
+
This package does **not** include a validated native `model-manifest.json`, so AX Engine execution
|
| 106 |
+
is not established by this release. The AX Engine fields in `axquant_runtime.json` describe the
|
| 107 |
+
intended compatibility contract, not observed runtime evidence. Use the architecture-specific MLX
|
| 108 |
+
runtime path above. The artifact records AX Engine version
|
| 109 |
+
`not recorded`, but version discovery alone is not a runtime check.
|
| 110 |
+
|
| 111 |
+
## Quantization layout
|
| 112 |
+
|
| 113 |
+
| Main-weight precision | Parameters | Share |
|
| 114 |
+
| --- | ---: | ---: |
|
| 115 |
+
| `4bit` | 79.00B | 99.15% |
|
| 116 |
+
| `8bit` | 361.59M | 0.45% |
|
| 117 |
+
| `bf16` | 312.56M | 0.39% |
|
| 118 |
+
|
| 119 |
+
- Quantization methods: `affine, bf16`.
|
| 120 |
+
- Group sizes used by quantized assignments: `32, 64`.
|
| 121 |
+
- MTP sidecar: not included.
|
| 122 |
+
- Vision sidecar: not included.
|
| 123 |
+
- Optimization scope: `text-path`.
|
| 124 |
+
- Support tier: `convertible`.
|
| 125 |
+
|
| 126 |
+
BF16 sidecars, when present, are included in total download size. Their presence does not by itself
|
| 127 |
+
establish MTP acceleration or vision-language quality.
|
| 128 |
+
|
| 129 |
+
## Evidence and validation status
|
| 130 |
+
|
| 131 |
+
| Check | Status |
|
| 132 |
+
| --- | --- |
|
| 133 |
+
| Planning evidence | `architecture_prior` |
|
| 134 |
+
| Calibration | none; the allocation is based on architecture priors |
|
| 135 |
+
| Quantizer execution | 74125/74125 recorded module conversions succeeded; 0 fallbacks |
|
| 136 |
+
| AX Engine native manifest | not included |
|
| 137 |
+
| Quality versus BF16 or uniform baselines | Not published; no quality-retention claim |
|
| 138 |
+
| MTP acceptance and speed | **not certified**; no MTP speedup claim for this checkpoint (Qwen3-Coder-Next source declares no MTP; certification is non-MTP direct-decode checkpoint Tier 1 only (qwen3-next-direct track).) |
|
| 139 |
+
| AX Engine kernel evidence | `unmeasured` |
|
| 140 |
+
| Vision-language quality | Not applicable (vision disabled for this pack) |
|
| 141 |
+
| Speech-recognition quality | Not applicable (audio disabled for this pack) |
|
| 142 |
+
| Long-context quality | 262,144-token capacity is config metadata, not a validated claim |
|
| 143 |
+
| Release certification | **Checkpoint Tier 1 certified** on `df-macstudio-m2` (2026-08-18), Hub commit `000000000000`; the formal AXQuant M0-M8 release campaign is a separate process and is not implied |
|
| 144 |
+
|
| 145 |
+
## Modalities (capability-gated)
|
| 146 |
+
|
| 147 |
+
Text checkpoint Tier 1 does **not** imply vision or audio quality. `Vision present=true` on a pack is not a quality pass.
|
| 148 |
+
|
| 149 |
+
| Modality | Claim | Supported | Reason |
|
| 150 |
+
| --- | --- | --- | --- |
|
| 151 |
+
| Vision | `not-applicable` | `false` | vision not supported on this pack |
|
| 152 |
+
| Audio | `not-applicable` | `false` | audio not supported on this pack |
|
| 153 |
+
|
| 154 |
+
## Intended use and limitations
|
| 155 |
+
|
| 156 |
+
- Intended for local development and evaluation on Apple Silicon with MLX-compatible runtimes.
|
| 157 |
+
- No minimum unified-memory figure is claimed; loadability depends on model size, context length,
|
| 158 |
+
KV-cache policy, runtime buffers, and other processes using unified memory.
|
| 159 |
+
- Architecture-prior allocation is not measured sensitivity. It must not be presented as measured
|
| 160 |
+
model quality.
|
| 161 |
+
- The configured context window can require substantially more memory as the KV cache grows.
|
| 162 |
+
- AX Engine execution is not established because this package has no validated native manifest.
|
| 163 |
+
|
| 164 |
+
- Upstream capabilities, limitations, biases, and responsible-use guidance still apply.
|
| 165 |
+
|
| 166 |
+
## Provenance and audit files
|
| 167 |
+
|
| 168 |
+
- [`axquant_manifest.json`](axquant_manifest.json): package identity, byte accounting, runtime
|
| 169 |
+
contract, software versions, and file checksums.
|
| 170 |
+
- [`axquant_plan.json`](axquant_plan.json): per-tensor precision decisions and planning evidence.
|
| 171 |
+
- [`axquant_quantizer_execution.json`](axquant_quantizer_execution.json): conversion coverage and
|
| 172 |
+
fallback records.
|
| 173 |
+
- [`axquant_runtime.json`](axquant_runtime.json): declared AX Engine and MLX compatibility metadata; runtime checks remain separate evidence.
|
| 174 |
+
|
| 175 |
+
All published provenance uses repository-relative paths. Local source paths are stripped before
|
| 176 |
+
publication. The checkpoint was converted from BF16 rather than re-quantized from an OptiQ
|
| 177 |
+
artifact. If an OptiQ repository is published separately, it uses a different quantizer and
|
| 178 |
+
should not be assumed to have identical BPW or quality.
|
| 179 |
+
|
| 180 |
+
## License
|
| 181 |
+
|
| 182 |
+
The checkpoint follows the upstream model license where applicable (often Apache License 2.0). See
|
| 183 |
+
the [Qwen/Qwen3-Coder-Next model card](https://huggingface.co/Qwen/Qwen3-Coder-Next/tree/a7fbcb5c0e12d62a448eaa0e260346bf5dcc0feb)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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"axquant_version": "1.9.0",
|
| 3 |
+
"calibration": null,
|
| 4 |
+
"created_at": "2026-08-18T18:30:00.469669Z",
|
| 5 |
+
"effective_bpw": 5.059036550784871,
|
| 6 |
+
"files": [
|
| 7 |
+
{
|
| 8 |
+
"path": "README.md",
|
| 9 |
+
"sha256": "11e3eb7edd3b80c27700c00ab437368e0abdd4718d3109f8585abca977c6c74c",
|
| 10 |
+
"size_bytes": 8683
|
| 11 |
+
},
|
| 12 |
+
{
|
| 13 |
+
"path": "axquant_plan.json",
|
| 14 |
+
"sha256": "a83a02c5cec9f5065654fcdb071bf4d48ee74370ebbff2f8ac9377834866c65b",
|
| 15 |
+
"size_bytes": 67900706
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"path": "axquant_quantizer_execution.json",
|
| 19 |
+
"sha256": "a7b7024c8a74a126aeead3162b55f4b923939b474c4b88a170138b5584281414",
|
| 20 |
+
"size_bytes": 18745977
|
| 21 |
+
},
|
| 22 |
+
{
|
| 23 |
+
"path": "axquant_runtime.json",
|
| 24 |
+
"sha256": "06d0b8ad801cc8d8a7d4ed799848088fec2381c110cf98d1da5ae548b6bfb30d",
|
| 25 |
+
"size_bytes": 1628
|
| 26 |
+
},
|
| 27 |
+
{
|
| 28 |
+
"path": "chat_template.jinja",
|
| 29 |
+
"sha256": "c79a833039a43602150cce0902403d6e376c50930c1b2a139b2964e1f0c322a0",
|
| 30 |
+
"size_bytes": 6068
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"path": "config.json",
|
| 34 |
+
"sha256": "fc1e86652df25bc7dc455035a33dbd02c09deb91908ec2aad33f20e929dab6cf",
|
| 35 |
+
"size_bytes": 156950
|
| 36 |
+
},
|
| 37 |
+
{
|
| 38 |
+
"path": "generation_config.json",
|
| 39 |
+
"sha256": "37a3c1ef63516ca489c575f0db1c0405ddc0c3dbaca9ed987344c966c37aeef5",
|
| 40 |
+
"size_bytes": 214
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"path": "model-00001-of-00009.safetensors",
|
| 44 |
+
"sha256": "25e0609df75f20e2d00380d92950b49ee112de291234a77a96bc222d4c1e5f4e",
|
| 45 |
+
"size_bytes": 5298640091
|
| 46 |
+
},
|
| 47 |
+
{
|
| 48 |
+
"path": "model-00002-of-00009.safetensors",
|
| 49 |
+
"sha256": "3d6a034a16a0a9fc1681d0654620b7aaf86781bd4b50b2730905d5f51585f1e3",
|
| 50 |
+
"size_bytes": 5251437577
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"path": "model-00003-of-00009.safetensors",
|
| 54 |
+
"sha256": "1cac58ec604e6fa9255d6541f388056b3d505dca44c5d82c7b2f75d5267f1477",
|
| 55 |
+
"size_bytes": 5254914577
|
| 56 |
+
},
|
| 57 |
+
{
|
| 58 |
+
"path": "model-00004-of-00009.safetensors",
|
| 59 |
+
"sha256": "1f5d1903eed4f9b1785174a28f13cc870de4f765d2484ed4b84764b1371e9e51",
|
| 60 |
+
"size_bytes": 5251437678
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
"path": "model-00005-of-00009.safetensors",
|
| 64 |
+
"sha256": "25117fa9ceebe5dcd156850b540bc76da9d30c53bbbf2b367ae244ae302a861f",
|
| 65 |
+
"size_bytes": 5254914611
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"path": "model-00006-of-00009.safetensors",
|
| 69 |
+
"sha256": "b4f5a246c38f81d5cad012bac46de7cb2e9900a16dad48209677482216dfc303",
|
| 70 |
+
"size_bytes": 5251437708
|
| 71 |
+
},
|
| 72 |
+
{
|
| 73 |
+
"path": "model-00007-of-00009.safetensors",
|
| 74 |
+
"sha256": "625f136ddd98f53968cf4e34c217e3a95e36c32d9b593d236c0fad683e73aae6",
|
| 75 |
+
"size_bytes": 5254914607
|
| 76 |
+
},
|
| 77 |
+
{
|
| 78 |
+
"path": "model-00008-of-00009.safetensors",
|
| 79 |
+
"sha256": "74234c80e06ab56f4d8af0918e8a3cd41223e6b1bfa210f369488b7b6e74e30b",
|
| 80 |
+
"size_bytes": 5251437720
|
| 81 |
+
},
|
| 82 |
+
{
|
| 83 |
+
"path": "model-00009-of-00009.safetensors",
|
| 84 |
+
"sha256": "dfb10b70f81105971143f8d0ee3ae65fd435604e4d0b428d3df3cd0e77a45a52",
|
| 85 |
+
"size_bytes": 909221492
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"path": "model.safetensors.index.json",
|
| 89 |
+
"sha256": "7381ca01ebfa27aa1b45668f5bcc2c4bb2b6e53de49fd6763a04844c9cfd116a",
|
| 90 |
+
"size_bytes": 131598
|
| 91 |
+
},
|
| 92 |
+
{
|
| 93 |
+
"path": "qwen3_coder_detector_sgl.py",
|
| 94 |
+
"sha256": "e5a6112dd41df1580ede5f52e928e58cb74985dfa5628fd94073fd6a0f20fb8d",
|
| 95 |
+
"size_bytes": 19855
|
| 96 |
+
},
|
| 97 |
+
{
|
| 98 |
+
"path": "qwen3coder_tool_parser_vllm.py",
|
| 99 |
+
"sha256": "e6ad932aaa29a4004d592ca655c3d1ad849525a498ba60a716909ec9c1fda297",
|
| 100 |
+
"size_bytes": 31680
|
| 101 |
+
},
|
| 102 |
+
{
|
| 103 |
+
"path": "tokenizer.json",
|
| 104 |
+
"sha256": "be75606093db2094d7cd20f3c2f385c212750648bd6ea4fb2bf507a6a4c55506",
|
| 105 |
+
"size_bytes": 11422650
|
| 106 |
+
},
|
| 107 |
+
{
|
| 108 |
+
"path": "tokenizer_config.json",
|
| 109 |
+
"sha256": "23ff856b54c821dbd7e3fbcb9f33bd514f03a1ce194390d51bebae7de5a601be",
|
| 110 |
+
"size_bytes": 731
|
| 111 |
+
}
|
| 112 |
+
],
|
| 113 |
+
"format": "mlx",
|
| 114 |
+
"logical_parameters": 79674391296,
|
| 115 |
+
"main_logical_parameters": 79674391296,
|
| 116 |
+
"main_weight_file_size_bytes": 42978356061,
|
| 117 |
+
"measured_main_bpw": 4.31539975260861,
|
| 118 |
+
"measured_total_bpw": 4.31539975260861,
|
| 119 |
+
"mtp_acceptance_retention": null,
|
| 120 |
+
"mtp_distribution": {},
|
| 121 |
+
"mtp_measured_speedup": null,
|
| 122 |
+
"mtp_policy": {
|
| 123 |
+
"candidate_bits": [
|
| 124 |
+
8,
|
| 125 |
+
16
|
| 126 |
+
],
|
| 127 |
+
"min_bits": 8,
|
| 128 |
+
"mode": "protected",
|
| 129 |
+
"optimize_for_acceptance": true,
|
| 130 |
+
"preserve_external_sidecar": true,
|
| 131 |
+
"protect_norms": true,
|
| 132 |
+
"protect_output_head": true
|
| 133 |
+
},
|
| 134 |
+
"mtp_present": false,
|
| 135 |
+
"mtp_weight_file_size_bytes": 0,
|
| 136 |
+
"plan_sha256": "02567ac858019017a3421bcf536f3b748a1491abd64cd8416bda2942568023f1",
|
| 137 |
+
"profile": "agent-coding",
|
| 138 |
+
"protected_weight_file_size_bytes": 0,
|
| 139 |
+
"quantizer": "axquant",
|
| 140 |
+
"runtime": {
|
| 141 |
+
"ax_engine": {
|
| 142 |
+
"decode_kernel": null,
|
| 143 |
+
"fused_mtp": null,
|
| 144 |
+
"kernel_evidence": "unmeasured",
|
| 145 |
+
"model_manifest": "model-manifest.json",
|
| 146 |
+
"preferred_group_size": 32
|
| 147 |
+
},
|
| 148 |
+
"compatible_runtimes": [
|
| 149 |
+
{
|
| 150 |
+
"compatibility_level": "B",
|
| 151 |
+
"manifest": "config.json",
|
| 152 |
+
"mtp_support": "none",
|
| 153 |
+
"name": "mlx-lm",
|
| 154 |
+
"notes": [
|
| 155 |
+
"Standard backbone inference is the compatibility target.",
|
| 156 |
+
"AXQuant MTP metadata may be ignored by MLX-LM."
|
| 157 |
+
],
|
| 158 |
+
"standard_inference": true,
|
| 159 |
+
"standard_mlx_weights": true,
|
| 160 |
+
"support_level": "standard-inference"
|
| 161 |
+
}
|
| 162 |
+
],
|
| 163 |
+
"created_at": "2026-08-18T18:27:54.487021Z",
|
| 164 |
+
"kv_cache": null,
|
| 165 |
+
"memory_policy": {
|
| 166 |
+
"kv_cache_precision": "runtime-default",
|
| 167 |
+
"mtp_buffers": "not-required",
|
| 168 |
+
"prefix_cache": "runtime-managed",
|
| 169 |
+
"unified_memory_safety_margin": "benchmark-required"
|
| 170 |
+
},
|
| 171 |
+
"mtp": {
|
| 172 |
+
"acceptance_retention": null,
|
| 173 |
+
"detected": false,
|
| 174 |
+
"draft_tokens": null,
|
| 175 |
+
"enabled_by_default": false,
|
| 176 |
+
"head_precision": null,
|
| 177 |
+
"measured_speedup": null,
|
| 178 |
+
"optimized": false,
|
| 179 |
+
"recommended_temperature_max": null,
|
| 180 |
+
"sidecar_file": null,
|
| 181 |
+
"verification_mode": null
|
| 182 |
+
},
|
| 183 |
+
"optimization_scope": "text-path",
|
| 184 |
+
"primary_runtime": {
|
| 185 |
+
"compatibility_level": "A",
|
| 186 |
+
"manifest": "model-manifest.json",
|
| 187 |
+
"mtp_support": "none",
|
| 188 |
+
"name": "ax-engine",
|
| 189 |
+
"notes": [
|
| 190 |
+
"Runtime claims require a passing AX Engine doctor and benchmark report."
|
| 191 |
+
],
|
| 192 |
+
"standard_inference": true,
|
| 193 |
+
"standard_mlx_weights": true,
|
| 194 |
+
"support_level": "optimized"
|
| 195 |
+
},
|
| 196 |
+
"schema_version": "axquant.runtime.v1"
|
| 197 |
+
},
|
| 198 |
+
"schema_version": "axquant.artifact.v2",
|
| 199 |
+
"software_versions": {
|
| 200 |
+
"ax_engine": null,
|
| 201 |
+
"axquant": "1.9.0",
|
| 202 |
+
"mlx": "0.32.0",
|
| 203 |
+
"mlx_lm": "0.31.3",
|
| 204 |
+
"pydantic": "2.13.4",
|
| 205 |
+
"python": "3.12.13",
|
| 206 |
+
"safetensors": "0.8.0"
|
| 207 |
+
},
|
| 208 |
+
"source_model": {
|
| 209 |
+
"architecture": "Qwen3NextForCausalLM",
|
| 210 |
+
"format": "mlx",
|
| 211 |
+
"local_path": null,
|
| 212 |
+
"model_id": "Qwen/Qwen3-Coder-Next",
|
| 213 |
+
"revision": "a7fbcb5c0e12d62a448eaa0e260346bf5dcc0feb"
|
| 214 |
+
},
|
| 215 |
+
"target_class": "5p6bpw",
|
| 216 |
+
"weight_distribution": {
|
| 217 |
+
"4bit": {
|
| 218 |
+
"fraction": 0.9915386718739344,
|
| 219 |
+
"parameters": 79000240128
|
| 220 |
+
},
|
| 221 |
+
"8bit": {
|
| 222 |
+
"fraction": 0.0045384078135800405,
|
| 223 |
+
"parameters": 361594880
|
| 224 |
+
},
|
| 225 |
+
"bf16": {
|
| 226 |
+
"fraction": 0.003922920312485546,
|
| 227 |
+
"parameters": 312556288
|
| 228 |
+
}
|
| 229 |
+
},
|
| 230 |
+
"weight_file_size_bytes": 42978356061
|
| 231 |
+
}
|
axquant_plan.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a83a02c5cec9f5065654fcdb071bf4d48ee74370ebbff2f8ac9377834866c65b
|
| 3 |
+
size 67900706
|
axquant_quantizer_execution.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a7b7024c8a74a126aeead3162b55f4b923939b474c4b88a170138b5584281414
|
| 3 |
+
size 18745977
|
axquant_runtime.json
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"ax_engine": {
|
| 3 |
+
"decode_kernel": null,
|
| 4 |
+
"fused_mtp": null,
|
| 5 |
+
"kernel_evidence": "unmeasured",
|
| 6 |
+
"model_manifest": "model-manifest.json",
|
| 7 |
+
"preferred_group_size": 32
|
| 8 |
+
},
|
| 9 |
+
"compatible_runtimes": [
|
| 10 |
+
{
|
| 11 |
+
"compatibility_level": "B",
|
| 12 |
+
"manifest": "config.json",
|
| 13 |
+
"mtp_support": "none",
|
| 14 |
+
"name": "mlx-lm",
|
| 15 |
+
"notes": [
|
| 16 |
+
"Standard backbone inference is the compatibility target.",
|
| 17 |
+
"AXQuant MTP metadata may be ignored by MLX-LM."
|
| 18 |
+
],
|
| 19 |
+
"standard_inference": true,
|
| 20 |
+
"standard_mlx_weights": true,
|
| 21 |
+
"support_level": "standard-inference"
|
| 22 |
+
}
|
| 23 |
+
],
|
| 24 |
+
"created_at": "2026-08-18T18:27:54.487021Z",
|
| 25 |
+
"kv_cache": null,
|
| 26 |
+
"memory_policy": {
|
| 27 |
+
"kv_cache_precision": "runtime-default",
|
| 28 |
+
"mtp_buffers": "not-required",
|
| 29 |
+
"prefix_cache": "runtime-managed",
|
| 30 |
+
"unified_memory_safety_margin": "benchmark-required"
|
| 31 |
+
},
|
| 32 |
+
"mtp": {
|
| 33 |
+
"acceptance_retention": null,
|
| 34 |
+
"detected": false,
|
| 35 |
+
"draft_tokens": null,
|
| 36 |
+
"enabled_by_default": false,
|
| 37 |
+
"head_precision": null,
|
| 38 |
+
"measured_speedup": null,
|
| 39 |
+
"optimized": false,
|
| 40 |
+
"recommended_temperature_max": null,
|
| 41 |
+
"sidecar_file": null,
|
| 42 |
+
"verification_mode": null
|
| 43 |
+
},
|
| 44 |
+
"optimization_scope": "text-path",
|
| 45 |
+
"primary_runtime": {
|
| 46 |
+
"compatibility_level": "A",
|
| 47 |
+
"manifest": "model-manifest.json",
|
| 48 |
+
"mtp_support": "none",
|
| 49 |
+
"name": "ax-engine",
|
| 50 |
+
"notes": [
|
| 51 |
+
"Runtime claims require a passing AX Engine doctor and benchmark report."
|
| 52 |
+
],
|
| 53 |
+
"standard_inference": true,
|
| 54 |
+
"standard_mlx_weights": true,
|
| 55 |
+
"support_level": "optimized"
|
| 56 |
+
},
|
| 57 |
+
"schema_version": "axquant.runtime.v1"
|
| 58 |
+
}
|
chat_template.jinja
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{% macro render_extra_keys(json_dict, handled_keys) %}
|
| 2 |
+
{%- if json_dict is mapping %}
|
| 3 |
+
{%- for json_key in json_dict if json_key not in handled_keys %}
|
| 4 |
+
{%- if json_dict[json_key] is string %}
|
| 5 |
+
{{-'\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '</' ~ json_key ~ '>' }}
|
| 6 |
+
{%- else %}
|
| 7 |
+
{{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '</' ~ json_key ~ '>' }}
|
| 8 |
+
{%- endif %}
|
| 9 |
+
{%- endfor %}
|
| 10 |
+
{%- endif %}
|
| 11 |
+
{%- endmacro %}
|
| 12 |
+
|
| 13 |
+
{%- if messages[0]["role"] == "system" %}
|
| 14 |
+
{%- set system_message = messages[0]["content"] %}
|
| 15 |
+
{%- set loop_messages = messages[1:] %}
|
| 16 |
+
{%- else %}
|
| 17 |
+
{%- set loop_messages = messages %}
|
| 18 |
+
{%- endif %}
|
| 19 |
+
|
| 20 |
+
{%- if not tools is defined %}
|
| 21 |
+
{%- set tools = [] %}
|
| 22 |
+
{%- endif %}
|
| 23 |
+
|
| 24 |
+
{%- if system_message is defined %}
|
| 25 |
+
{{- "<|im_start|>system\n" + system_message }}
|
| 26 |
+
{%- else %}
|
| 27 |
+
{%- if tools is iterable and tools | length > 0 %}
|
| 28 |
+
{{- "<|im_start|>system\nYou are Qwen, a helpful AI assistant that can interact with a computer to solve tasks." }}
|
| 29 |
+
{%- endif %}
|
| 30 |
+
{%- endif %}
|
| 31 |
+
{%- if tools is iterable and tools | length > 0 %}
|
| 32 |
+
{{- "\n\n# Tools\n\nYou have access to the following functions:\n\n" }}
|
| 33 |
+
{{- "<tools>" }}
|
| 34 |
+
{%- for tool in tools %}
|
| 35 |
+
{%- if tool.function is defined %}
|
| 36 |
+
{%- set tool = tool.function %}
|
| 37 |
+
{%- endif %}
|
| 38 |
+
{{- "\n<function>\n<name>" ~ tool.name ~ "</name>" }}
|
| 39 |
+
{%- if tool.description is defined %}
|
| 40 |
+
{{- '\n<description>' ~ (tool.description | trim) ~ '</description>' }}
|
| 41 |
+
{%- endif %}
|
| 42 |
+
{{- '\n<parameters>' }}
|
| 43 |
+
{%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %}
|
| 44 |
+
{%- for param_name, param_fields in tool.parameters.properties|items %}
|
| 45 |
+
{{- '\n<parameter>' }}
|
| 46 |
+
{{- '\n<name>' ~ param_name ~ '</name>' }}
|
| 47 |
+
{%- if param_fields.type is defined %}
|
| 48 |
+
{{- '\n<type>' ~ (param_fields.type | string) ~ '</type>' }}
|
| 49 |
+
{%- endif %}
|
| 50 |
+
{%- if param_fields.description is defined %}
|
| 51 |
+
{{- '\n<description>' ~ (param_fields.description | trim) ~ '</description>' }}
|
| 52 |
+
{%- endif %}
|
| 53 |
+
{%- set handled_keys = ['name', 'type', 'description'] %}
|
| 54 |
+
{{- render_extra_keys(param_fields, handled_keys) }}
|
| 55 |
+
{{- '\n</parameter>' }}
|
| 56 |
+
{%- endfor %}
|
| 57 |
+
{%- endif %}
|
| 58 |
+
{%- set handled_keys = ['type', 'properties'] %}
|
| 59 |
+
{{- render_extra_keys(tool.parameters, handled_keys) }}
|
| 60 |
+
{{- '\n</parameters>' }}
|
| 61 |
+
{%- set handled_keys = ['type', 'name', 'description', 'parameters'] %}
|
| 62 |
+
{{- render_extra_keys(tool, handled_keys) }}
|
| 63 |
+
{{- '\n</function>' }}
|
| 64 |
+
{%- endfor %}
|
| 65 |
+
{{- "\n</tools>" }}
|
| 66 |
+
{{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
|
| 67 |
+
{%- endif %}
|
| 68 |
+
{%- if system_message is defined %}
|
| 69 |
+
{{- '<|im_end|>\n' }}
|
| 70 |
+
{%- else %}
|
| 71 |
+
{%- if tools is iterable and tools | length > 0 %}
|
| 72 |
+
{{- '<|im_end|>\n' }}
|
| 73 |
+
{%- endif %}
|
| 74 |
+
{%- endif %}
|
| 75 |
+
{%- for message in loop_messages %}
|
| 76 |
+
{%- if message.role == "assistant" and message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %}
|
| 77 |
+
{{- '<|im_start|>' + message.role }}
|
| 78 |
+
{%- if message.content is defined and message.content is string and message.content | trim | length > 0 %}
|
| 79 |
+
{{- '\n' + message.content | trim + '\n' }}
|
| 80 |
+
{%- endif %}
|
| 81 |
+
{%- for tool_call in message.tool_calls %}
|
| 82 |
+
{%- if tool_call.function is defined %}
|
| 83 |
+
{%- set tool_call = tool_call.function %}
|
| 84 |
+
{%- endif %}
|
| 85 |
+
{{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
|
| 86 |
+
{%- if tool_call.arguments is defined %}
|
| 87 |
+
{%- for args_name, args_value in tool_call.arguments|items %}
|
| 88 |
+
{{- '<parameter=' + args_name + '>\n' }}
|
| 89 |
+
{%- set args_value = args_value if args_value is string else args_value | tojson | safe %}
|
| 90 |
+
{{- args_value }}
|
| 91 |
+
{{- '\n</parameter>\n' }}
|
| 92 |
+
{%- endfor %}
|
| 93 |
+
{%- endif %}
|
| 94 |
+
{{- '</function>\n</tool_call>' }}
|
| 95 |
+
{%- endfor %}
|
| 96 |
+
{{- '<|im_end|>\n' }}
|
| 97 |
+
{%- elif message.role == "user" or message.role == "system" or message.role == "assistant" %}
|
| 98 |
+
{{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' + '\n' }}
|
| 99 |
+
{%- elif message.role == "tool" %}
|
| 100 |
+
{%- if loop.previtem and loop.previtem.role != "tool" %}
|
| 101 |
+
{{- '<|im_start|>user' }}
|
| 102 |
+
{%- endif %}
|
| 103 |
+
{{- '\n<tool_response>\n' }}
|
| 104 |
+
{{- message.content }}
|
| 105 |
+
{{- '\n</tool_response>' }}
|
| 106 |
+
{%- if not loop.last and loop.nextitem.role != "tool" %}
|
| 107 |
+
{{- '<|im_end|>\n' }}
|
| 108 |
+
{%- elif loop.last %}
|
| 109 |
+
{{- '<|im_end|>\n' }}
|
| 110 |
+
{%- endif %}
|
| 111 |
+
{%- else %}
|
| 112 |
+
{{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' }}
|
| 113 |
+
{%- endif %}
|
| 114 |
+
{%- endfor %}
|
| 115 |
+
{%- if add_generation_prompt %}
|
| 116 |
+
{{- '<|im_start|>assistant\n' }}
|
| 117 |
+
{%- endif %}
|
config.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
generation_config.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token_id": 151643,
|
| 3 |
+
"do_sample": true,
|
| 4 |
+
"eos_token_id": [
|
| 5 |
+
151645,
|
| 6 |
+
151643
|
| 7 |
+
],
|
| 8 |
+
"pad_token_id": 151643,
|
| 9 |
+
"temperature": 1.0,
|
| 10 |
+
"top_k": 40,
|
| 11 |
+
"top_p": 0.95,
|
| 12 |
+
"transformers_version": "4.57.3"
|
| 13 |
+
}
|
model-00001-of-00009.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:25e0609df75f20e2d00380d92950b49ee112de291234a77a96bc222d4c1e5f4e
|
| 3 |
+
size 5298640091
|
model-00002-of-00009.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3d6a034a16a0a9fc1681d0654620b7aaf86781bd4b50b2730905d5f51585f1e3
|
| 3 |
+
size 5251437577
|
model-00003-of-00009.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1cac58ec604e6fa9255d6541f388056b3d505dca44c5d82c7b2f75d5267f1477
|
| 3 |
+
size 5254914577
|
model-00004-of-00009.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1f5d1903eed4f9b1785174a28f13cc870de4f765d2484ed4b84764b1371e9e51
|
| 3 |
+
size 5251437678
|
model-00005-of-00009.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:25117fa9ceebe5dcd156850b540bc76da9d30c53bbbf2b367ae244ae302a861f
|
| 3 |
+
size 5254914611
|
model-00006-of-00009.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b4f5a246c38f81d5cad012bac46de7cb2e9900a16dad48209677482216dfc303
|
| 3 |
+
size 5251437708
|
model-00007-of-00009.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:625f136ddd98f53968cf4e34c217e3a95e36c32d9b593d236c0fad683e73aae6
|
| 3 |
+
size 5254914607
|
model-00008-of-00009.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:74234c80e06ab56f4d8af0918e8a3cd41223e6b1bfa210f369488b7b6e74e30b
|
| 3 |
+
size 5251437720
|
model-00009-of-00009.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:dfb10b70f81105971143f8d0ee3ae65fd435604e4d0b428d3df3cd0e77a45a52
|
| 3 |
+
size 909221492
|
model.safetensors.index.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
qwen3_coder_detector_sgl.py
ADDED
|
@@ -0,0 +1,474 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ast
|
| 2 |
+
import json
|
| 3 |
+
import logging
|
| 4 |
+
import re
|
| 5 |
+
from typing import Any, List, Optional
|
| 6 |
+
|
| 7 |
+
from sglang.srt.entrypoints.openai.protocol import Tool
|
| 8 |
+
from sglang.srt.function_call.base_format_detector import BaseFormatDetector
|
| 9 |
+
from sglang.srt.function_call.core_types import (
|
| 10 |
+
StreamingParseResult,
|
| 11 |
+
ToolCallItem,
|
| 12 |
+
_GetInfoFunc,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
logger = logging.getLogger(__name__)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class Qwen3CoderDetector(BaseFormatDetector):
|
| 19 |
+
def __init__(self):
|
| 20 |
+
super().__init__()
|
| 21 |
+
|
| 22 |
+
# Sentinel tokens
|
| 23 |
+
self.tool_call_start_token: str = "<tool_call>"
|
| 24 |
+
self.tool_call_end_token: str = "</tool_call>"
|
| 25 |
+
self.tool_call_prefix: str = "<function="
|
| 26 |
+
self.function_end_token: str = "</function>"
|
| 27 |
+
self.parameter_prefix: str = "<parameter="
|
| 28 |
+
self.parameter_end_token: str = "</parameter>"
|
| 29 |
+
|
| 30 |
+
# Regex for non-streaming fallback
|
| 31 |
+
self.tool_call_regex = re.compile(r"<tool_call>(.*?)</tool_call>", re.DOTALL)
|
| 32 |
+
self.tool_call_function_regex = re.compile(
|
| 33 |
+
r"<function=(.*?)</function>|<function=(.*)$", re.DOTALL
|
| 34 |
+
)
|
| 35 |
+
self.tool_call_parameter_regex = re.compile(
|
| 36 |
+
r"<parameter=(.*?)(?:</parameter>|(?=<parameter=)|(?=</function>)|$)",
|
| 37 |
+
re.DOTALL,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
# Streaming State
|
| 41 |
+
# Base class already initializes _buffer, we just use it directly
|
| 42 |
+
# No need to check with hasattr - we control the lifecycle through inheritance
|
| 43 |
+
|
| 44 |
+
# Index pointing to the next character to be processed in buffer
|
| 45 |
+
self.parsed_pos: int = 0
|
| 46 |
+
# Parameter count inside the current tool being processed, used to determine whether to add comma
|
| 47 |
+
self.current_tool_param_count: int = 0
|
| 48 |
+
# Flag indicating whether current tool has already sent '{'
|
| 49 |
+
self.json_started: bool = False
|
| 50 |
+
|
| 51 |
+
# [FIX] New state flag: mark whether inside tool_call structure block
|
| 52 |
+
self.is_inside_tool_call: bool = False
|
| 53 |
+
|
| 54 |
+
# Initialize attributes that were missing in the original PR
|
| 55 |
+
self.current_func_name: Optional[str] = None
|
| 56 |
+
|
| 57 |
+
def has_tool_call(self, text: str) -> bool:
|
| 58 |
+
return self.tool_call_start_token in text
|
| 59 |
+
|
| 60 |
+
def _get_arguments_config(
|
| 61 |
+
self, func_name: str, tools: Optional[list[Tool]]
|
| 62 |
+
) -> dict:
|
| 63 |
+
"""Extract argument configuration for a function."""
|
| 64 |
+
if tools is None:
|
| 65 |
+
return {}
|
| 66 |
+
for config in tools:
|
| 67 |
+
try:
|
| 68 |
+
config_type = config.type
|
| 69 |
+
config_function = config.function
|
| 70 |
+
config_function_name = config_function.name
|
| 71 |
+
except AttributeError:
|
| 72 |
+
continue
|
| 73 |
+
|
| 74 |
+
if config_type == "function" and config_function_name == func_name:
|
| 75 |
+
try:
|
| 76 |
+
params = config_function.parameters
|
| 77 |
+
except AttributeError:
|
| 78 |
+
return {}
|
| 79 |
+
|
| 80 |
+
if isinstance(params, dict) and "properties" in params:
|
| 81 |
+
return params["properties"]
|
| 82 |
+
elif isinstance(params, dict):
|
| 83 |
+
return params
|
| 84 |
+
else:
|
| 85 |
+
return {}
|
| 86 |
+
logger.warning(f"Tool '{func_name}' is not defined in the tools list.")
|
| 87 |
+
return {}
|
| 88 |
+
|
| 89 |
+
def _convert_param_value(
|
| 90 |
+
self, param_value: str, param_name: str, param_config: dict, func_name: str
|
| 91 |
+
) -> Any:
|
| 92 |
+
"""Convert parameter value based on its type in the schema."""
|
| 93 |
+
# Handle null value for any type
|
| 94 |
+
if param_value.lower() == "null":
|
| 95 |
+
return None
|
| 96 |
+
|
| 97 |
+
if param_name not in param_config:
|
| 98 |
+
if param_config != {}:
|
| 99 |
+
logger.warning(
|
| 100 |
+
f"Parsed parameter '{param_name}' is not defined in the tool "
|
| 101 |
+
f"parameters for tool '{func_name}', directly returning the string value."
|
| 102 |
+
)
|
| 103 |
+
return param_value
|
| 104 |
+
|
| 105 |
+
if (
|
| 106 |
+
isinstance(param_config[param_name], dict)
|
| 107 |
+
and "type" in param_config[param_name]
|
| 108 |
+
):
|
| 109 |
+
param_type = str(param_config[param_name]["type"]).strip().lower()
|
| 110 |
+
else:
|
| 111 |
+
param_type = "string"
|
| 112 |
+
if param_type in ["string", "str", "text", "varchar", "char", "enum"]:
|
| 113 |
+
return param_value
|
| 114 |
+
elif (
|
| 115 |
+
param_type.startswith("int")
|
| 116 |
+
or param_type.startswith("uint")
|
| 117 |
+
or param_type.startswith("long")
|
| 118 |
+
or param_type.startswith("short")
|
| 119 |
+
or param_type.startswith("unsigned")
|
| 120 |
+
):
|
| 121 |
+
try:
|
| 122 |
+
param_value = int(param_value)
|
| 123 |
+
except Exception:
|
| 124 |
+
logger.warning(
|
| 125 |
+
f"Parsed value '{param_value}' of parameter '{param_name}' is not an integer in tool "
|
| 126 |
+
f"'{func_name}', degenerating to string."
|
| 127 |
+
)
|
| 128 |
+
return param_value
|
| 129 |
+
elif param_type.startswith("num") or param_type.startswith("float"):
|
| 130 |
+
try:
|
| 131 |
+
maybe_convert = (
|
| 132 |
+
False if "." in param_value or "e" in param_value.lower() else True
|
| 133 |
+
)
|
| 134 |
+
param_value: float = float(param_value)
|
| 135 |
+
if maybe_convert and param_value.is_integer():
|
| 136 |
+
param_value = int(param_value)
|
| 137 |
+
except Exception:
|
| 138 |
+
logger.warning(
|
| 139 |
+
f"Parsed value '{param_value}' of parameter '{param_name}' is not a float in tool "
|
| 140 |
+
f"'{func_name}', degenerating to string."
|
| 141 |
+
)
|
| 142 |
+
return param_value
|
| 143 |
+
elif param_type in ["boolean", "bool", "binary"]:
|
| 144 |
+
param_value = param_value.lower()
|
| 145 |
+
if param_value not in ["true", "false"]:
|
| 146 |
+
logger.warning(
|
| 147 |
+
f"Parsed value '{param_value}' of parameter '{param_name}' is not a boolean (`true` of `false`) in tool '{func_name}', degenerating to false."
|
| 148 |
+
)
|
| 149 |
+
return param_value == "true"
|
| 150 |
+
else:
|
| 151 |
+
if (
|
| 152 |
+
param_type in ["object", "array", "arr"]
|
| 153 |
+
or param_type.startswith("dict")
|
| 154 |
+
or param_type.startswith("list")
|
| 155 |
+
):
|
| 156 |
+
try:
|
| 157 |
+
param_value = json.loads(param_value)
|
| 158 |
+
return param_value
|
| 159 |
+
except Exception:
|
| 160 |
+
logger.warning(
|
| 161 |
+
f"Parsed value '{param_value}' of parameter '{param_name}' cannot be parsed with json.loads in tool "
|
| 162 |
+
f"'{func_name}', will try other methods to parse it."
|
| 163 |
+
)
|
| 164 |
+
try:
|
| 165 |
+
param_value = ast.literal_eval(param_value) # safer
|
| 166 |
+
except Exception:
|
| 167 |
+
logger.warning(
|
| 168 |
+
f"Parsed value '{param_value}' of parameter '{param_name}' cannot be converted via Python `ast.literal_eval()` in tool '{func_name}', degenerating to string."
|
| 169 |
+
)
|
| 170 |
+
return param_value
|
| 171 |
+
|
| 172 |
+
def detect_and_parse(self, text: str, tools: List[Tool]) -> StreamingParseResult:
|
| 173 |
+
"""One-shot parsing for non-streaming scenarios."""
|
| 174 |
+
if self.tool_call_start_token not in text:
|
| 175 |
+
return StreamingParseResult(normal_text=text)
|
| 176 |
+
|
| 177 |
+
calls = []
|
| 178 |
+
try:
|
| 179 |
+
# Simple cleanup of the text to find tool calls
|
| 180 |
+
# Note: This is a simplified regex approach consistent with vLLM
|
| 181 |
+
raw_tool_calls = self.tool_call_regex.findall(text)
|
| 182 |
+
if not raw_tool_calls:
|
| 183 |
+
# Fallback: maybe the whole text is inside the tag or tags are stripped
|
| 184 |
+
if self.tool_call_prefix in text:
|
| 185 |
+
raw_tool_calls = [text]
|
| 186 |
+
|
| 187 |
+
tool_idx = 0
|
| 188 |
+
for tool_content in raw_tool_calls:
|
| 189 |
+
# Find function calls
|
| 190 |
+
funcs = self.tool_call_function_regex.findall(tool_content)
|
| 191 |
+
for func_match in funcs:
|
| 192 |
+
func_body = func_match[0] or func_match[1]
|
| 193 |
+
if ">" not in func_body:
|
| 194 |
+
continue
|
| 195 |
+
|
| 196 |
+
name_end = func_body.index(">")
|
| 197 |
+
func_name = func_body[:name_end]
|
| 198 |
+
params_str = func_body[name_end + 1 :]
|
| 199 |
+
|
| 200 |
+
param_config = self._get_arguments_config(func_name, tools)
|
| 201 |
+
parsed_params = {}
|
| 202 |
+
|
| 203 |
+
for p_match in self.tool_call_parameter_regex.findall(params_str):
|
| 204 |
+
if ">" not in p_match:
|
| 205 |
+
continue
|
| 206 |
+
p_idx = p_match.index(">")
|
| 207 |
+
p_name = p_match[:p_idx]
|
| 208 |
+
p_val = p_match[p_idx + 1 :]
|
| 209 |
+
# Remove prefixing and trailing \n
|
| 210 |
+
if p_val.startswith("\n"):
|
| 211 |
+
p_val = p_val[1:]
|
| 212 |
+
if p_val.endswith("\n"):
|
| 213 |
+
p_val = p_val[:-1]
|
| 214 |
+
|
| 215 |
+
parsed_params[p_name] = self._convert_param_value(
|
| 216 |
+
p_val, p_name, param_config, func_name
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
calls.append(
|
| 220 |
+
ToolCallItem(
|
| 221 |
+
tool_index=tool_idx,
|
| 222 |
+
name=func_name,
|
| 223 |
+
parameters=json.dumps(parsed_params, ensure_ascii=False),
|
| 224 |
+
)
|
| 225 |
+
)
|
| 226 |
+
tool_idx += 1
|
| 227 |
+
|
| 228 |
+
# Determine normal text (text before the first tool call)
|
| 229 |
+
start_idx = text.find(self.tool_call_start_token)
|
| 230 |
+
if start_idx == -1:
|
| 231 |
+
start_idx = text.find(self.tool_call_prefix)
|
| 232 |
+
normal_text = text[:start_idx] if start_idx > 0 else ""
|
| 233 |
+
|
| 234 |
+
return StreamingParseResult(normal_text=normal_text, calls=calls)
|
| 235 |
+
|
| 236 |
+
except Exception as e:
|
| 237 |
+
logger.error(f"Error in detect_and_parse: {e}")
|
| 238 |
+
return StreamingParseResult(normal_text=text)
|
| 239 |
+
|
| 240 |
+
def parse_streaming_increment(
|
| 241 |
+
self, new_text: str, tools: List[Tool]
|
| 242 |
+
) -> StreamingParseResult:
|
| 243 |
+
"""
|
| 244 |
+
Robust cursor-based streaming parser.
|
| 245 |
+
"""
|
| 246 |
+
self._buffer += new_text
|
| 247 |
+
|
| 248 |
+
# Guard against empty buffer
|
| 249 |
+
if not self._buffer:
|
| 250 |
+
return StreamingParseResult()
|
| 251 |
+
|
| 252 |
+
calls = []
|
| 253 |
+
normal_text_chunks = []
|
| 254 |
+
|
| 255 |
+
while True:
|
| 256 |
+
# Working text slice
|
| 257 |
+
current_slice = self._buffer[self.parsed_pos :]
|
| 258 |
+
|
| 259 |
+
# Optimization: If almost empty, wait for more
|
| 260 |
+
if not current_slice:
|
| 261 |
+
break
|
| 262 |
+
|
| 263 |
+
# -------------------------------------------------------
|
| 264 |
+
# 1. Priority detection: check if it's the start of Tool Call
|
| 265 |
+
# -------------------------------------------------------
|
| 266 |
+
if current_slice.startswith(self.tool_call_start_token):
|
| 267 |
+
self.parsed_pos += len(self.tool_call_start_token)
|
| 268 |
+
self.is_inside_tool_call = True
|
| 269 |
+
continue
|
| 270 |
+
|
| 271 |
+
# -------------------------------------------------------
|
| 272 |
+
# 2. Function Name: <function=name>
|
| 273 |
+
# -------------------------------------------------------
|
| 274 |
+
if current_slice.startswith(self.tool_call_prefix):
|
| 275 |
+
end_angle = current_slice.find(">")
|
| 276 |
+
if end_angle != -1:
|
| 277 |
+
func_name = current_slice[len(self.tool_call_prefix) : end_angle]
|
| 278 |
+
|
| 279 |
+
self.current_tool_id += 1
|
| 280 |
+
self.current_tool_name_sent = True
|
| 281 |
+
self.current_tool_param_count = 0
|
| 282 |
+
self.json_started = False
|
| 283 |
+
self.current_func_name = func_name
|
| 284 |
+
|
| 285 |
+
calls.append(
|
| 286 |
+
ToolCallItem(
|
| 287 |
+
tool_index=self.current_tool_id,
|
| 288 |
+
name=func_name,
|
| 289 |
+
parameters="",
|
| 290 |
+
)
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
self.parsed_pos += end_angle + 1
|
| 294 |
+
continue
|
| 295 |
+
else:
|
| 296 |
+
# Incomplete tag
|
| 297 |
+
break
|
| 298 |
+
|
| 299 |
+
# -------------------------------------------------------
|
| 300 |
+
# 3. Parameter: <parameter=name>value...
|
| 301 |
+
# -------------------------------------------------------
|
| 302 |
+
if current_slice.startswith(self.parameter_prefix):
|
| 303 |
+
name_end = current_slice.find(">")
|
| 304 |
+
if name_end != -1:
|
| 305 |
+
value_start_idx = name_end + 1
|
| 306 |
+
rest_of_slice = current_slice[value_start_idx:]
|
| 307 |
+
|
| 308 |
+
# A parameter can end in multiple ways:
|
| 309 |
+
# 1. [Normal] Encounter </parameter>
|
| 310 |
+
# 2. [Abnormal] Encounter next <parameter=
|
| 311 |
+
# 3. [Abnormal] Encounter </function>
|
| 312 |
+
# So we need to find the smallest one as the parameter end position.
|
| 313 |
+
cand_end_param = rest_of_slice.find(self.parameter_end_token)
|
| 314 |
+
cand_next_param = rest_of_slice.find(self.parameter_prefix)
|
| 315 |
+
cand_end_func = rest_of_slice.find(self.function_end_token)
|
| 316 |
+
|
| 317 |
+
candidates = []
|
| 318 |
+
if cand_end_param != -1:
|
| 319 |
+
candidates.append(
|
| 320 |
+
(cand_end_param, len(self.parameter_end_token))
|
| 321 |
+
)
|
| 322 |
+
if cand_next_param != -1:
|
| 323 |
+
candidates.append((cand_next_param, 0))
|
| 324 |
+
if cand_end_func != -1:
|
| 325 |
+
candidates.append((cand_end_func, 0))
|
| 326 |
+
|
| 327 |
+
if candidates:
|
| 328 |
+
best_cand = min(candidates, key=lambda x: x[0])
|
| 329 |
+
end_pos = best_cand[0]
|
| 330 |
+
end_token_len = best_cand[1]
|
| 331 |
+
|
| 332 |
+
param_name = current_slice[
|
| 333 |
+
len(self.parameter_prefix) : name_end
|
| 334 |
+
]
|
| 335 |
+
raw_value = rest_of_slice[:end_pos]
|
| 336 |
+
|
| 337 |
+
# Cleanup value
|
| 338 |
+
if raw_value.startswith("\n"):
|
| 339 |
+
raw_value = raw_value[1:]
|
| 340 |
+
if raw_value.endswith("\n"):
|
| 341 |
+
raw_value = raw_value[:-1]
|
| 342 |
+
|
| 343 |
+
# JSON Construction
|
| 344 |
+
if not self.json_started:
|
| 345 |
+
calls.append(
|
| 346 |
+
ToolCallItem(
|
| 347 |
+
tool_index=self.current_tool_id, parameters="{"
|
| 348 |
+
)
|
| 349 |
+
)
|
| 350 |
+
self.json_started = True
|
| 351 |
+
|
| 352 |
+
param_config = self._get_arguments_config(
|
| 353 |
+
self.current_func_name, tools
|
| 354 |
+
)
|
| 355 |
+
converted_val = self._convert_param_value(
|
| 356 |
+
raw_value, param_name, param_config, self.current_func_name
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
# Construct JSON fragment: "key": value
|
| 360 |
+
# Note: We must be careful with json.dumps to ensure valid JSON streaming
|
| 361 |
+
json_key_val = f"{json.dumps(param_name)}: {json.dumps(converted_val, ensure_ascii=False)}"
|
| 362 |
+
|
| 363 |
+
if self.current_tool_param_count > 0:
|
| 364 |
+
fragment = f", {json_key_val}"
|
| 365 |
+
else:
|
| 366 |
+
fragment = json_key_val
|
| 367 |
+
|
| 368 |
+
calls.append(
|
| 369 |
+
ToolCallItem(
|
| 370 |
+
tool_index=self.current_tool_id, parameters=fragment
|
| 371 |
+
)
|
| 372 |
+
)
|
| 373 |
+
self.current_tool_param_count += 1
|
| 374 |
+
|
| 375 |
+
# Advance cursor
|
| 376 |
+
total_len = (name_end + 1) + end_pos + end_token_len
|
| 377 |
+
self.parsed_pos += total_len
|
| 378 |
+
continue
|
| 379 |
+
|
| 380 |
+
# Incomplete parameter tag or value
|
| 381 |
+
break
|
| 382 |
+
|
| 383 |
+
# -------------------------------------------------------
|
| 384 |
+
# 4. Function End: </function>
|
| 385 |
+
# -------------------------------------------------------
|
| 386 |
+
if current_slice.startswith(self.function_end_token):
|
| 387 |
+
if not self.json_started:
|
| 388 |
+
calls.append(
|
| 389 |
+
ToolCallItem(tool_index=self.current_tool_id, parameters="{")
|
| 390 |
+
)
|
| 391 |
+
self.json_started = True
|
| 392 |
+
|
| 393 |
+
calls.append(
|
| 394 |
+
ToolCallItem(tool_index=self.current_tool_id, parameters="}")
|
| 395 |
+
)
|
| 396 |
+
self.parsed_pos += len(self.function_end_token)
|
| 397 |
+
self.current_func_name = None
|
| 398 |
+
continue
|
| 399 |
+
|
| 400 |
+
# -------------------------------------------------------
|
| 401 |
+
# 5. Tool Call End: </tool_call>
|
| 402 |
+
# -------------------------------------------------------
|
| 403 |
+
if current_slice.startswith(self.tool_call_end_token):
|
| 404 |
+
self.parsed_pos += len(self.tool_call_end_token)
|
| 405 |
+
self.is_inside_tool_call = False # [FIX] Exit tool call region
|
| 406 |
+
continue
|
| 407 |
+
|
| 408 |
+
# -------------------------------------------------------
|
| 409 |
+
# 6. Handling content / whitespace / normal text
|
| 410 |
+
# -------------------------------------------------------
|
| 411 |
+
# If current position is not the start of a tag (i.e., doesn't start with <), it might be plain text,
|
| 412 |
+
# or a newline between two tags.
|
| 413 |
+
# But we need to be careful not to output truncated tags like "<fun" as text.
|
| 414 |
+
|
| 415 |
+
next_open_angle = current_slice.find("<")
|
| 416 |
+
|
| 417 |
+
if next_open_angle == -1:
|
| 418 |
+
# This entire segment is plain text
|
| 419 |
+
if not self.is_inside_tool_call:
|
| 420 |
+
normal_text_chunks.append(current_slice)
|
| 421 |
+
# [FIX] If inside tool call, discard this text (usually \n), don't append
|
| 422 |
+
self.parsed_pos += len(current_slice)
|
| 423 |
+
continue
|
| 424 |
+
|
| 425 |
+
elif next_open_angle == 0:
|
| 426 |
+
# Looks like a Tag, but doesn't match any known Tag above
|
| 427 |
+
|
| 428 |
+
possible_tags = [
|
| 429 |
+
self.tool_call_start_token,
|
| 430 |
+
self.tool_call_end_token,
|
| 431 |
+
self.tool_call_prefix,
|
| 432 |
+
self.function_end_token,
|
| 433 |
+
self.parameter_prefix,
|
| 434 |
+
self.parameter_end_token,
|
| 435 |
+
]
|
| 436 |
+
|
| 437 |
+
is_potential_tag = False
|
| 438 |
+
for tag in possible_tags:
|
| 439 |
+
if tag.startswith(current_slice):
|
| 440 |
+
is_potential_tag = True
|
| 441 |
+
break
|
| 442 |
+
|
| 443 |
+
if is_potential_tag:
|
| 444 |
+
break # Wait for more
|
| 445 |
+
else:
|
| 446 |
+
# Just a plain '<' symbol
|
| 447 |
+
if not self.is_inside_tool_call:
|
| 448 |
+
normal_text_chunks.append("<")
|
| 449 |
+
self.parsed_pos += 1
|
| 450 |
+
continue
|
| 451 |
+
|
| 452 |
+
else:
|
| 453 |
+
# '<' is in the middle
|
| 454 |
+
text_segment = current_slice[:next_open_angle]
|
| 455 |
+
if not self.is_inside_tool_call:
|
| 456 |
+
normal_text_chunks.append(text_segment)
|
| 457 |
+
# [FIX] If inside tool call, discard whitespace/text before Tag
|
| 458 |
+
self.parsed_pos += next_open_angle
|
| 459 |
+
continue
|
| 460 |
+
|
| 461 |
+
# Memory Cleanup: Slice the buffer
|
| 462 |
+
# Keep unparsed part, discard parsed part
|
| 463 |
+
if self.parsed_pos > 0:
|
| 464 |
+
self._buffer = self._buffer[self.parsed_pos :]
|
| 465 |
+
self.parsed_pos = 0
|
| 466 |
+
|
| 467 |
+
normal_text = "".join(normal_text_chunks) if normal_text_chunks else ""
|
| 468 |
+
return StreamingParseResult(calls=calls, normal_text=normal_text)
|
| 469 |
+
|
| 470 |
+
def supports_structural_tag(self) -> bool:
|
| 471 |
+
return False
|
| 472 |
+
|
| 473 |
+
def structure_info(self) -> _GetInfoFunc:
|
| 474 |
+
raise NotImplementedError
|
qwen3coder_tool_parser_vllm.py
ADDED
|
@@ -0,0 +1,690 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
| 3 |
+
import ast
|
| 4 |
+
import json
|
| 5 |
+
import uuid
|
| 6 |
+
from collections.abc import Sequence
|
| 7 |
+
from typing import Any, List, Optional, Union
|
| 8 |
+
|
| 9 |
+
import regex as re
|
| 10 |
+
|
| 11 |
+
from vllm.entrypoints.openai.protocol import (ChatCompletionRequest,
|
| 12 |
+
ChatCompletionToolsParam,
|
| 13 |
+
DeltaFunctionCall, DeltaMessage,
|
| 14 |
+
DeltaToolCall,
|
| 15 |
+
ExtractedToolCallInformation,
|
| 16 |
+
FunctionCall, ToolCall)
|
| 17 |
+
from vllm.entrypoints.openai.tool_parsers.abstract_tool_parser import (
|
| 18 |
+
ToolParser, ToolParserManager)
|
| 19 |
+
from vllm.logger import init_logger
|
| 20 |
+
from vllm.transformers_utils.tokenizer import AnyTokenizer
|
| 21 |
+
|
| 22 |
+
logger = init_logger(__name__)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@ToolParserManager.register_module("qwen3_coder")
|
| 26 |
+
class Qwen3CoderToolParser(ToolParser):
|
| 27 |
+
|
| 28 |
+
def __init__(self, tokenizer: AnyTokenizer):
|
| 29 |
+
super().__init__(tokenizer)
|
| 30 |
+
|
| 31 |
+
self.current_tool_name_sent: bool = False
|
| 32 |
+
self.prev_tool_call_arr: list[dict] = []
|
| 33 |
+
self.current_tool_id: int = -1
|
| 34 |
+
self.streamed_args_for_tool: list[str] = []
|
| 35 |
+
|
| 36 |
+
# Sentinel tokens for streaming mode
|
| 37 |
+
self.tool_call_start_token: str = "<tool_call>"
|
| 38 |
+
self.tool_call_end_token: str = "</tool_call>"
|
| 39 |
+
self.tool_call_prefix: str = "<function="
|
| 40 |
+
self.function_end_token: str = "</function>"
|
| 41 |
+
self.parameter_prefix: str = "<parameter="
|
| 42 |
+
self.parameter_end_token: str = "</parameter>"
|
| 43 |
+
self.is_tool_call_started: bool = False
|
| 44 |
+
self.failed_count: int = 0
|
| 45 |
+
|
| 46 |
+
# Enhanced streaming state - reset for each new message
|
| 47 |
+
self._reset_streaming_state()
|
| 48 |
+
|
| 49 |
+
# Regex patterns
|
| 50 |
+
self.tool_call_complete_regex = re.compile(
|
| 51 |
+
r"<tool_call>(.*?)</tool_call>", re.DOTALL)
|
| 52 |
+
self.tool_call_regex = re.compile(
|
| 53 |
+
r"<tool_call>(.*?)</tool_call>|<tool_call>(.*?)$", re.DOTALL)
|
| 54 |
+
self.tool_call_function_regex = re.compile(
|
| 55 |
+
r"<function=(.*?)</function>|<function=(.*)$", re.DOTALL)
|
| 56 |
+
self.tool_call_parameter_regex = re.compile(
|
| 57 |
+
r"<parameter=(.*?)(?:</parameter>|(?=<parameter=)|(?=</function>)|$)",
|
| 58 |
+
re.DOTALL)
|
| 59 |
+
|
| 60 |
+
if not self.model_tokenizer:
|
| 61 |
+
raise ValueError(
|
| 62 |
+
"The model tokenizer must be passed to the ToolParser "
|
| 63 |
+
"constructor during construction.")
|
| 64 |
+
|
| 65 |
+
self.tool_call_start_token_id = self.vocab.get(
|
| 66 |
+
self.tool_call_start_token)
|
| 67 |
+
self.tool_call_end_token_id = self.vocab.get(self.tool_call_end_token)
|
| 68 |
+
|
| 69 |
+
if self.tool_call_start_token_id is None or self.tool_call_end_token_id is None:
|
| 70 |
+
raise RuntimeError(
|
| 71 |
+
"Qwen3 XML Tool parser could not locate tool call start/end "
|
| 72 |
+
"tokens in the tokenizer!")
|
| 73 |
+
|
| 74 |
+
logger.info(
|
| 75 |
+
f"vLLM Successfully import tool parser {self.__class__.__name__} !"
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
def _generate_tool_call_id(self) -> str:
|
| 79 |
+
"""Generate a unique tool call ID."""
|
| 80 |
+
return f"call_{uuid.uuid4().hex[:24]}"
|
| 81 |
+
|
| 82 |
+
def _reset_streaming_state(self):
|
| 83 |
+
"""Reset all streaming state."""
|
| 84 |
+
self.current_tool_index = 0
|
| 85 |
+
self.is_tool_call_started = False
|
| 86 |
+
self.header_sent = False
|
| 87 |
+
self.current_tool_id = None
|
| 88 |
+
self.current_function_name = None
|
| 89 |
+
self.current_param_name = None
|
| 90 |
+
self.current_param_value = ""
|
| 91 |
+
self.param_count = 0
|
| 92 |
+
self.in_param = False
|
| 93 |
+
self.in_function = False
|
| 94 |
+
self.accumulated_text = ""
|
| 95 |
+
self.json_started = False
|
| 96 |
+
self.json_closed = False
|
| 97 |
+
# Store accumulated parameters for type conversion
|
| 98 |
+
self.accumulated_params = {}
|
| 99 |
+
self.streaming_request = None
|
| 100 |
+
|
| 101 |
+
def _get_arguments_config(
|
| 102 |
+
self, func_name: str,
|
| 103 |
+
tools: Optional[list[ChatCompletionToolsParam]]) -> dict:
|
| 104 |
+
"""Extract argument configuration for a function."""
|
| 105 |
+
if tools is None:
|
| 106 |
+
return {}
|
| 107 |
+
for config in tools:
|
| 108 |
+
if not hasattr(config, "type") or not (hasattr(
|
| 109 |
+
config, "function") and hasattr(config.function, "name")):
|
| 110 |
+
continue
|
| 111 |
+
if config.type == "function" and config.function.name == func_name:
|
| 112 |
+
if not hasattr(config.function, "parameters"):
|
| 113 |
+
return {}
|
| 114 |
+
params = config.function.parameters
|
| 115 |
+
if isinstance(params, dict) and "properties" in params:
|
| 116 |
+
return params["properties"]
|
| 117 |
+
elif isinstance(params, dict):
|
| 118 |
+
return params
|
| 119 |
+
else:
|
| 120 |
+
return {}
|
| 121 |
+
logger.warning(f"Tool '{func_name}' is not defined in the tools list.")
|
| 122 |
+
return {}
|
| 123 |
+
|
| 124 |
+
def _convert_param_value(self, param_value: str, param_name: str,
|
| 125 |
+
param_config: dict, func_name: str) -> Any:
|
| 126 |
+
"""Convert parameter value based on its type in the schema."""
|
| 127 |
+
# Handle null value for any type
|
| 128 |
+
if param_value.lower() == "null":
|
| 129 |
+
return None
|
| 130 |
+
|
| 131 |
+
if param_name not in param_config:
|
| 132 |
+
if param_config != {}:
|
| 133 |
+
logger.warning(
|
| 134 |
+
f"Parsed parameter '{param_name}' is not defined in the tool "
|
| 135 |
+
f"parameters for tool '{func_name}', directly returning the string value."
|
| 136 |
+
)
|
| 137 |
+
return param_value
|
| 138 |
+
|
| 139 |
+
if isinstance(param_config[param_name],
|
| 140 |
+
dict) and "type" in param_config[param_name]:
|
| 141 |
+
param_type = str(param_config[param_name]["type"]).strip().lower()
|
| 142 |
+
else:
|
| 143 |
+
param_type = "string"
|
| 144 |
+
if param_type in ["string", "str", "text", "varchar", "char", "enum"]:
|
| 145 |
+
return param_value
|
| 146 |
+
elif param_type.startswith("int") or param_type.startswith(
|
| 147 |
+
"uint") or param_type.startswith(
|
| 148 |
+
"long") or param_type.startswith(
|
| 149 |
+
"short") or param_type.startswith("unsigned"):
|
| 150 |
+
try:
|
| 151 |
+
param_value = int(param_value)
|
| 152 |
+
except:
|
| 153 |
+
logger.warning(
|
| 154 |
+
f"Parsed value '{param_value}' of parameter '{param_name}' is not an integer in tool "
|
| 155 |
+
f"'{func_name}', degenerating to string.")
|
| 156 |
+
return param_value
|
| 157 |
+
elif param_type.startswith("num") or param_type.startswith("float"):
|
| 158 |
+
try:
|
| 159 |
+
maybe_convert = False if "." in param_value or "e" in param_value.lower() else True
|
| 160 |
+
param_value: float = float(param_value)
|
| 161 |
+
if maybe_convert and param_value.is_integer():
|
| 162 |
+
param_value = int(param_value)
|
| 163 |
+
except:
|
| 164 |
+
logger.warning(
|
| 165 |
+
f"Parsed value '{param_value}' of parameter '{param_name}' is not a float in tool "
|
| 166 |
+
f"'{func_name}', degenerating to string.")
|
| 167 |
+
return param_value
|
| 168 |
+
elif param_type in ["boolean", "bool", "binary"]:
|
| 169 |
+
param_value = param_value.lower()
|
| 170 |
+
if param_value not in ["true", "false"]:
|
| 171 |
+
logger.warning(
|
| 172 |
+
f"Parsed value '{param_value}' of parameter '{param_name}' is not a boolean (`true` of `false`) in tool '{func_name}', degenerating to false."
|
| 173 |
+
)
|
| 174 |
+
return param_value == "true"
|
| 175 |
+
else:
|
| 176 |
+
if param_type in ["object", "array", "arr"
|
| 177 |
+
] or param_type.startswith(
|
| 178 |
+
"dict") or param_type.startswith("list"):
|
| 179 |
+
try:
|
| 180 |
+
param_value = json.loads(param_value)
|
| 181 |
+
return param_value
|
| 182 |
+
except:
|
| 183 |
+
logger.warning(
|
| 184 |
+
f"Parsed value '{param_value}' of parameter '{param_name}' cannot be parsed with json.loads in tool "
|
| 185 |
+
f"'{func_name}', will try other methods to parse it.")
|
| 186 |
+
try:
|
| 187 |
+
param_value = ast.literal_eval(param_value) # safer
|
| 188 |
+
except:
|
| 189 |
+
logger.warning(
|
| 190 |
+
f"Parsed value '{param_value}' of parameter '{param_name}' cannot be converted via Python `ast.literal_eval()` in tool '{func_name}', degenerating to string."
|
| 191 |
+
)
|
| 192 |
+
return param_value
|
| 193 |
+
|
| 194 |
+
def _parse_xml_function_call(
|
| 195 |
+
self, function_call_str: str,
|
| 196 |
+
tools: Optional[list[ChatCompletionToolsParam]]
|
| 197 |
+
) -> Optional[ToolCall]:
|
| 198 |
+
|
| 199 |
+
# Extract function name
|
| 200 |
+
end_index = function_call_str.index(">")
|
| 201 |
+
function_name = function_call_str[:end_index]
|
| 202 |
+
param_config = self._get_arguments_config(function_name, tools)
|
| 203 |
+
parameters = function_call_str[end_index + 1:]
|
| 204 |
+
param_dict = {}
|
| 205 |
+
for match_text in self.tool_call_parameter_regex.findall(parameters):
|
| 206 |
+
idx = match_text.index(">")
|
| 207 |
+
param_name = match_text[:idx]
|
| 208 |
+
param_value = str(match_text[idx + 1:])
|
| 209 |
+
# Remove prefix and trailing \n
|
| 210 |
+
if param_value.startswith("\n"):
|
| 211 |
+
param_value = param_value[1:]
|
| 212 |
+
if param_value.endswith("\n"):
|
| 213 |
+
param_value = param_value[:-1]
|
| 214 |
+
|
| 215 |
+
param_dict[param_name] = self._convert_param_value(
|
| 216 |
+
param_value, param_name, param_config, function_name)
|
| 217 |
+
return ToolCall(
|
| 218 |
+
type="function",
|
| 219 |
+
function=FunctionCall(name=function_name,
|
| 220 |
+
arguments=json.dumps(param_dict,
|
| 221 |
+
ensure_ascii=False)),
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
def _get_function_calls(self, model_output: str) -> List[str]:
|
| 225 |
+
# Find all tool calls
|
| 226 |
+
matched_ranges = self.tool_call_regex.findall(model_output)
|
| 227 |
+
raw_tool_calls = [
|
| 228 |
+
match[0] if match[0] else match[1] for match in matched_ranges
|
| 229 |
+
]
|
| 230 |
+
|
| 231 |
+
# Back-off strategy if no tool_call tags found
|
| 232 |
+
if len(raw_tool_calls) == 0:
|
| 233 |
+
raw_tool_calls = [model_output]
|
| 234 |
+
|
| 235 |
+
raw_function_calls = []
|
| 236 |
+
for tool_call in raw_tool_calls:
|
| 237 |
+
raw_function_calls.extend(
|
| 238 |
+
self.tool_call_function_regex.findall(tool_call))
|
| 239 |
+
|
| 240 |
+
function_calls = [
|
| 241 |
+
match[0] if match[0] else match[1] for match in raw_function_calls
|
| 242 |
+
]
|
| 243 |
+
return function_calls
|
| 244 |
+
|
| 245 |
+
def extract_tool_calls(
|
| 246 |
+
self,
|
| 247 |
+
model_output: str,
|
| 248 |
+
request: ChatCompletionRequest,
|
| 249 |
+
) -> ExtractedToolCallInformation:
|
| 250 |
+
# Quick check to avoid unnecessary processing
|
| 251 |
+
if self.tool_call_prefix not in model_output:
|
| 252 |
+
return ExtractedToolCallInformation(tools_called=False,
|
| 253 |
+
tool_calls=[],
|
| 254 |
+
content=model_output)
|
| 255 |
+
|
| 256 |
+
try:
|
| 257 |
+
function_calls = self._get_function_calls(model_output)
|
| 258 |
+
if len(function_calls) == 0:
|
| 259 |
+
return ExtractedToolCallInformation(tools_called=False,
|
| 260 |
+
tool_calls=[],
|
| 261 |
+
content=model_output)
|
| 262 |
+
|
| 263 |
+
tool_calls = [
|
| 264 |
+
self._parse_xml_function_call(function_call_str, request.tools)
|
| 265 |
+
for function_call_str in function_calls
|
| 266 |
+
]
|
| 267 |
+
|
| 268 |
+
# Populate prev_tool_call_arr for serving layer to set finish_reason
|
| 269 |
+
self.prev_tool_call_arr.clear() # Clear previous calls
|
| 270 |
+
for tool_call in tool_calls:
|
| 271 |
+
if tool_call:
|
| 272 |
+
self.prev_tool_call_arr.append({
|
| 273 |
+
"name":
|
| 274 |
+
tool_call.function.name,
|
| 275 |
+
"arguments":
|
| 276 |
+
tool_call.function.arguments,
|
| 277 |
+
})
|
| 278 |
+
|
| 279 |
+
# Extract content before tool calls
|
| 280 |
+
content_index = model_output.find(self.tool_call_start_token)
|
| 281 |
+
content_index = content_index if content_index >= 0 else model_output.find(
|
| 282 |
+
self.tool_call_prefix)
|
| 283 |
+
content = model_output[:content_index] # .rstrip()
|
| 284 |
+
|
| 285 |
+
return ExtractedToolCallInformation(
|
| 286 |
+
tools_called=(len(tool_calls) > 0),
|
| 287 |
+
tool_calls=tool_calls,
|
| 288 |
+
content=content if content else None,
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
except Exception:
|
| 292 |
+
logger.exception("Error in extracting tool call from response.")
|
| 293 |
+
return ExtractedToolCallInformation(tools_called=False,
|
| 294 |
+
tool_calls=[],
|
| 295 |
+
content=model_output)
|
| 296 |
+
|
| 297 |
+
def extract_tool_calls_streaming(
|
| 298 |
+
self,
|
| 299 |
+
previous_text: str,
|
| 300 |
+
current_text: str,
|
| 301 |
+
delta_text: str,
|
| 302 |
+
previous_token_ids: Sequence[int],
|
| 303 |
+
current_token_ids: Sequence[int],
|
| 304 |
+
delta_token_ids: Sequence[int],
|
| 305 |
+
request: ChatCompletionRequest,
|
| 306 |
+
) -> Union[DeltaMessage, None]:
|
| 307 |
+
# Store request for type conversion
|
| 308 |
+
if not previous_text:
|
| 309 |
+
self._reset_streaming_state()
|
| 310 |
+
self.streaming_request = request
|
| 311 |
+
|
| 312 |
+
# If no delta text, return None unless it's an EOS token after tool calls
|
| 313 |
+
if not delta_text:
|
| 314 |
+
# Check if this is an EOS token after all tool calls are complete
|
| 315 |
+
# We check for tool calls in the text even if is_tool_call_started is False
|
| 316 |
+
# because it might have been reset after processing all tools
|
| 317 |
+
if delta_token_ids and self.tool_call_end_token_id not in delta_token_ids:
|
| 318 |
+
# Count complete tool calls
|
| 319 |
+
complete_calls = len(
|
| 320 |
+
self.tool_call_complete_regex.findall(current_text))
|
| 321 |
+
|
| 322 |
+
# If we have completed tool calls and populated prev_tool_call_arr
|
| 323 |
+
if complete_calls > 0 and len(self.prev_tool_call_arr) > 0:
|
| 324 |
+
# Check if all tool calls are closed
|
| 325 |
+
open_calls = current_text.count(
|
| 326 |
+
self.tool_call_start_token) - current_text.count(
|
| 327 |
+
self.tool_call_end_token)
|
| 328 |
+
if open_calls == 0:
|
| 329 |
+
# Return empty delta message to allow finish_reason processing
|
| 330 |
+
return DeltaMessage(content="")
|
| 331 |
+
elif not self.is_tool_call_started and current_text:
|
| 332 |
+
# This is a regular content response that's now complete
|
| 333 |
+
return DeltaMessage(content="")
|
| 334 |
+
return None
|
| 335 |
+
|
| 336 |
+
# Update accumulated text
|
| 337 |
+
self.accumulated_text = current_text
|
| 338 |
+
|
| 339 |
+
# Check if we need to advance to next tool
|
| 340 |
+
if self.json_closed and not self.in_function:
|
| 341 |
+
# Check if this tool call has ended
|
| 342 |
+
tool_ends = current_text.count(self.tool_call_end_token)
|
| 343 |
+
if tool_ends > self.current_tool_index:
|
| 344 |
+
# This tool has ended, advance to next
|
| 345 |
+
self.current_tool_index += 1
|
| 346 |
+
self.header_sent = False
|
| 347 |
+
self.param_count = 0
|
| 348 |
+
self.json_started = False
|
| 349 |
+
self.json_closed = False
|
| 350 |
+
self.accumulated_params = {}
|
| 351 |
+
|
| 352 |
+
# Check if there are more tool calls
|
| 353 |
+
tool_starts = current_text.count(self.tool_call_start_token)
|
| 354 |
+
if self.current_tool_index >= tool_starts:
|
| 355 |
+
# No more tool calls
|
| 356 |
+
self.is_tool_call_started = False
|
| 357 |
+
# Continue processing next tool
|
| 358 |
+
return None
|
| 359 |
+
|
| 360 |
+
# Handle normal content before tool calls
|
| 361 |
+
if not self.is_tool_call_started:
|
| 362 |
+
# Check if tool call is starting
|
| 363 |
+
if self.tool_call_start_token_id in delta_token_ids or self.tool_call_start_token in delta_text:
|
| 364 |
+
self.is_tool_call_started = True
|
| 365 |
+
# Return any content before the tool call
|
| 366 |
+
if self.tool_call_start_token in delta_text:
|
| 367 |
+
content_before = delta_text[:delta_text.index(
|
| 368 |
+
self.tool_call_start_token)]
|
| 369 |
+
if content_before:
|
| 370 |
+
return DeltaMessage(content=content_before)
|
| 371 |
+
return None
|
| 372 |
+
else:
|
| 373 |
+
# Check if we're between tool calls - skip whitespace
|
| 374 |
+
if current_text.rstrip().endswith(self.tool_call_end_token):
|
| 375 |
+
# We just ended a tool call, skip whitespace
|
| 376 |
+
if delta_text.strip() == "":
|
| 377 |
+
return None
|
| 378 |
+
# Normal content, no tool call
|
| 379 |
+
return DeltaMessage(content=delta_text)
|
| 380 |
+
|
| 381 |
+
# Check if we're between tool calls (waiting for next one)
|
| 382 |
+
# Count tool calls we've seen vs processed
|
| 383 |
+
tool_starts_count = current_text.count(self.tool_call_start_token)
|
| 384 |
+
if self.current_tool_index >= tool_starts_count:
|
| 385 |
+
# We're past all tool calls, shouldn't be here
|
| 386 |
+
return None
|
| 387 |
+
|
| 388 |
+
# We're in a tool call, find the current tool call portion
|
| 389 |
+
# Need to find the correct tool call based on current_tool_index
|
| 390 |
+
tool_starts = []
|
| 391 |
+
idx = 0
|
| 392 |
+
while True:
|
| 393 |
+
idx = current_text.find(self.tool_call_start_token, idx)
|
| 394 |
+
if idx == -1:
|
| 395 |
+
break
|
| 396 |
+
tool_starts.append(idx)
|
| 397 |
+
idx += len(self.tool_call_start_token)
|
| 398 |
+
|
| 399 |
+
if self.current_tool_index >= len(tool_starts):
|
| 400 |
+
# No more tool calls to process yet
|
| 401 |
+
return None
|
| 402 |
+
|
| 403 |
+
tool_start_idx = tool_starts[self.current_tool_index]
|
| 404 |
+
# Find where this tool call ends (or current position if not ended yet)
|
| 405 |
+
tool_end_idx = current_text.find(self.tool_call_end_token,
|
| 406 |
+
tool_start_idx)
|
| 407 |
+
if tool_end_idx == -1:
|
| 408 |
+
tool_text = current_text[tool_start_idx:]
|
| 409 |
+
else:
|
| 410 |
+
tool_text = current_text[tool_start_idx:tool_end_idx +
|
| 411 |
+
len(self.tool_call_end_token)]
|
| 412 |
+
|
| 413 |
+
# Looking for function header
|
| 414 |
+
if not self.header_sent:
|
| 415 |
+
if self.tool_call_prefix in tool_text:
|
| 416 |
+
func_start = tool_text.find(self.tool_call_prefix) + len(
|
| 417 |
+
self.tool_call_prefix)
|
| 418 |
+
func_end = tool_text.find(">", func_start)
|
| 419 |
+
|
| 420 |
+
if func_end != -1:
|
| 421 |
+
# Found complete function name
|
| 422 |
+
self.current_function_name = tool_text[func_start:func_end]
|
| 423 |
+
self.current_tool_id = self._generate_tool_call_id()
|
| 424 |
+
self.header_sent = True
|
| 425 |
+
self.in_function = True
|
| 426 |
+
|
| 427 |
+
# IMPORTANT: Add to prev_tool_call_arr immediately when we detect a tool call
|
| 428 |
+
# This ensures finish_reason="tool_calls" even if parsing isn't complete
|
| 429 |
+
already_added = any(
|
| 430 |
+
tool.get("name") == self.current_function_name
|
| 431 |
+
for tool in self.prev_tool_call_arr)
|
| 432 |
+
if not already_added:
|
| 433 |
+
self.prev_tool_call_arr.append({
|
| 434 |
+
"name": self.current_function_name,
|
| 435 |
+
"arguments":
|
| 436 |
+
"{}", # Placeholder, will be updated later
|
| 437 |
+
})
|
| 438 |
+
|
| 439 |
+
# Send header with function info
|
| 440 |
+
return DeltaMessage(tool_calls=[
|
| 441 |
+
DeltaToolCall(
|
| 442 |
+
index=self.current_tool_index,
|
| 443 |
+
id=self.current_tool_id,
|
| 444 |
+
function=DeltaFunctionCall(
|
| 445 |
+
name=self.current_function_name, arguments=""),
|
| 446 |
+
type="function",
|
| 447 |
+
)
|
| 448 |
+
])
|
| 449 |
+
return None
|
| 450 |
+
|
| 451 |
+
# We've sent header, now handle function body
|
| 452 |
+
if self.in_function:
|
| 453 |
+
# Send opening brace if not sent yet
|
| 454 |
+
if not self.json_started and self.parameter_prefix not in delta_text:
|
| 455 |
+
self.json_started = True
|
| 456 |
+
return DeltaMessage(tool_calls=[
|
| 457 |
+
DeltaToolCall(
|
| 458 |
+
index=self.current_tool_index,
|
| 459 |
+
function=DeltaFunctionCall(arguments="{"),
|
| 460 |
+
)
|
| 461 |
+
])
|
| 462 |
+
|
| 463 |
+
# Make sure json_started is set if we're processing parameters
|
| 464 |
+
if not self.json_started:
|
| 465 |
+
self.json_started = True
|
| 466 |
+
|
| 467 |
+
# Check for function end in accumulated text
|
| 468 |
+
if not self.json_closed and self.function_end_token in tool_text:
|
| 469 |
+
# Close JSON
|
| 470 |
+
self.json_closed = True
|
| 471 |
+
|
| 472 |
+
# Extract the complete tool call to update prev_tool_call_arr with final arguments
|
| 473 |
+
# Find the function content
|
| 474 |
+
func_start = tool_text.find(self.tool_call_prefix) + len(
|
| 475 |
+
self.tool_call_prefix)
|
| 476 |
+
func_content_end = tool_text.find(self.function_end_token,
|
| 477 |
+
func_start)
|
| 478 |
+
if func_content_end != -1:
|
| 479 |
+
func_content = tool_text[func_start:func_content_end]
|
| 480 |
+
# Parse to get the complete arguments
|
| 481 |
+
try:
|
| 482 |
+
parsed_tool = self._parse_xml_function_call(
|
| 483 |
+
func_content, self.streaming_request.tools
|
| 484 |
+
if self.streaming_request else None)
|
| 485 |
+
if parsed_tool:
|
| 486 |
+
# Update existing entry in prev_tool_call_arr with complete arguments
|
| 487 |
+
for i, tool in enumerate(self.prev_tool_call_arr):
|
| 488 |
+
if tool.get(
|
| 489 |
+
"name") == parsed_tool.function.name:
|
| 490 |
+
self.prev_tool_call_arr[i][
|
| 491 |
+
"arguments"] = parsed_tool.function.arguments
|
| 492 |
+
break
|
| 493 |
+
except Exception:
|
| 494 |
+
pass # Ignore parsing errors during streaming
|
| 495 |
+
|
| 496 |
+
result = DeltaMessage(tool_calls=[
|
| 497 |
+
DeltaToolCall(
|
| 498 |
+
index=self.current_tool_index,
|
| 499 |
+
function=DeltaFunctionCall(arguments="}"),
|
| 500 |
+
)
|
| 501 |
+
])
|
| 502 |
+
|
| 503 |
+
# Reset state for next tool
|
| 504 |
+
self.in_function = False
|
| 505 |
+
self.json_closed = True
|
| 506 |
+
self.accumulated_params = {}
|
| 507 |
+
|
| 508 |
+
return result
|
| 509 |
+
|
| 510 |
+
# Look for parameters
|
| 511 |
+
# Find all parameter starts
|
| 512 |
+
param_starts = []
|
| 513 |
+
idx = 0
|
| 514 |
+
while True:
|
| 515 |
+
idx = tool_text.find(self.parameter_prefix, idx)
|
| 516 |
+
if idx == -1:
|
| 517 |
+
break
|
| 518 |
+
param_starts.append(idx)
|
| 519 |
+
idx += len(self.parameter_prefix)
|
| 520 |
+
|
| 521 |
+
# Check if we should start a new parameter
|
| 522 |
+
if not self.in_param and self.param_count < len(param_starts):
|
| 523 |
+
|
| 524 |
+
if len(param_starts) > self.param_count:
|
| 525 |
+
# Process the next parameter
|
| 526 |
+
param_idx = param_starts[self.param_count]
|
| 527 |
+
param_start = param_idx + len(self.parameter_prefix)
|
| 528 |
+
remaining = tool_text[param_start:]
|
| 529 |
+
|
| 530 |
+
if ">" in remaining:
|
| 531 |
+
# We have the complete parameter name
|
| 532 |
+
name_end = remaining.find(">")
|
| 533 |
+
self.current_param_name = remaining[:name_end]
|
| 534 |
+
|
| 535 |
+
# Find the parameter value
|
| 536 |
+
value_start = param_start + name_end + 1
|
| 537 |
+
value_text = tool_text[value_start:]
|
| 538 |
+
if value_text.startswith("\n"):
|
| 539 |
+
value_text = value_text[1:]
|
| 540 |
+
|
| 541 |
+
# Find where this parameter ends
|
| 542 |
+
param_end_idx = value_text.find(
|
| 543 |
+
self.parameter_end_token)
|
| 544 |
+
if param_end_idx == -1:
|
| 545 |
+
# No closing tag, look for next parameter or function end
|
| 546 |
+
next_param_idx = value_text.find(
|
| 547 |
+
self.parameter_prefix)
|
| 548 |
+
func_end_idx = value_text.find(
|
| 549 |
+
self.function_end_token)
|
| 550 |
+
|
| 551 |
+
if next_param_idx != -1 and (func_end_idx == -1
|
| 552 |
+
or next_param_idx
|
| 553 |
+
< func_end_idx):
|
| 554 |
+
param_end_idx = next_param_idx
|
| 555 |
+
elif func_end_idx != -1:
|
| 556 |
+
param_end_idx = func_end_idx
|
| 557 |
+
else:
|
| 558 |
+
# Neither found, check if tool call is complete
|
| 559 |
+
if self.tool_call_end_token in tool_text:
|
| 560 |
+
# Tool call is complete, so parameter must be complete too
|
| 561 |
+
# Use all remaining text before function end as value
|
| 562 |
+
param_end_idx = len(value_text)
|
| 563 |
+
else:
|
| 564 |
+
# Still streaming, wait for more content
|
| 565 |
+
return None
|
| 566 |
+
|
| 567 |
+
if param_end_idx != -1:
|
| 568 |
+
# Complete parameter found
|
| 569 |
+
param_value = value_text[:param_end_idx]
|
| 570 |
+
if param_value.endswith("\n"):
|
| 571 |
+
param_value = param_value[:-1]
|
| 572 |
+
|
| 573 |
+
# Store raw value for later processing
|
| 574 |
+
self.accumulated_params[
|
| 575 |
+
self.current_param_name] = param_value
|
| 576 |
+
|
| 577 |
+
# Get parameter configuration for type conversion
|
| 578 |
+
param_config = self._get_arguments_config(
|
| 579 |
+
self.current_function_name,
|
| 580 |
+
self.streaming_request.tools
|
| 581 |
+
if self.streaming_request else None)
|
| 582 |
+
|
| 583 |
+
# Convert the parameter value to the appropriate type
|
| 584 |
+
converted_value = self._convert_param_value(
|
| 585 |
+
param_value, self.current_param_name,
|
| 586 |
+
param_config, self.current_function_name)
|
| 587 |
+
|
| 588 |
+
# Build JSON fragment based on the converted type
|
| 589 |
+
# Use json.dumps to properly serialize the value
|
| 590 |
+
serialized_value = json.dumps(converted_value,
|
| 591 |
+
ensure_ascii=False)
|
| 592 |
+
|
| 593 |
+
if self.param_count == 0:
|
| 594 |
+
json_fragment = f'"{self.current_param_name}": {serialized_value}'
|
| 595 |
+
else:
|
| 596 |
+
json_fragment = f', "{self.current_param_name}": {serialized_value}'
|
| 597 |
+
|
| 598 |
+
self.param_count += 1
|
| 599 |
+
|
| 600 |
+
return DeltaMessage(tool_calls=[
|
| 601 |
+
DeltaToolCall(
|
| 602 |
+
index=self.current_tool_index,
|
| 603 |
+
function=DeltaFunctionCall(
|
| 604 |
+
arguments=json_fragment),
|
| 605 |
+
)
|
| 606 |
+
])
|
| 607 |
+
|
| 608 |
+
# Continue parameter value - Not used in the current implementation
|
| 609 |
+
# since we process complete parameters above
|
| 610 |
+
if self.in_param:
|
| 611 |
+
if self.parameter_end_token in delta_text:
|
| 612 |
+
# End of parameter
|
| 613 |
+
end_idx = delta_text.find(self.parameter_end_token)
|
| 614 |
+
value_chunk = delta_text[:end_idx]
|
| 615 |
+
|
| 616 |
+
# Skip past > if at start
|
| 617 |
+
if not self.current_param_value and ">" in value_chunk:
|
| 618 |
+
gt_idx = value_chunk.find(">")
|
| 619 |
+
value_chunk = value_chunk[gt_idx + 1:]
|
| 620 |
+
|
| 621 |
+
if not self.current_param_value and value_chunk.startswith(
|
| 622 |
+
"\n"):
|
| 623 |
+
value_chunk = value_chunk[1:]
|
| 624 |
+
|
| 625 |
+
# Store complete value
|
| 626 |
+
full_value = self.current_param_value + value_chunk
|
| 627 |
+
self.accumulated_params[
|
| 628 |
+
self.current_param_name] = full_value
|
| 629 |
+
|
| 630 |
+
# Get parameter configuration for type conversion
|
| 631 |
+
param_config = self._get_arguments_config(
|
| 632 |
+
self.current_function_name,
|
| 633 |
+
self.streaming_request.tools
|
| 634 |
+
if self.streaming_request else None)
|
| 635 |
+
|
| 636 |
+
# Convert the parameter value to the appropriate type
|
| 637 |
+
converted_value = self._convert_param_value(
|
| 638 |
+
full_value, self.current_param_name, param_config,
|
| 639 |
+
self.current_function_name)
|
| 640 |
+
|
| 641 |
+
# Serialize the converted value
|
| 642 |
+
serialized_value = json.dumps(converted_value,
|
| 643 |
+
ensure_ascii=False)
|
| 644 |
+
|
| 645 |
+
# Since we've been streaming the quoted version, we need to close it properly
|
| 646 |
+
# This is complex - for now just complete the value
|
| 647 |
+
self.in_param = False
|
| 648 |
+
self.current_param_value = ""
|
| 649 |
+
|
| 650 |
+
# Just close the current parameter string
|
| 651 |
+
return DeltaMessage(tool_calls=[
|
| 652 |
+
DeltaToolCall(
|
| 653 |
+
index=self.current_tool_index,
|
| 654 |
+
function=DeltaFunctionCall(
|
| 655 |
+
arguments='"'), # Close the string quote
|
| 656 |
+
)
|
| 657 |
+
])
|
| 658 |
+
else:
|
| 659 |
+
# Continue accumulating value
|
| 660 |
+
value_chunk = delta_text
|
| 661 |
+
|
| 662 |
+
# Handle first chunk after param name
|
| 663 |
+
if not self.current_param_value and ">" in value_chunk:
|
| 664 |
+
gt_idx = value_chunk.find(">")
|
| 665 |
+
value_chunk = value_chunk[gt_idx + 1:]
|
| 666 |
+
|
| 667 |
+
if not self.current_param_value and value_chunk.startswith(
|
| 668 |
+
"\n"):
|
| 669 |
+
value_chunk = value_chunk[1:]
|
| 670 |
+
|
| 671 |
+
if value_chunk:
|
| 672 |
+
# Stream the escaped delta
|
| 673 |
+
prev_escaped = json.dumps(
|
| 674 |
+
self.current_param_value, ensure_ascii=False
|
| 675 |
+
)[1:-1] if self.current_param_value else ""
|
| 676 |
+
self.current_param_value += value_chunk
|
| 677 |
+
full_escaped = json.dumps(self.current_param_value,
|
| 678 |
+
ensure_ascii=False)[1:-1]
|
| 679 |
+
delta_escaped = full_escaped[len(prev_escaped):]
|
| 680 |
+
|
| 681 |
+
if delta_escaped:
|
| 682 |
+
return DeltaMessage(tool_calls=[
|
| 683 |
+
DeltaToolCall(
|
| 684 |
+
index=self.current_tool_index,
|
| 685 |
+
function=DeltaFunctionCall(
|
| 686 |
+
arguments=delta_escaped),
|
| 687 |
+
)
|
| 688 |
+
])
|
| 689 |
+
|
| 690 |
+
return None
|
tokenizer.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:be75606093db2094d7cd20f3c2f385c212750648bd6ea4fb2bf507a6a4c55506
|
| 3 |
+
size 11422650
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_prefix_space": false,
|
| 3 |
+
"backend": "tokenizers",
|
| 4 |
+
"bos_token": null,
|
| 5 |
+
"clean_up_tokenization_spaces": false,
|
| 6 |
+
"eos_token": "<|im_end|>",
|
| 7 |
+
"errors": "replace",
|
| 8 |
+
"extra_special_tokens": [
|
| 9 |
+
"<|im_start|>",
|
| 10 |
+
"<|im_end|>",
|
| 11 |
+
"<|object_ref_start|>",
|
| 12 |
+
"<|object_ref_end|>",
|
| 13 |
+
"<|box_start|>",
|
| 14 |
+
"<|box_end|>",
|
| 15 |
+
"<|quad_start|>",
|
| 16 |
+
"<|quad_end|>",
|
| 17 |
+
"<|vision_start|>",
|
| 18 |
+
"<|vision_end|>",
|
| 19 |
+
"<|vision_pad|>",
|
| 20 |
+
"<|image_pad|>",
|
| 21 |
+
"<|video_pad|>"
|
| 22 |
+
],
|
| 23 |
+
"is_local": true,
|
| 24 |
+
"local_files_only": false,
|
| 25 |
+
"model_max_length": 1048576,
|
| 26 |
+
"pad_token": "<|endoftext|>",
|
| 27 |
+
"split_special_tokens": false,
|
| 28 |
+
"tokenizer_class": "Qwen2Tokenizer",
|
| 29 |
+
"tool_parser_type": "qwen3_coder",
|
| 30 |
+
"unk_token": null
|
| 31 |
+
}
|