Instructions to use unsloth/Qwen3-Coder-Next-Base with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use unsloth/Qwen3-Coder-Next-Base with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="unsloth/Qwen3-Coder-Next-Base") messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("unsloth/Qwen3-Coder-Next-Base") model = AutoModelForCausalLM.from_pretrained("unsloth/Qwen3-Coder-Next-Base", device_map="auto") messages = [ {"role": "user", "content": "Who are you?"}, ] inputs = tokenizer.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", ).to(model.device) outputs = model.generate(**inputs, max_new_tokens=256) print(tokenizer.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use unsloth/Qwen3-Coder-Next-Base with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "unsloth/Qwen3-Coder-Next-Base" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "unsloth/Qwen3-Coder-Next-Base", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/unsloth/Qwen3-Coder-Next-Base
- SGLang
How to use unsloth/Qwen3-Coder-Next-Base with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "unsloth/Qwen3-Coder-Next-Base" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "unsloth/Qwen3-Coder-Next-Base", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "unsloth/Qwen3-Coder-Next-Base" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "unsloth/Qwen3-Coder-Next-Base", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Unsloth Desktop
- Docker Model Runner
How to use unsloth/Qwen3-Coder-Next-Base with Docker Model Runner:
docker model run hf.co/unsloth/Qwen3-Coder-Next-Base
Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+1
- README.md+92-3
- added_tokens.jsonAdded+28
- chat_template.jinjaAdded+117
- config.jsonAdded+95
- generation_config.jsonAdded+13
- merges.txtAdded
- model-00001-of-00040.safetensorsAdded+3
- model-00002-of-00040.safetensorsAdded+3
- model-00003-of-00040.safetensorsAdded+3
- model-00004-of-00040.safetensorsAdded+3
- model-00005-of-00040.safetensorsAdded+3
- model-00006-of-00040.safetensorsAdded+3
- model-00007-of-00040.safetensorsAdded+3
- model-00008-of-00040.safetensorsAdded+3
- model-00009-of-00040.safetensorsAdded+3
- model-00010-of-00040.safetensorsAdded+3
- model-00011-of-00040.safetensorsAdded+3
- model-00012-of-00040.safetensorsAdded+3
- model-00013-of-00040.safetensorsAdded+3
- model-00014-of-00040.safetensorsAdded+3
- model-00015-of-00040.safetensorsAdded+3
- model-00016-of-00040.safetensorsAdded+3
- model-00017-of-00040.safetensorsAdded+3
- model-00018-of-00040.safetensorsAdded+3
- model-00019-of-00040.safetensorsAdded+3
- model-00020-of-00040.safetensorsAdded+3
- model-00021-of-00040.safetensorsAdded+3
- model-00022-of-00040.safetensorsAdded+3
- model-00023-of-00040.safetensorsAdded+3
- model-00024-of-00040.safetensorsAdded+3
- model-00025-of-00040.safetensorsAdded+3
- model-00026-of-00040.safetensorsAdded+3
- model-00027-of-00040.safetensorsAdded+3
- model-00028-of-00040.safetensorsAdded+3
- model-00029-of-00040.safetensorsAdded+3
- model-00030-of-00040.safetensorsAdded+3
- model-00031-of-00040.safetensorsAdded+3
- model-00032-of-00040.safetensorsAdded+3
- model-00033-of-00040.safetensorsAdded+3
- model-00034-of-00040.safetensorsAdded+3
- model-00035-of-00040.safetensorsAdded+3
- model-00036-of-00040.safetensorsAdded+3
- model-00037-of-00040.safetensorsAdded+3
- model-00038-of-00040.safetensorsAdded+3
- model-00039-of-00040.safetensorsAdded+3
- model-00040-of-00040.safetensorsAdded+3
- model.safetensors.index.jsonAdded
- qwen3_coder_detector_sgl.pyAdded+474
- qwen3coder_tool_parser_vllm.pyAdded+690
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -texttokenizer.json filter=lfs diff=lfs merge=lfs -text
123---license: apache-2.0---1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192---tags:- unslothbase_model:- Qwen/Qwen3-Coder-Next-Baselibrary_name: transformerslicense: apache-2.0license_link: https://huggingface.co/Qwen/Qwen3-Coder-Next-Base/blob/main/LICENSEpipeline_tag: text-generation---> [!NOTE]> Includes Unsloth **chat template fixes**! <br> For `llama.cpp`, use `--jinja`><div><p style="margin-top: 0;margin-bottom: 0;"><em><a href="https://docs.unsloth.ai/basics/unsloth-dynamic-v2.0-gguf">Unsloth Dynamic 2.0</a> achieves superior accuracy & outperforms other leading quants.</em></p><div style="display: flex; gap: 5px; align-items: center; "><a href="https://github.com/unslothai/unsloth/"><img src="https://github.com/unslothai/unsloth/raw/main/images/unsloth%20new%20logo.png" width="133"></a><a href="https://discord.gg/unsloth"><img src="https://github.com/unslothai/unsloth/raw/main/images/Discord%20button.png" width="173"></a><a href="https://docs.unsloth.ai/"><img src="https://raw.githubusercontent.com/unslothai/unsloth/refs/heads/main/images/documentation%20green%20button.png" width="143"></a></div></div># Qwen3-Coder-Next-Base<a href="https://chat.qwen.ai/" target="_blank" style="margin: 2px;"><img alt="Chat" src="https://img.shields.io/badge/%F0%9F%92%9C%EF%B8%8F%20Qwen%20Chat%20-536af5" style="display: inline-block; vertical-align: middle;"/></a>## HighlightsToday, we're announcing **Qwen3-Coder-Next-Base**, an open-weight language model designed specifically for coding agents and local development. It features the following key enhancements:- **Advanced architecture**: It integrates the Hybrid Attention with highly sparse MoE, enabling high throughput and strong ultra-long-context modeling.- **Robust data foundation**: Trained on highly diverse, broad-coverage corpora, with native 256K context and support for 370+ languages, it leaves ample headroom for post-training.- **Agentic coding capability**: With a carefully designed training recipe, it has strong capabilities in tool calling, scaffold/template adaptation, and error detection/recovery, making it a strong backbone for reliable coding agents.## Model Overview**Qwen3-Coder-Next-Base** has the following features:- Type: Causal Language Models- Training Stage: Pretraining- Number of Parameters: 80B in total and 3B activated- Number of Parameters (Non-Embedding): 79B- Hidden Dimension: 2048- Number of Layers: 48- Hybrid Layout: 12 \* (3 \* (Gated DeltaNet -> MoE) -> 1 \* (Gated Attention -> MoE))- Gated Attention:- Number of Attention Heads: 16 for Q and 2 for KV- Head Dimension: 256- Rotary Position Embedding Dimension: 64- Gated DeltaNet:- Number of Linear Attention Heads: 32 for V and 16 for QK- Head Dimension: 128- Mixture of Experts:- Number of Experts: 512- Number of Activated Experts: 10- Number of Shared Experts: 1- Expert Intermediate Dimension: 512- Context Length: 262,144 natively**NOTE: This model supports only non-thinking mode and does not generate ``<think></think>`` blocks in its output. Meanwhile, specifying `enable_thinking=False` is no longer required.**For more details, including benchmark evaluation, hardware requirements, and inference performance, please refer to our [blog](https://qwenlm.github.io/blog/qwen3-coder-next/), [GitHub](https://github.com/QwenLM/Qwen3-Coder), and [Documentation](https://qwen.readthedocs.io/en/latest/).## Best PracticesTo achieve optimal performance, we recommend the following sampling parameters: `temperature=1.0`, `top_p=0.95`, `top_k=40`.## CitationIf you find our work helpful, feel free to give us a cite.```@techreport{qwen_qwen3_coder_next_tech_report,title = {Qwen3-Coder-Next Technical Report},author = {{Qwen Team}},url = {https://github.com/QwenLM/Qwen3-Coder/blob/main/qwen3_coder_next_tech_report.pdf},note = {Accessed: 2026-02-03}}```
12345678910111213141516171819202122232425262728{ "</think>": 151668, "</tool_call>": 151658, "</tool_response>": 151666, "<think>": 151667, "<tool_call>": 151657, "<tool_response>": 151665, "<|box_end|>": 151649, "<|box_start|>": 151648, "<|endoftext|>": 151643, "<|file_sep|>": 151664, "<|fim_middle|>": 151660, "<|fim_pad|>": 151662, "<|fim_prefix|>": 151659, "<|fim_suffix|>": 151661, "<|im_end|>": 151645, "<|im_start|>": 151644, "<|image_pad|>": 151655, "<|object_ref_end|>": 151647, "<|object_ref_start|>": 151646, "<|quad_end|>": 151651, "<|quad_start|>": 151650, "<|repo_name|>": 151663, "<|video_pad|>": 151656, "<|vision_end|>": 151653, "<|vision_pad|>": 151654, "<|vision_start|>": 151652}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117{% macro render_extra_keys(json_dict, handled_keys) %} {%- if json_dict is mapping %} {%- for json_key in json_dict if json_key not in handled_keys %} {%- if json_dict[json_key] is string %} {{-'\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '</' ~ json_key ~ '>' }} {%- else %} {{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '</' ~ json_key ~ '>' }} {%- endif %} {%- endfor %} {%- endif %}{%- endmacro %}
{%- if messages[0]["role"] == "system" %} {%- set system_message = messages[0]["content"] %} {%- set loop_messages = messages[1:] %}{%- else %} {%- set loop_messages = messages %}{%- endif %}
{%- if not tools is defined %} {%- set tools = [] %}{%- endif %}
{%- if system_message is defined %} {{- "<|im_start|>system\n" + system_message }}{%- else %} {%- if tools is iterable and tools | length > 0 %} {{- "<|im_start|>system\nYou are Qwen, a helpful AI assistant that can interact with a computer to solve tasks." }} {%- endif %}{%- endif %}{%- if tools is iterable and tools | length > 0 %} {{- "\n\n# Tools\n\nYou have access to the following functions:\n\n" }} {{- "<tools>" }} {%- for tool in tools %} {%- if tool.function is defined %} {%- set tool = tool.function %} {%- endif %} {{- "\n<function>\n<name>" ~ tool.name ~ "</name>" }} {%- if tool.description is defined %} {{- '\n<description>' ~ (tool.description | trim) ~ '</description>' }} {%- endif %} {{- '\n<parameters>' }} {%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %} {%- for param_name, param_fields in tool.parameters.properties|items %} {{- '\n<parameter>' }} {{- '\n<name>' ~ param_name ~ '</name>' }} {%- if param_fields.type is defined %} {{- '\n<type>' ~ (param_fields.type | string) ~ '</type>' }} {%- endif %} {%- if param_fields.description is defined %} {{- '\n<description>' ~ (param_fields.description | trim) ~ '</description>' }} {%- endif %} {%- set handled_keys = ['name', 'type', 'description'] %} {{- render_extra_keys(param_fields, handled_keys) }} {{- '\n</parameter>' }} {%- endfor %} {%- endif %} {%- set handled_keys = ['type', 'properties'] %} {{- render_extra_keys(tool.parameters, handled_keys) }} {{- '\n</parameters>' }} {%- set handled_keys = ['type', 'name', 'description', 'parameters'] %} {{- render_extra_keys(tool, handled_keys) }} {{- '\n</function>' }} {%- endfor %} {{- "\n</tools>" }} {{- '\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>' }}{%- endif %}{%- if system_message is defined %} {{- '<|im_end|>\n' }}{%- else %} {%- if tools is iterable and tools | length > 0 %} {{- '<|im_end|>\n' }} {%- endif %}{%- endif %}{%- for message in loop_messages %} {%- if message.role == "assistant" and message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %} {{- '<|im_start|>' + message.role }} {%- if message.content is defined and message.content is string and message.content | trim | length > 0 %} {{- '\n' + message.content | trim + '\n' }} {%- endif %} {%- for tool_call in message.tool_calls %} {%- if tool_call.function is defined %} {%- set tool_call = tool_call.function %} {%- endif %} {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }} {%- if tool_call.arguments is defined %} {%- for args_name, args_value in tool_call.arguments|items %} {{- '<parameter=' + args_name + '>\n' }} {%- set args_value = args_value if args_value is string else args_value | tojson | safe %} {{- args_value }} {{- '\n</parameter>\n' }} {%- endfor %} {%- endif %} {{- '</function>\n</tool_call>' }} {%- endfor %} {{- '<|im_end|>\n' }} {%- elif message.role == "user" or message.role == "system" or message.role == "assistant" %} {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' + '\n' }} {%- elif message.role == "tool" %} {%- if loop.previtem and loop.previtem.role != "tool" %} {{- '<|im_start|>user' }} {%- endif %} {{- '\n<tool_response>\n' }} {{- message.content }} {{- '\n</tool_response>' }} {%- if not loop.last and loop.nextitem.role != "tool" %} {{- '<|im_end|>\n' }} {%- elif loop.last %} {{- '<|im_end|>\n' }} {%- endif %} {%- else %} {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' }} {%- endif %}{%- endfor %}{%- if add_generation_prompt %} {{- '<|im_start|>assistant\n' }}{%- endif %}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495{ "architectures": [ "Qwen3NextForCausalLM" ], "attention_bias": false, "attention_dropout": 0, "decoder_sparse_step": 1, "torch_dtype": "bfloat16", "eos_token_id": 151645, "full_attention_interval": 4, "head_dim": 256, "hidden_act": "silu", "hidden_size": 2048, "initializer_range": 0.02, "intermediate_size": 5120, "layer_types": [ "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention", "linear_attention", "linear_attention", "linear_attention", "full_attention" ], "linear_conv_kernel_dim": 4, "linear_key_head_dim": 128, "linear_num_key_heads": 16, "linear_num_value_heads": 32, "linear_value_head_dim": 128, "max_position_embeddings": 262144, "mlp_only_layers": [], "model_type": "qwen3_next", "moe_intermediate_size": 512, "norm_topk_prob": true, "num_attention_heads": 16, "num_experts": 512, "num_experts_per_tok": 10, "num_hidden_layers": 48, "num_key_value_heads": 2, "output_router_logits": false, "pad_token_id": 151654, "partial_rotary_factor": 0.25, "rms_norm_eps": 1e-06, "rope_scaling": null, "rope_theta": 5000000, "router_aux_loss_coef": 0.001, "shared_expert_intermediate_size": 512, "tie_word_embeddings": false, "transformers_version": "4.57.6", "unsloth_fixed": true, "use_cache": true, "use_sliding_window": false, "vocab_size": 151936}12345678910111213{ "bos_token_id": 151643, "do_sample": true, "eos_token_id": [ 151645, 151643 ], "pad_token_id": 151643, "temperature": 1.0, "top_k": 40, "top_p": 0.95, "transformers_version": "4.57.3"}123version https://git-lfs.github.com/spec/v1oid sha256:4154d3f07228c9f8445e5f67c816cb9b11936601b528bd12a956b57ec716eb50size 3999619288123version https://git-lfs.github.com/spec/v1oid sha256:2b64b32e3dbb7d14e004db9b8bf211f8bb4220c216609d8a2a7648d0d2b833aesize 3999841816123version https://git-lfs.github.com/spec/v1oid sha256:619c5131f2d46e272a74a5d7b2be176c2dae464a79ab089fccae4281e8a9105esize 3999515608123version https://git-lfs.github.com/spec/v1oid sha256:c496fe649cd1e98fcf08e46d8429fc353447cc403065b0dfd27eb67cc8145c65size 3999842032123version https://git-lfs.github.com/spec/v1oid sha256:b9a09bd4d14d02a6b95d17e651f9cffb881a11c14d8fcdb80a9d1811ed8f7f6csize 3999842240123version https://git-lfs.github.com/spec/v1oid sha256:1c456d137bc9368de5818bb7c67a2ef265529cbfcb67ce3d555c9adb1ee42e9esize 3999853248123version https://git-lfs.github.com/spec/v1oid sha256:ccce4c7a4e4f37fc02e8ce3fe4578f9e67e7956cbc0fc7b37be7ae3a3001b8e9size 3999841944123version https://git-lfs.github.com/spec/v1oid sha256:7e99fa7af0028ca68a5018346a789e90b892c5c5862efdc7644b18d61c5be64csize 3999842032123version https://git-lfs.github.com/spec/v1oid sha256:c21d18a25e64d1ed0a65a11a4bea05f160cec40fc2e4192c686610eebe4fec46size 3999843224123version https://git-lfs.github.com/spec/v1oid sha256:51a5e58c6d182b4f0fffe44b0833cb979b45f2db99369d17871d95dec036fa0asize 3999517840123version https://git-lfs.github.com/spec/v1oid sha256:8e5c1701f67de6792a579ff5620bf168bda982ce05a48f9cceb9e6273f20ac92size 4000181328123version https://git-lfs.github.com/spec/v1oid sha256:5fc238d0999010dbd07ac6590d94ea0dbd53ec81e3a7b04c3580e0e9afc52baasize 3999843912123version https://git-lfs.github.com/spec/v1oid sha256:6d29d706020a54482312b304c61bf3d7d39570cec001a413604c43bc41440badsize 3999517504123version https://git-lfs.github.com/spec/v1oid sha256:8f0791fdcc9d2adfeb1d1090751bf45bc4001a0667dc61ff99497fd0769c27d0size 3999844016123version https://git-lfs.github.com/spec/v1oid sha256:daf29f3820eb08934ccb2c500985dd4c95d6464e61aee18ecf216b2a65c1efbdsize 4000181768123version https://git-lfs.github.com/spec/v1oid sha256:ddbbde7fb22d53ba49d10a36171adfbec92354654fd3effd5883920aa749c14esize 3999517280123version https://git-lfs.github.com/spec/v1oid sha256:6fde8437d71cf5e2f44d2f860fdcdaa50bbce87bf6b8357aedf3880eed11c8b6size 3999843912123version https://git-lfs.github.com/spec/v1oid sha256:f9447b461373298d48febcebdaf2b7a68615199546c474a7fab1665f94b28c37size 3999843912123version https://git-lfs.github.com/spec/v1oid sha256:1c2c96bb51520ef6fb626a7c6a5e70816bebe10cf335cac769531fe34921cb7csize 3999844120123version https://git-lfs.github.com/spec/v1oid sha256:e922c9f9885f6a41bf76e80d54079b501218e993cde584872b37ae2c6f753d39size 3999855064123version https://git-lfs.github.com/spec/v1oid sha256:84ff130604b8ead1b441445d5b652fa6c2687997eb72a3f5c49247a781425b77size 3999843824123version https://git-lfs.github.com/spec/v1oid sha256:0dcd0e80116cfe9d5c70d94c63c5b46ab2426784d58666f5a4592dd22717d38fsize 3999843912123version https://git-lfs.github.com/spec/v1oid sha256:753b5e44df6b7e8f324dfa9f17754e1425b4db75ceca590b742c2218b17e0a99size 3999517496123version https://git-lfs.github.com/spec/v1oid sha256:531f06f424f3a0c8823fa481e0012c429907fcab1e13ef421fb2dd891c0cdbc5size 3999844296123version https://git-lfs.github.com/spec/v1oid sha256:d6ad6f8d6930b49e700f39e8be514d45a3166e124d007802c5c4c82e5cd435b8size 4000181328123version https://git-lfs.github.com/spec/v1oid sha256:86594609634418a19dbca114cf272413f7a79b70b80f50154c0d71668233efd7size 3999517504123version https://git-lfs.github.com/spec/v1oid sha256:ce1cb0ed0fa6be9368c55f4eac22f27c06c640d14b1d97903485c52700b7ccd7size 3999843912123version https://git-lfs.github.com/spec/v1oid sha256:e045632a406ff76b543c2ceb1b4755c4a0d01305f146487ba6a548f60a28d49esize 3999844016123version https://git-lfs.github.com/spec/v1oid sha256:4f902d3a827acd2dd38cf30468260f494be1508d6ccfcd2eb6a41021f7416e16size 3999855352123version https://git-lfs.github.com/spec/v1oid sha256:306064928813a0bf8f6fe192de9d67dae870adafa8b112072a7834a1a29a6371size 3999843704123version https://git-lfs.github.com/spec/v1oid sha256:fda4170c97a2412c01e9341a20500972fbc5b603cc52f2cbfe9c8776c24ec53dsize 3999843912123version https://git-lfs.github.com/spec/v1oid sha256:ca0e08919effe195be303e54fa3502ab4975dbd0687f9a4aeae17b59344415a5size 3999843912123version https://git-lfs.github.com/spec/v1oid sha256:a24e90d5e458c6dd47f97ae4da448f541113d4a4114bc75952dec613ac9d8836size 3999517720123version https://git-lfs.github.com/spec/v1oid sha256:c55e63b390214b1681d5c64c8c657dc9bcc153739781dcdb37b03a29adee4ad7size 4000181528123version https://git-lfs.github.com/spec/v1oid sha256:c26a4edbe6a47e40c1b71fe23ad6e49b1a556ed1d60c2a96e9240a6ef773e701size 3999843824123version https://git-lfs.github.com/spec/v1oid sha256:d5b79b898c31611413caf773e188d7f978312ae5d1cd100e16233027a2b0d6ecsize 3999517504123version https://git-lfs.github.com/spec/v1oid sha256:d290b04adc6c108b2312c01a61cf246927eb9c13ba6f0405086d771b2fb84990size 3999843904123version https://git-lfs.github.com/spec/v1oid sha256:03da644a2e3a7abd04bbce353fd124385bc4328364617fecb94a8b3829992f09size 3999844296123version https://git-lfs.github.com/spec/v1oid sha256:837747b4657851a8e8f168393c71dab8058da7161c685bceb46bfbc0cec748f4size 3999854920123version https://git-lfs.github.com/spec/v1oid sha256:3e77aae3fa20022fb16d41e13b3bcf31a030b53855ac75d6158727fe22b83aebsize 3365572528123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474import astimport jsonimport loggingimport refrom typing import Any, List, Optional
from sglang.srt.entrypoints.openai.protocol import Toolfrom sglang.srt.function_call.base_format_detector import BaseFormatDetectorfrom sglang.srt.function_call.core_types import ( StreamingParseResult, ToolCallItem, _GetInfoFunc,)
logger = logging.getLogger(__name__)
class Qwen3CoderDetector(BaseFormatDetector): def __init__(self): super().__init__()
# Sentinel tokens self.tool_call_start_token: str = "<tool_call>" self.tool_call_end_token: str = "</tool_call>" self.tool_call_prefix: str = "<function=" self.function_end_token: str = "</function>" self.parameter_prefix: str = "<parameter=" self.parameter_end_token: str = "</parameter>"
# Regex for non-streaming fallback self.tool_call_regex = re.compile(r"<tool_call>(.*?)</tool_call>", re.DOTALL) self.tool_call_function_regex = re.compile( r"<function=(.*?)</function>|<function=(.*)$", re.DOTALL ) self.tool_call_parameter_regex = re.compile( r"<parameter=(.*?)(?:</parameter>|(?=<parameter=)|(?=</function>)|$)", re.DOTALL, )
# Streaming State # Base class already initializes _buffer, we just use it directly # No need to check with hasattr - we control the lifecycle through inheritance
# Index pointing to the next character to be processed in buffer self.parsed_pos: int = 0 # Parameter count inside the current tool being processed, used to determine whether to add comma self.current_tool_param_count: int = 0 # Flag indicating whether current tool has already sent '{' self.json_started: bool = False
# [FIX] New state flag: mark whether inside tool_call structure block self.is_inside_tool_call: bool = False
# Initialize attributes that were missing in the original PR self.current_func_name: Optional[str] = None
def has_tool_call(self, text: str) -> bool: return self.tool_call_start_token in text
def _get_arguments_config( self, func_name: str, tools: Optional[list[Tool]] ) -> dict: """Extract argument configuration for a function.""" if tools is None: return {} for config in tools: try: config_type = config.type config_function = config.function config_function_name = config_function.name except AttributeError: continue
if config_type == "function" and config_function_name == func_name: try: params = config_function.parameters except AttributeError: return {}
if isinstance(params, dict) and "properties" in params: return params["properties"] elif isinstance(params, dict): return params else: return {} logger.warning(f"Tool '{func_name}' is not defined in the tools list.") return {}
def _convert_param_value( self, param_value: str, param_name: str, param_config: dict, func_name: str ) -> Any: """Convert parameter value based on its type in the schema.""" # Handle null value for any type if param_value.lower() == "null": return None
if param_name not in param_config: if param_config != {}: logger.warning( f"Parsed parameter '{param_name}' is not defined in the tool " f"parameters for tool '{func_name}', directly returning the string value." ) return param_value
if ( isinstance(param_config[param_name], dict) and "type" in param_config[param_name] ): param_type = str(param_config[param_name]["type"]).strip().lower() else: param_type = "string" if param_type in ["string", "str", "text", "varchar", "char", "enum"]: return param_value elif ( param_type.startswith("int") or param_type.startswith("uint") or param_type.startswith("long") or param_type.startswith("short") or param_type.startswith("unsigned") ): try: param_value = int(param_value) except Exception: logger.warning( f"Parsed value '{param_value}' of parameter '{param_name}' is not an integer in tool " f"'{func_name}', degenerating to string." ) return param_value elif param_type.startswith("num") or param_type.startswith("float"): try: maybe_convert = ( False if "." in param_value or "e" in param_value.lower() else True ) param_value: float = float(param_value) if maybe_convert and param_value.is_integer(): param_value = int(param_value) except Exception: logger.warning( f"Parsed value '{param_value}' of parameter '{param_name}' is not a float in tool " f"'{func_name}', degenerating to string." ) return param_value elif param_type in ["boolean", "bool", "binary"]: param_value = param_value.lower() if param_value not in ["true", "false"]: logger.warning( f"Parsed value '{param_value}' of parameter '{param_name}' is not a boolean (`true` of `false`) in tool '{func_name}', degenerating to false." ) return param_value == "true" else: if ( param_type in ["object", "array", "arr"] or param_type.startswith("dict") or param_type.startswith("list") ): try: param_value = json.loads(param_value) return param_value except Exception: logger.warning( f"Parsed value '{param_value}' of parameter '{param_name}' cannot be parsed with json.loads in tool " f"'{func_name}', will try other methods to parse it." ) try: param_value = ast.literal_eval(param_value) # safer except Exception: logger.warning( f"Parsed value '{param_value}' of parameter '{param_name}' cannot be converted via Python `ast.literal_eval()` in tool '{func_name}', degenerating to string." ) return param_value
def detect_and_parse(self, text: str, tools: List[Tool]) -> StreamingParseResult: """One-shot parsing for non-streaming scenarios.""" if self.tool_call_start_token not in text: return StreamingParseResult(normal_text=text)
calls = [] try: # Simple cleanup of the text to find tool calls # Note: This is a simplified regex approach consistent with vLLM raw_tool_calls = self.tool_call_regex.findall(text) if not raw_tool_calls: # Fallback: maybe the whole text is inside the tag or tags are stripped if self.tool_call_prefix in text: raw_tool_calls = [text]
tool_idx = 0 for tool_content in raw_tool_calls: # Find function calls funcs = self.tool_call_function_regex.findall(tool_content) for func_match in funcs: func_body = func_match[0] or func_match[1] if ">" not in func_body: continue
name_end = func_body.index(">") func_name = func_body[:name_end] params_str = func_body[name_end + 1 :]
param_config = self._get_arguments_config(func_name, tools) parsed_params = {}
for p_match in self.tool_call_parameter_regex.findall(params_str): if ">" not in p_match: continue p_idx = p_match.index(">") p_name = p_match[:p_idx] p_val = p_match[p_idx + 1 :] # Remove prefixing and trailing \n if p_val.startswith("\n"): p_val = p_val[1:] if p_val.endswith("\n"): p_val = p_val[:-1]
parsed_params[p_name] = self._convert_param_value( p_val, p_name, param_config, func_name )
calls.append( ToolCallItem( tool_index=tool_idx, name=func_name, parameters=json.dumps(parsed_params, ensure_ascii=False), ) ) tool_idx += 1
# Determine normal text (text before the first tool call) start_idx = text.find(self.tool_call_start_token) if start_idx == -1: start_idx = text.find(self.tool_call_prefix) normal_text = text[:start_idx] if start_idx > 0 else ""
return StreamingParseResult(normal_text=normal_text, calls=calls)
except Exception as e: logger.error(f"Error in detect_and_parse: {e}") return StreamingParseResult(normal_text=text)
def parse_streaming_increment( self, new_text: str, tools: List[Tool] ) -> StreamingParseResult: """ Robust cursor-based streaming parser. """ self._buffer += new_text
# Guard against empty buffer if not self._buffer: return StreamingParseResult()
calls = [] normal_text_chunks = []
while True: # Working text slice current_slice = self._buffer[self.parsed_pos :]
# Optimization: If almost empty, wait for more if not current_slice: break
# ------------------------------------------------------- # 1. Priority detection: check if it's the start of Tool Call # ------------------------------------------------------- if current_slice.startswith(self.tool_call_start_token): self.parsed_pos += len(self.tool_call_start_token) self.is_inside_tool_call = True continue
# ------------------------------------------------------- # 2. Function Name: <function=name> # ------------------------------------------------------- if current_slice.startswith(self.tool_call_prefix): end_angle = current_slice.find(">") if end_angle != -1: func_name = current_slice[len(self.tool_call_prefix) : end_angle]
self.current_tool_id += 1 self.current_tool_name_sent = True self.current_tool_param_count = 0 self.json_started = False self.current_func_name = func_name
calls.append( ToolCallItem( tool_index=self.current_tool_id, name=func_name, parameters="", ) )
self.parsed_pos += end_angle + 1 continue else: # Incomplete tag break
# ------------------------------------------------------- # 3. Parameter: <parameter=name>value... # ------------------------------------------------------- if current_slice.startswith(self.parameter_prefix): name_end = current_slice.find(">") if name_end != -1: value_start_idx = name_end + 1 rest_of_slice = current_slice[value_start_idx:]
# A parameter can end in multiple ways: # 1. [Normal] Encounter </parameter> # 2. [Abnormal] Encounter next <parameter= # 3. [Abnormal] Encounter </function> # So we need to find the smallest one as the parameter end position. cand_end_param = rest_of_slice.find(self.parameter_end_token) cand_next_param = rest_of_slice.find(self.parameter_prefix) cand_end_func = rest_of_slice.find(self.function_end_token)
candidates = [] if cand_end_param != -1: candidates.append( (cand_end_param, len(self.parameter_end_token)) ) if cand_next_param != -1: candidates.append((cand_next_param, 0)) if cand_end_func != -1: candidates.append((cand_end_func, 0))
if candidates: best_cand = min(candidates, key=lambda x: x[0]) end_pos = best_cand[0] end_token_len = best_cand[1]
param_name = current_slice[ len(self.parameter_prefix) : name_end ] raw_value = rest_of_slice[:end_pos]
# Cleanup value if raw_value.startswith("\n"): raw_value = raw_value[1:] if raw_value.endswith("\n"): raw_value = raw_value[:-1]
# JSON Construction if not self.json_started: calls.append( ToolCallItem( tool_index=self.current_tool_id, parameters="{" ) ) self.json_started = True
param_config = self._get_arguments_config( self.current_func_name, tools ) converted_val = self._convert_param_value( raw_value, param_name, param_config, self.current_func_name )
# Construct JSON fragment: "key": value # Note: We must be careful with json.dumps to ensure valid JSON streaming json_key_val = f"{json.dumps(param_name)}: {json.dumps(converted_val, ensure_ascii=False)}"
if self.current_tool_param_count > 0: fragment = f", {json_key_val}" else: fragment = json_key_val
calls.append( ToolCallItem( tool_index=self.current_tool_id, parameters=fragment ) ) self.current_tool_param_count += 1
# Advance cursor total_len = (name_end + 1) + end_pos + end_token_len self.parsed_pos += total_len continue
# Incomplete parameter tag or value break
# ------------------------------------------------------- # 4. Function End: </function> # ------------------------------------------------------- if current_slice.startswith(self.function_end_token): if not self.json_started: calls.append( ToolCallItem(tool_index=self.current_tool_id, parameters="{") ) self.json_started = True
calls.append( ToolCallItem(tool_index=self.current_tool_id, parameters="}") ) self.parsed_pos += len(self.function_end_token) self.current_func_name = None continue
# ------------------------------------------------------- # 5. Tool Call End: </tool_call> # ------------------------------------------------------- if current_slice.startswith(self.tool_call_end_token): self.parsed_pos += len(self.tool_call_end_token) self.is_inside_tool_call = False # [FIX] Exit tool call region continue
# ------------------------------------------------------- # 6. Handling content / whitespace / normal text # ------------------------------------------------------- # If current position is not the start of a tag (i.e., doesn't start with <), it might be plain text, # or a newline between two tags. # But we need to be careful not to output truncated tags like "<fun" as text.
next_open_angle = current_slice.find("<")
if next_open_angle == -1: # This entire segment is plain text if not self.is_inside_tool_call: normal_text_chunks.append(current_slice) # [FIX] If inside tool call, discard this text (usually \n), don't append self.parsed_pos += len(current_slice) continue
elif next_open_angle == 0: # Looks like a Tag, but doesn't match any known Tag above
possible_tags = [ self.tool_call_start_token, self.tool_call_end_token, self.tool_call_prefix, self.function_end_token, self.parameter_prefix, self.parameter_end_token, ]
is_potential_tag = False for tag in possible_tags: if tag.startswith(current_slice): is_potential_tag = True break
if is_potential_tag: break # Wait for more else: # Just a plain '<' symbol if not self.is_inside_tool_call: normal_text_chunks.append("<") self.parsed_pos += 1 continue
else: # '<' is in the middle text_segment = current_slice[:next_open_angle] if not self.is_inside_tool_call: normal_text_chunks.append(text_segment) # [FIX] If inside tool call, discard whitespace/text before Tag self.parsed_pos += next_open_angle continue
# Memory Cleanup: Slice the buffer # Keep unparsed part, discard parsed part if self.parsed_pos > 0: self._buffer = self._buffer[self.parsed_pos :] self.parsed_pos = 0
normal_text = "".join(normal_text_chunks) if normal_text_chunks else "" return StreamingParseResult(calls=calls, normal_text=normal_text)
def supports_structural_tag(self) -> bool: return False
def structure_info(self) -> _GetInfoFunc: raise NotImplementedError123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690# SPDX-License-Identifier: Apache-2.0# SPDX-FileCopyrightText: Copyright contributors to the vLLM projectimport astimport jsonimport uuidfrom collections.abc import Sequencefrom typing import Any, List, Optional, Union
import regex as re
from vllm.entrypoints.openai.protocol import (ChatCompletionRequest, ChatCompletionToolsParam, DeltaFunctionCall, DeltaMessage, DeltaToolCall, ExtractedToolCallInformation, FunctionCall, ToolCall)from vllm.entrypoints.openai.tool_parsers.abstract_tool_parser import ( ToolParser, ToolParserManager)from vllm.logger import init_loggerfrom vllm.transformers_utils.tokenizer import AnyTokenizer
logger = init_logger(__name__)
@ToolParserManager.register_module("qwen3_coder")class Qwen3CoderToolParser(ToolParser):
def __init__(self, tokenizer: AnyTokenizer): super().__init__(tokenizer)
self.current_tool_name_sent: bool = False self.prev_tool_call_arr: list[dict] = [] self.current_tool_id: int = -1 self.streamed_args_for_tool: list[str] = []
# Sentinel tokens for streaming mode self.tool_call_start_token: str = "<tool_call>" self.tool_call_end_token: str = "</tool_call>" self.tool_call_prefix: str = "<function=" self.function_end_token: str = "</function>" self.parameter_prefix: str = "<parameter=" self.parameter_end_token: str = "</parameter>" self.is_tool_call_started: bool = False self.failed_count: int = 0
# Enhanced streaming state - reset for each new message self._reset_streaming_state()
# Regex patterns self.tool_call_complete_regex = re.compile( r"<tool_call>(.*?)</tool_call>", re.DOTALL) self.tool_call_regex = re.compile( r"<tool_call>(.*?)</tool_call>|<tool_call>(.*?)$", re.DOTALL) self.tool_call_function_regex = re.compile( r"<function=(.*?)</function>|<function=(.*)$", re.DOTALL) self.tool_call_parameter_regex = re.compile( r"<parameter=(.*?)(?:</parameter>|(?=<parameter=)|(?=</function>)|$)", re.DOTALL)
if not self.model_tokenizer: raise ValueError( "The model tokenizer must be passed to the ToolParser " "constructor during construction.")
self.tool_call_start_token_id = self.vocab.get( self.tool_call_start_token) self.tool_call_end_token_id = self.vocab.get(self.tool_call_end_token)
if self.tool_call_start_token_id is None or self.tool_call_end_token_id is None: raise RuntimeError( "Qwen3 XML Tool parser could not locate tool call start/end " "tokens in the tokenizer!")
logger.info( f"vLLM Successfully import tool parser {self.__class__.__name__} !" )
def _generate_tool_call_id(self) -> str: """Generate a unique tool call ID.""" return f"call_{uuid.uuid4().hex[:24]}"
def _reset_streaming_state(self): """Reset all streaming state.""" self.current_tool_index = 0 self.is_tool_call_started = False self.header_sent = False self.current_tool_id = None self.current_function_name = None self.current_param_name = None self.current_param_value = "" self.param_count = 0 self.in_param = False self.in_function = False self.accumulated_text = "" self.json_started = False self.json_closed = False # Store accumulated parameters for type conversion self.accumulated_params = {} self.streaming_request = None
def _get_arguments_config( self, func_name: str, tools: Optional[list[ChatCompletionToolsParam]]) -> dict: """Extract argument configuration for a function.""" if tools is None: return {} for config in tools: if not hasattr(config, "type") or not (hasattr( config, "function") and hasattr(config.function, "name")): continue if config.type == "function" and config.function.name == func_name: if not hasattr(config.function, "parameters"): return {} params = config.function.parameters if isinstance(params, dict) and "properties" in params: return params["properties"] elif isinstance(params, dict): return params else: return {} logger.warning(f"Tool '{func_name}' is not defined in the tools list.") return {}
def _convert_param_value(self, param_value: str, param_name: str, param_config: dict, func_name: str) -> Any: """Convert parameter value based on its type in the schema.""" # Handle null value for any type if param_value.lower() == "null": return None
if param_name not in param_config: if param_config != {}: logger.warning( f"Parsed parameter '{param_name}' is not defined in the tool " f"parameters for tool '{func_name}', directly returning the string value." ) return param_value
if isinstance(param_config[param_name], dict) and "type" in param_config[param_name]: param_type = str(param_config[param_name]["type"]).strip().lower() else: param_type = "string" if param_type in ["string", "str", "text", "varchar", "char", "enum"]: return param_value elif param_type.startswith("int") or param_type.startswith( "uint") or param_type.startswith( "long") or param_type.startswith( "short") or param_type.startswith("unsigned"): try: param_value = int(param_value) except: logger.warning( f"Parsed value '{param_value}' of parameter '{param_name}' is not an integer in tool " f"'{func_name}', degenerating to string.") return param_value elif param_type.startswith("num") or param_type.startswith("float"): try: maybe_convert = False if "." in param_value or "e" in param_value.lower() else True param_value: float = float(param_value) if maybe_convert and param_value.is_integer(): param_value = int(param_value) except: logger.warning( f"Parsed value '{param_value}' of parameter '{param_name}' is not a float in tool " f"'{func_name}', degenerating to string.") return param_value elif param_type in ["boolean", "bool", "binary"]: param_value = param_value.lower() if param_value not in ["true", "false"]: logger.warning( f"Parsed value '{param_value}' of parameter '{param_name}' is not a boolean (`true` of `false`) in tool '{func_name}', degenerating to false." ) return param_value == "true" else: if param_type in ["object", "array", "arr" ] or param_type.startswith( "dict") or param_type.startswith("list"): try: param_value = json.loads(param_value) return param_value except: logger.warning( f"Parsed value '{param_value}' of parameter '{param_name}' cannot be parsed with json.loads in tool " f"'{func_name}', will try other methods to parse it.") try: param_value = ast.literal_eval(param_value) # safer except: logger.warning( f"Parsed value '{param_value}' of parameter '{param_name}' cannot be converted via Python `ast.literal_eval()` in tool '{func_name}', degenerating to string." ) return param_value
def _parse_xml_function_call( self, function_call_str: str, tools: Optional[list[ChatCompletionToolsParam]] ) -> Optional[ToolCall]:
# Extract function name end_index = function_call_str.index(">") function_name = function_call_str[:end_index] param_config = self._get_arguments_config(function_name, tools) parameters = function_call_str[end_index + 1:] param_dict = {} for match_text in self.tool_call_parameter_regex.findall(parameters): idx = match_text.index(">") param_name = match_text[:idx] param_value = str(match_text[idx + 1:]) # Remove prefix and trailing \n if param_value.startswith("\n"): param_value = param_value[1:] if param_value.endswith("\n"): param_value = param_value[:-1]
param_dict[param_name] = self._convert_param_value( param_value, param_name, param_config, function_name) return ToolCall( type="function", function=FunctionCall(name=function_name, arguments=json.dumps(param_dict, ensure_ascii=False)), )
def _get_function_calls(self, model_output: str) -> List[str]: # Find all tool calls matched_ranges = self.tool_call_regex.findall(model_output) raw_tool_calls = [ match[0] if match[0] else match[1] for match in matched_ranges ]
# Back-off strategy if no tool_call tags found if len(raw_tool_calls) == 0: raw_tool_calls = [model_output]
raw_function_calls = [] for tool_call in raw_tool_calls: raw_function_calls.extend( self.tool_call_function_regex.findall(tool_call))
function_calls = [ match[0] if match[0] else match[1] for match in raw_function_calls ] return function_calls
def extract_tool_calls( self, model_output: str, request: ChatCompletionRequest, ) -> ExtractedToolCallInformation: # Quick check to avoid unnecessary processing if self.tool_call_prefix not in model_output: return ExtractedToolCallInformation(tools_called=False, tool_calls=[], content=model_output)
try: function_calls = self._get_function_calls(model_output) if len(function_calls) == 0: return ExtractedToolCallInformation(tools_called=False, tool_calls=[], content=model_output)
tool_calls = [ self._parse_xml_function_call(function_call_str, request.tools) for function_call_str in function_calls ]
# Populate prev_tool_call_arr for serving layer to set finish_reason self.prev_tool_call_arr.clear() # Clear previous calls for tool_call in tool_calls: if tool_call: self.prev_tool_call_arr.append({ "name": tool_call.function.name, "arguments": tool_call.function.arguments, })
# Extract content before tool calls content_index = model_output.find(self.tool_call_start_token) content_index = content_index if content_index >= 0 else model_output.find( self.tool_call_prefix) content = model_output[:content_index] # .rstrip()
return ExtractedToolCallInformation( tools_called=(len(tool_calls) > 0), tool_calls=tool_calls, content=content if content else None, )
except Exception: logger.exception("Error in extracting tool call from response.") return ExtractedToolCallInformation(tools_called=False, tool_calls=[], content=model_output)
def extract_tool_calls_streaming( self, previous_text: str, current_text: str, delta_text: str, previous_token_ids: Sequence[int], current_token_ids: Sequence[int], delta_token_ids: Sequence[int], request: ChatCompletionRequest, ) -> Union[DeltaMessage, None]: # Store request for type conversion if not previous_text: self._reset_streaming_state() self.streaming_request = request
# If no delta text, return None unless it's an EOS token after tool calls if not delta_text: # Check if this is an EOS token after all tool calls are complete # We check for tool calls in the text even if is_tool_call_started is False # because it might have been reset after processing all tools if delta_token_ids and self.tool_call_end_token_id not in delta_token_ids: # Count complete tool calls complete_calls = len( self.tool_call_complete_regex.findall(current_text))
# If we have completed tool calls and populated prev_tool_call_arr if complete_calls > 0 and len(self.prev_tool_call_arr) > 0: # Check if all tool calls are closed open_calls = current_text.count( self.tool_call_start_token) - current_text.count( self.tool_call_end_token) if open_calls == 0: # Return empty delta message to allow finish_reason processing return DeltaMessage(content="") elif not self.is_tool_call_started and current_text: # This is a regular content response that's now complete return DeltaMessage(content="") return None
# Update accumulated text self.accumulated_text = current_text
# Check if we need to advance to next tool if self.json_closed and not self.in_function: # Check if this tool call has ended tool_ends = current_text.count(self.tool_call_end_token) if tool_ends > self.current_tool_index: # This tool has ended, advance to next self.current_tool_index += 1 self.header_sent = False self.param_count = 0 self.json_started = False self.json_closed = False self.accumulated_params = {}
# Check if there are more tool calls tool_starts = current_text.count(self.tool_call_start_token) if self.current_tool_index >= tool_starts: # No more tool calls self.is_tool_call_started = False # Continue processing next tool return None
# Handle normal content before tool calls if not self.is_tool_call_started: # Check if tool call is starting if self.tool_call_start_token_id in delta_token_ids or self.tool_call_start_token in delta_text: self.is_tool_call_started = True # Return any content before the tool call if self.tool_call_start_token in delta_text: content_before = delta_text[:delta_text.index( self.tool_call_start_token)] if content_before: return DeltaMessage(content=content_before) return None else: # Check if we're between tool calls - skip whitespace if current_text.rstrip().endswith(self.tool_call_end_token): # We just ended a tool call, skip whitespace if delta_text.strip() == "": return None # Normal content, no tool call return DeltaMessage(content=delta_text)
# Check if we're between tool calls (waiting for next one) # Count tool calls we've seen vs processed tool_starts_count = current_text.count(self.tool_call_start_token) if self.current_tool_index >= tool_starts_count: # We're past all tool calls, shouldn't be here return None
# We're in a tool call, find the current tool call portion # Need to find the correct tool call based on current_tool_index tool_starts = [] idx = 0 while True: idx = current_text.find(self.tool_call_start_token, idx) if idx == -1: break tool_starts.append(idx) idx += len(self.tool_call_start_token)
if self.current_tool_index >= len(tool_starts): # No more tool calls to process yet return None
tool_start_idx = tool_starts[self.current_tool_index] # Find where this tool call ends (or current position if not ended yet) tool_end_idx = current_text.find(self.tool_call_end_token, tool_start_idx) if tool_end_idx == -1: tool_text = current_text[tool_start_idx:] else: tool_text = current_text[tool_start_idx:tool_end_idx + len(self.tool_call_end_token)]
# Looking for function header if not self.header_sent: if self.tool_call_prefix in tool_text: func_start = tool_text.find(self.tool_call_prefix) + len( self.tool_call_prefix) func_end = tool_text.find(">", func_start)
if func_end != -1: # Found complete function name self.current_function_name = tool_text[func_start:func_end] self.current_tool_id = self._generate_tool_call_id() self.header_sent = True self.in_function = True
# IMPORTANT: Add to prev_tool_call_arr immediately when we detect a tool call # This ensures finish_reason="tool_calls" even if parsing isn't complete already_added = any( tool.get("name") == self.current_function_name for tool in self.prev_tool_call_arr) if not already_added: self.prev_tool_call_arr.append({ "name": self.current_function_name, "arguments": "{}", # Placeholder, will be updated later })
# Send header with function info return DeltaMessage(tool_calls=[ DeltaToolCall( index=self.current_tool_index, id=self.current_tool_id, function=DeltaFunctionCall( name=self.current_function_name, arguments=""), type="function", ) ]) return None
# We've sent header, now handle function body if self.in_function: # Send opening brace if not sent yet if not self.json_started and self.parameter_prefix not in delta_text: self.json_started = True return DeltaMessage(tool_calls=[ DeltaToolCall( index=self.current_tool_index, function=DeltaFunctionCall(arguments="{"), ) ])
# Make sure json_started is set if we're processing parameters if not self.json_started: self.json_started = True
# Check for function end in accumulated text if not self.json_closed and self.function_end_token in tool_text: # Close JSON self.json_closed = True
# Extract the complete tool call to update prev_tool_call_arr with final arguments # Find the function content func_start = tool_text.find(self.tool_call_prefix) + len( self.tool_call_prefix) func_content_end = tool_text.find(self.function_end_token, func_start) if func_content_end != -1: func_content = tool_text[func_start:func_content_end] # Parse to get the complete arguments try: parsed_tool = self._parse_xml_function_call( func_content, self.streaming_request.tools if self.streaming_request else None) if parsed_tool: # Update existing entry in prev_tool_call_arr with complete arguments for i, tool in enumerate(self.prev_tool_call_arr): if tool.get( "name") == parsed_tool.function.name: self.prev_tool_call_arr[i][ "arguments"] = parsed_tool.function.arguments break except Exception: pass # Ignore parsing errors during streaming
result = DeltaMessage(tool_calls=[ DeltaToolCall( index=self.current_tool_index, function=DeltaFunctionCall(arguments="}"), ) ])
# Reset state for next tool self.in_function = False self.json_closed = True self.accumulated_params = {}
return result
# Look for parameters # Find all parameter starts param_starts = [] idx = 0 while True: idx = tool_text.find(self.parameter_prefix, idx) if idx == -1: break param_starts.append(idx) idx += len(self.parameter_prefix)
# Check if we should start a new parameter if not self.in_param and self.param_count < len(param_starts):
if len(param_starts) > self.param_count: # Process the next parameter param_idx = param_starts[self.param_count] param_start = param_idx + len(self.parameter_prefix) remaining = tool_text[param_start:]
if ">" in remaining: # We have the complete parameter name name_end = remaining.find(">") self.current_param_name = remaining[:name_end]
# Find the parameter value value_start = param_start + name_end + 1 value_text = tool_text[value_start:] if value_text.startswith("\n"): value_text = value_text[1:]
# Find where this parameter ends param_end_idx = value_text.find( self.parameter_end_token) if param_end_idx == -1: # No closing tag, look for next parameter or function end next_param_idx = value_text.find( self.parameter_prefix) func_end_idx = value_text.find( self.function_end_token)
if next_param_idx != -1 and (func_end_idx == -1 or next_param_idx < func_end_idx): param_end_idx = next_param_idx elif func_end_idx != -1: param_end_idx = func_end_idx else: # Neither found, check if tool call is complete if self.tool_call_end_token in tool_text: # Tool call is complete, so parameter must be complete too # Use all remaining text before function end as value param_end_idx = len(value_text) else: # Still streaming, wait for more content return None
if param_end_idx != -1: # Complete parameter found param_value = value_text[:param_end_idx] if param_value.endswith("\n"): param_value = param_value[:-1]
# Store raw value for later processing self.accumulated_params[ self.current_param_name] = param_value
# Get parameter configuration for type conversion param_config = self._get_arguments_config( self.current_function_name, self.streaming_request.tools if self.streaming_request else None)
# Convert the parameter value to the appropriate type converted_value = self._convert_param_value( param_value, self.current_param_name, param_config, self.current_function_name)
# Build JSON fragment based on the converted type # Use json.dumps to properly serialize the value serialized_value = json.dumps(converted_value, ensure_ascii=False)
if self.param_count == 0: json_fragment = f'"{self.current_param_name}": {serialized_value}' else: json_fragment = f', "{self.current_param_name}": {serialized_value}'
self.param_count += 1
return DeltaMessage(tool_calls=[ DeltaToolCall( index=self.current_tool_index, function=DeltaFunctionCall( arguments=json_fragment), ) ])
# Continue parameter value - Not used in the current implementation # since we process complete parameters above if self.in_param: if self.parameter_end_token in delta_text: # End of parameter end_idx = delta_text.find(self.parameter_end_token) value_chunk = delta_text[:end_idx]
# Skip past > if at start if not self.current_param_value and ">" in value_chunk: gt_idx = value_chunk.find(">") value_chunk = value_chunk[gt_idx + 1:]
if not self.current_param_value and value_chunk.startswith( "\n"): value_chunk = value_chunk[1:]
# Store complete value full_value = self.current_param_value + value_chunk self.accumulated_params[ self.current_param_name] = full_value
# Get parameter configuration for type conversion param_config = self._get_arguments_config( self.current_function_name, self.streaming_request.tools if self.streaming_request else None)
# Convert the parameter value to the appropriate type converted_value = self._convert_param_value( full_value, self.current_param_name, param_config, self.current_function_name)
# Serialize the converted value serialized_value = json.dumps(converted_value, ensure_ascii=False)
# Since we've been streaming the quoted version, we need to close it properly # This is complex - for now just complete the value self.in_param = False self.current_param_value = ""
# Just close the current parameter string return DeltaMessage(tool_calls=[ DeltaToolCall( index=self.current_tool_index, function=DeltaFunctionCall( arguments='"'), # Close the string quote ) ]) else: # Continue accumulating value value_chunk = delta_text
# Handle first chunk after param name if not self.current_param_value and ">" in value_chunk: gt_idx = value_chunk.find(">") value_chunk = value_chunk[gt_idx + 1:]
if not self.current_param_value and value_chunk.startswith( "\n"): value_chunk = value_chunk[1:]
if value_chunk: # Stream the escaped delta prev_escaped = json.dumps( self.current_param_value, ensure_ascii=False )[1:-1] if self.current_param_value else "" self.current_param_value += value_chunk full_escaped = json.dumps(self.current_param_value, ensure_ascii=False)[1:-1] delta_escaped = full_escaped[len(prev_escaped):]
if delta_escaped: return DeltaMessage(tool_calls=[ DeltaToolCall( index=self.current_tool_index, function=DeltaFunctionCall( arguments=delta_escaped), ) ])
return None.gitattributes+1
README.md+92-3
added_tokens.jsonAdded+28
chat_template.jinjaAdded+117
config.jsonAdded+95
generation_config.jsonAdded+13
merges.txtAdded
model-00001-of-00040.safetensorsAdded+3
model-00002-of-00040.safetensorsAdded+3
model-00003-of-00040.safetensorsAdded+3
model-00004-of-00040.safetensorsAdded+3
model-00005-of-00040.safetensorsAdded+3
model-00006-of-00040.safetensorsAdded+3
model-00007-of-00040.safetensorsAdded+3
model-00008-of-00040.safetensorsAdded+3
model-00009-of-00040.safetensorsAdded+3
model-00010-of-00040.safetensorsAdded+3
model-00011-of-00040.safetensorsAdded+3
model-00012-of-00040.safetensorsAdded+3
model-00013-of-00040.safetensorsAdded+3
model-00014-of-00040.safetensorsAdded+3
model-00015-of-00040.safetensorsAdded+3
model-00016-of-00040.safetensorsAdded+3
model-00017-of-00040.safetensorsAdded+3
model-00018-of-00040.safetensorsAdded+3
model-00019-of-00040.safetensorsAdded+3
model-00020-of-00040.safetensorsAdded+3
model-00021-of-00040.safetensorsAdded+3
model-00022-of-00040.safetensorsAdded+3
model-00023-of-00040.safetensorsAdded+3
model-00024-of-00040.safetensorsAdded+3
model-00025-of-00040.safetensorsAdded+3
model-00026-of-00040.safetensorsAdded+3
model-00027-of-00040.safetensorsAdded+3
model-00028-of-00040.safetensorsAdded+3
model-00029-of-00040.safetensorsAdded+3
model-00030-of-00040.safetensorsAdded+3
model-00031-of-00040.safetensorsAdded+3
model-00032-of-00040.safetensorsAdded+3
model-00033-of-00040.safetensorsAdded+3
model-00034-of-00040.safetensorsAdded+3
model-00035-of-00040.safetensorsAdded+3
model-00036-of-00040.safetensorsAdded+3
model-00037-of-00040.safetensorsAdded+3
model-00038-of-00040.safetensorsAdded+3
model-00039-of-00040.safetensorsAdded+3
model-00040-of-00040.safetensorsAdded+3
model.safetensors.index.jsonAdded
qwen3_coder_detector_sgl.pyAdded+474
qwen3coder_tool_parser_vllm.pyAdded+690