Text Generation
Transformers
Safetensors
qwen3_next
aicippy
aivedha
aivibe
coding-agent
code-generation
agentic-coding
conversational
Run this model with HF Jobs
Run aivedha/aicippy-Coder on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/aivedha/aicippy-Coder. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/aivedha/aicippy-Coder on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/aivedha/aicippy-Coder. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/aivedha/aicippy-Coder. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use aivedha/aicippy-Coder with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use aivedha/aicippy-Coder with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="aivedha/aicippy-Coder") 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("aivedha/aicippy-Coder") model = AutoModelForCausalLM.from_pretrained("aivedha/aicippy-Coder", 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 aivedha/aicippy-Coder with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "aivedha/aicippy-Coder" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "aivedha/aicippy-Coder", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/aivedha/aicippy-Coder
- SGLang
How to use aivedha/aicippy-Coder 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 "aivedha/aicippy-Coder" \ --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": "aivedha/aicippy-Coder", "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 "aivedha/aicippy-Coder" \ --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": "aivedha/aicippy-Coder", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use aivedha/aicippy-Coder with Docker Model Runner:
docker model run hf.co/aivedha/aicippy-Coder
Commit ·
656f5b3
0
Parent(s):
Duplicate from Qwen/Qwen3-Coder-Next
Browse filesCo-authored-by: cheng <littlebird13@users.noreply.huggingface.co>
This view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributesAdded+35
- README.mdAdded+208
- chat_template.jinjaAdded+117
- config.jsonAdded+44
- 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
- tokenizer.jsonAdded
1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208---library_name: transformerslicense: apache-2.0license_link: https://huggingface.co/Qwen/Qwen3-Coder-Next/blob/main/LICENSEpipeline_tag: text-generation---
# Qwen3-Coder-Next
## Highlights
Today, we're announcing **Qwen3-Coder-Next**, an open-weight language model designed specifically for coding agents and local development. It features the following key enhancements:
- **Super Efficient with Significant Performance**: With only 3B activated parameters (80B total parameters), it achieves performance comparable to models with 10–20x more active parameters, making it highly cost-effective for agent deployment.- **Advanced Agentic Capabilities**: Through an elaborate training recipe, it excels at long-horizon reasoning, complex tool usage, and recovery from execution failures, ensuring robust performance in dynamic coding tasks.- **Versatile Integration with Real-World IDE**: Its 256k context length, combined with adaptability to various scaffold templates, enables seamless integration with different CLI/IDE platforms (e.g., Claude Code, Qwen Code, Qoder, Kilo, Trae, Cline, etc.), supporting diverse development environments.


## Model Overview
**Qwen3-Coder-Next** has the following features:- Type: Causal Language Models- Training Stage: Pretraining & Post-training- 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://qwen.ai/blog?id=qwen3-coder-next), [GitHub](https://github.com/QwenLM/Qwen3-Coder), and [Documentation](https://qwen.readthedocs.io/en/latest/).
## Quickstart
We advise you to use the latest version of `transformers`.
The following contains a code snippet illustrating how to use the model generate content based on given inputs. ```pythonfrom transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "Qwen/Qwen3-Coder-Next"
# load the tokenizer and the modeltokenizer = AutoTokenizer.from_pretrained(model_name)model = AutoModelForCausalLM.from_pretrained( model_name, torch_dtype="auto", device_map="auto")
# prepare the model inputprompt = "Write a quick sort algorithm."messages = [ {"role": "user", "content": prompt}]text = tokenizer.apply_chat_template( messages, tokenize=False, add_generation_prompt=True,)model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
# conduct text completiongenerated_ids = model.generate( **model_inputs, max_new_tokens=65536)output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
content = tokenizer.decode(output_ids, skip_special_tokens=True)
print("content:", content)```
**Note: If you encounter out-of-memory (OOM) issues, consider reducing the context length to a shorter value, such as `32,768`.**
For local use, applications such as Ollama, LMStudio, MLX-LM, llama.cpp, and KTransformers have also supported Qwen3.
## Deployment
For deployment, you can use the latest `sglang` or `vllm` to create an OpenAI-compatible API endpoint.
### SGLang
[SGLang](https://github.com/sgl-project/sglang) is a fast serving framework for large language models and vision language models.SGLang could be used to launch a server with OpenAI-compatible API service.
`sglang>=v0.5.8` is required for Qwen3-Coder-Next, which can be installed using:```shellpip install 'sglang[all]>=v0.5.8'```See [its documentation](https://docs.sglang.ai/get_started/install.html) for more details.
The following command can be used to create an API endpoint at `http://localhost:30000/v1` with maximum context length 256K tokens using tensor parallel on 4 GPUs.```shellpython -m sglang.launch_server --model Qwen/Qwen3-Coder-Next --port 30000 --tp-size 2 --tool-call-parser qwen3_coder```
> [!Note]> The default context length is 256K. Consider reducing the context length to a smaller value, e.g., `32768`, if the server fails to start.
### vLLM
[vLLM](https://github.com/vllm-project/vllm) is a high-throughput and memory-efficient inference and serving engine for LLMs.vLLM could be used to launch a server with OpenAI-compatible API service.
`vllm>=0.15.0` is required for Qwen3-Coder-Next, which can be installed using:```shellpip install 'vllm>=0.15.0'```See [its documentation](https://docs.vllm.ai/en/stable/getting_started/installation/index.html) for more details.
The following command can be used to create an API endpoint at `http://localhost:8000/v1` with maximum context length 256K tokens using tensor parallel on 4 GPUs.```shellvllm serve Qwen/Qwen3-Coder-Next --port 8000 --tensor-parallel-size 2 --enable-auto-tool-choice --tool-call-parser qwen3_coder```
> [!Note]> The default context length is 256K. Consider reducing the context length to a smaller value, e.g., `32768`, if the server fails to start.
## Agentic Coding
Qwen3-Coder-Next excels in tool calling capabilities.
You can simply define or use any tools as following example.```python# Your tool implementationdef square_the_number(num: float) -> dict: return num ** 2
# Define Toolstools=[ { "type":"function", "function":{ "name": "square_the_number", "description": "output the square of the number.", "parameters": { "type": "object", "required": ["input_num"], "properties": { 'input_num': { 'type': 'number', 'description': 'input_num is a number that will be squared' } }, } } }]
from openai import OpenAI# Define LLMclient = OpenAI( # Use a custom endpoint compatible with OpenAI API base_url='http://localhost:8000/v1', # api_base api_key="EMPTY") messages = [{'role': 'user', 'content': 'square the number 1024'}]
completion = client.chat.completions.create( messages=messages, model="Qwen3-Coder-Next", max_tokens=65536, tools=tools,)
print(completion.choices[0])```
## Best Practices
To achieve optimal performance, we recommend the following sampling parameters: `temperature=1.0`, `top_p=0.95`, `top_k=40`.
## Citation
If 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}}```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 %}1234567891011121314151617181920212223242526272829303132333435363738394041424344{ "architectures": [ "Qwen3NextForCausalLM" ], "attention_bias": false, "attention_dropout": 0, "bos_token_id": 151643, "decoder_sparse_step": 1, "eos_token_id": 151645, "full_attention_interval": 4, "head_dim": 256, "hidden_act": "silu", "hidden_size": 2048, "initializer_range": 0.02, "intermediate_size": 5120, "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, "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, "torch_dtype": "bfloat16", "transformers_version": "4.57.0.dev0", "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:8e9a517133bfbdc6806cf8b61793055a260efeb68e6e019fd90e4bbb1b665d0asize 3999619288123version https://git-lfs.github.com/spec/v1oid sha256:0ab43285dec19a2eba2705538dfc914dd37b3c85477d3769054e44f300e659a3size 3999841816123version https://git-lfs.github.com/spec/v1oid sha256:68a5796b8bd75672e471daf4488bdb6c792ad895772efeacfdc41c09eeb3eb6bsize 3999515608123version https://git-lfs.github.com/spec/v1oid sha256:93f07b2ae634bdaee995c35d16d1186e7481f202e05095d17b1fc162e62c45f6size 3999842032123version https://git-lfs.github.com/spec/v1oid sha256:9832c0217fc2ff64f1a051769aa51c004b39fcc12d785e336217087c968651f5size 3999842240123version https://git-lfs.github.com/spec/v1oid sha256:983dce04bba12c65e457feeeb37cfb13756690b63d75d93cea3b56c361cd6859size 3999853248123version https://git-lfs.github.com/spec/v1oid sha256:41f27ff915d0797f6016d32d30beb3ab092b53e56ad99461d130854b2db64bc1size 3999841944123version https://git-lfs.github.com/spec/v1oid sha256:7382d1f4621bcef01ebf2df6ce855692f48bc94184bbfe2afab30b8d976c87desize 3999842032123version https://git-lfs.github.com/spec/v1oid sha256:8ba622e8d78aac210b56f250e3faa6c759ab858b3d683fc0520015a60d8674b2size 3999843224123version https://git-lfs.github.com/spec/v1oid sha256:0b5ca0b7ddaa8d5f481753d8357db9ec5c66485d93732168a7e216e8bfda6f1fsize 3999517840123version https://git-lfs.github.com/spec/v1oid sha256:e85c1ce556170c785b9479b2e0c8302e2a5bc69ccf44bdc2d8b5477d15cfb356size 4000181328123version https://git-lfs.github.com/spec/v1oid sha256:91f8c5b1a133c191348ac8631474e3114b8f084a68dc4eb93664130efd758b79size 3999843912123version https://git-lfs.github.com/spec/v1oid sha256:a571b802c7946fc33c90f4c5728c53505b5b94cb002a4567541a9a1899c07495size 3999517504123version https://git-lfs.github.com/spec/v1oid sha256:32e918bdba2d2b9b7ff866e361f99626f7df92299df1e5e195f85f1ea22c8911size 3999844016123version https://git-lfs.github.com/spec/v1oid sha256:496865f049712fb4176154f9a2c7d48063fe855a17b2ad025466a3a316692fb4size 4000181768123version https://git-lfs.github.com/spec/v1oid sha256:9f1ff8098b81710184f274232b04ca4fbdd820afd28213bde60e4630ed57048fsize 3999517280123version https://git-lfs.github.com/spec/v1oid sha256:04d03dd323e34ea5eb409a41685b515ef36d1c943c4546d31e9c73d96f8c0c7dsize 3999843912123version https://git-lfs.github.com/spec/v1oid sha256:cc03f69e8d061957d9b5d08b7da0b40d79b27a34e8c4c3fb8d503b123b268df1size 3999843912123version https://git-lfs.github.com/spec/v1oid sha256:040ea97dd90ebb9a183fdbcc1bdfba1228f1fc56eeb35dbd09fe3dc807dbae41size 3999844120123version https://git-lfs.github.com/spec/v1oid sha256:036b86c2808d34d0d6972424937753ca434713defe433b04c1cf1ddde4c77685size 3999855064123version https://git-lfs.github.com/spec/v1oid sha256:f93091cfc1df5f0d290b43517382f06cc96709b71cc494431d36c217d4e05035size 3999843824123version https://git-lfs.github.com/spec/v1oid sha256:1173933660614dbcd56463c30573e4bc52f8b3e674217294149abd0368332366size 3999843912123version https://git-lfs.github.com/spec/v1oid sha256:d6c7d46d0b74aba6b7125c4797393900cf54c8545fd0da99485f24df7309e470size 3999517496123version https://git-lfs.github.com/spec/v1oid sha256:e98c2798567def2ef801648b8e1ef5e0451a04dcb4586f19c7d6843c7e71160fsize 3999844296123version https://git-lfs.github.com/spec/v1oid sha256:14b34f3e8899eb81a427320b7a17d94387f2e762af8dadcf667c28957c46b992size 4000181328123version https://git-lfs.github.com/spec/v1oid sha256:8f0c2a1bae6835037643e18e3d964f3cd59679fe31ed2c57d3d3e0e2902ec3e0size 3999517504123version https://git-lfs.github.com/spec/v1oid sha256:2c2aefa4ae3e70a2275f151669076c857df1549c5d13458947a8f5459d5531f3size 3999843912123version https://git-lfs.github.com/spec/v1oid sha256:8f3f40bafcd7bd2d902813ee3110746c8f46f2f646d11cf4c4611cf59d39001fsize 3999844016123version https://git-lfs.github.com/spec/v1oid sha256:69f5a1c4f50c3d24fff41a7a0b4ef806c6ab1e2469f6523acbe0b6a7b6a840d2size 3999855352123version https://git-lfs.github.com/spec/v1oid sha256:518965232d096a23f01c9d955ad925828ed22e77e2a067013ba549820ad8231fsize 3999843704123version https://git-lfs.github.com/spec/v1oid sha256:a24847e00ccfb3b510135d245083622f6f3337c016aa80c5bafceabf584e63c4size 3999843912123version https://git-lfs.github.com/spec/v1oid sha256:605e2609278cd172ab8e0fab95e89fed2e7884b2bad378a516d35275812c9031size 3999843912123version https://git-lfs.github.com/spec/v1oid sha256:3d2aa165f7b0d2a8acb66d869f823d7aa6344db75c6e1be833480acc2b252fdfsize 3999517720123version https://git-lfs.github.com/spec/v1oid sha256:04bd78b03a131401169af0e67d96db5c6071631010ac19e9c0c9b7fb8c3f1871size 4000181528123version https://git-lfs.github.com/spec/v1oid sha256:eb6da0385f8ba56b98a6677bdc59f1c9cfff291024d61f26554b1881bba8edabsize 3999843824123version https://git-lfs.github.com/spec/v1oid sha256:4925757ada6c754070fd6381c5e01225ca51c19213c83011ba6c39e541dda984size 3999517504123version https://git-lfs.github.com/spec/v1oid sha256:12528012534bba5c61b237f3441864f55707ec050e1372d8eaaf9fdce259cffdsize 3999843904123version https://git-lfs.github.com/spec/v1oid sha256:58d4fd2e057fe619a690ee969bd79f85e45b0862df6a5a433abeff31abf03f7fsize 3999844296123version https://git-lfs.github.com/spec/v1oid sha256:407d45b48d0682469ac555c84c6aa3ce6ee8c56759074a532670a4ab035fade3size 3999854920123version https://git-lfs.github.com/spec/v1oid sha256:9606cbc3a087efaba8e17cb97b9d91cd8d25e6cba6958079d58c19871d272053size 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.gitattributesAdded+35
README.mdAdded+208
chat_template.jinjaAdded+117
config.jsonAdded+44
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
tokenizer.jsonAdded