llm-router-utils
Lightweight extraction of sglang's reasoning parser, tool-call parser, and chat template rendering, for use in custom router services and lightweight LLM applications.
This library does not include any inference engine code. It only provides the "frontend" message processing pipeline: OpenAIServingChat._process_messages and its dependencies.
Installation
pip install llm-router-utils
CPU-only torch (optional, smaller on Linux)
This library depends on xgrammar, which declares torch>=1.10.0. By default pip pulls the CUDA-enabled torch wheel from PyPI (~502 MB on Linux x86_64). Routers don't use torch for GPU ops — only a lazy torch.version.hip / torch.npu.is_available() probe that returns False when torch is absent — so CPU-only torch is sufficient.
To install CPU-only torch, install it from the PyTorch CPU index before this package:
pip install torch --index-url https://download.pytorch.org/whl/cpu
pip install llm-router-utils
The second command sees torch already satisfied and skips the CUDA download. On Linux x86_64 this saves ~319 MB (502 → 183). On Windows there is no size difference (both ~116 MB), so this step is only useful on Linux.
Usage
from llm_router_utils.sglang.srt.configs.model_config import ModelConfig
from llm_router_utils.sglang.srt.managers.tokenizer_manager import TokenizerManager
from llm_router_utils.sglang.srt.parser.template_manager import TemplateManager
from llm_router_utils.sglang.srt.entrypoints.openai.serving_chat import OpenAIServingChat
from llm_router_utils.sglang.srt.server_args import ServerArgs, PortArgs
server_args = ServerArgs(model_path="Qwen/Qwen3-32B", tool_call_parser="qwen3_coder")
port_args = PortArgs()
tokenizer_manager = TokenizerManager(server_args, port_args)
template_manager = TemplateManager()
template_manager.initialize_templates(
tokenizer_manager=tokenizer_manager,
model_path=server_args.model_path,
chat_template=server_args.chat_template,
)
openai_serving_chat = OpenAIServingChat(tokenizer_manager, template_manager)
result = openai_serving_chat._process_messages(request, is_multimodal=False)
What's included
Migrated modules under llm_router_utils/sglang/srt/ (paths preserved from upstream):
| Module | Description |
|---|---|
parser/ |
Conversation templates (~50 model families), ReasoningParser + detectors, harmony/inkling, jinja utils, template detection, TemplateManager with TokenizerLike Protocol |
function_call/ |
FunctionCallParser + 44 detectors (hermes, glm, deepseek, qwen, kimi, mistral, muse-glimmer, …), JsonArrayParser, schema utils |
entrypoints/openai/ |
protocol.py (full OpenAI types), serving_chat.py (identical to upstream apart from import rewriting), serving_base.py (slimmed: HTTP entry points dropped, but the full helper surface serving_chat.py calls is retained), chat_encoding.py + chat_encoding_adapters.py, encoding_dsv32.py, serving_deepseek_recipe.py, serving_inkling.py, parallel_prompt_encode.py, sse_utils.py, usage_processor.py, utils.py |
parser/chat_parsing/ |
Response-template parsers (response_parser.py, content_parsers.py, response_templates.py) backing the template tool-call/reasoning detectors |
parser/response_template.py |
ResponseTemplate*Detector family plus response-template request configuration and grammar helpers |
function_call/response_template_structural_tag.py |
Structural tags derived from a chat template's own framing; used by beam_detector.py |
managers/ |
Slimmed TokenizerManager (uses upstream get_tokenizer for byte-parity incl. SGLANG_PATCH_TOKENIZER), slimmed io_struct.py, embed_types.py stub |
configs/ |
Slimmed ModelConfig (uses upstream get_config; exposes hf_config/is_multimodal/get_default_sampling_params/context_length), model_config_parser_registry.py |
tokenizer/ |
tiktoken_tokenizer.py |
disaggregation/ |
kv_events.py — KV cache event structs (EventBatch, KVCacheEvent, StorageMedium, BlockStored, BlockRemoved, AllBlocksCleared, KVEventBatch) |
mem_cache/ |
utils.py — pure-Python SHA256 hash helpers, byte-identical to sglang's C++ extension |
observability/ |
metrics_collector.py — data classes only: QueueCount, SchedulerStats, compute_routing_key_stats. Heavy *MetricsCollector classes stripped |
utils/hf_transformers/ |
Restored common.py/config.py/tokenizer.py/mistral_utils.py — upstream get_tokenizer/get_config. Slimmed hf_transformers_patches.py (torch-free only). patch_tokenizer.py verbatim |
connector/ (stub) |
create_remote_connector raises NotImplementedError |
| Top-level slimmed files | environ.py (env var registry) · server_args.py (device/revision/tokenizer_backend + PortArgs.init_new) · srt/utils/common.py (ImageData/VideoData/read_system_prompt_from_file + hf helpers) · sglang/utils.py (convert_json_schema_to_str/is_in_ci/TypeBasedDispatcher/LazyImport) |
What's NOT included
Inference engine code is intentionally stripped: schedulers, model loaders, layer implementations, CUDA/Triton kernels, sampling, constrained decoding, speculative decoding, LoRA runtime, distributed runtime, KV cache manager, HTTP server, multimodal processing, observability, and all CLI/launch scripts.
Version Mapping
The mapping between this repo's releases and upstream sglang versions, so users can find the release that matches a given sglang version:
| This repo | Upstream sglang |
|---|---|
v0.2.2 |
v0.5.16 |
v0.3.0 |
v0.5.17 |
v0.4.0 |
v0.5.18 |
v0.5.0 |
v0.5.19 |
v0.5.1 |
v0.5.19 |
v0.6.0 |
v0.5.20 |
v0.7.0 |
v0.5.21 |
v0.8.0 |
v0.5.22 |
v0.8.1 |
v0.5.22 |
v0.9.0 |
v0.5.23 |
See DEVELOPMENT.md for the development workflow (upgrades, checks, releases).
Platform note (since v0.9.0)
sglang v0.5.23 moved two capabilities out of its own tree into compiled platform-specific extensions:
| Capability | Package | Wheels |
|---|---|---|
| DeepSeek-V4 / V4.1 prompt encoding | deepseek-recipe==0.2.0 |
Linux (x86_64, aarch64), macOS |
| Inkling rendering | tml-renderers (inkling extra) |
Linux (x86_64, aarch64), macOS arm64 |
Neither publishes a Windows wheel, and upstream pins both with matching
platform markers. This package mirrors those markers, so on Windows these
extensions are simply not installed and the affected encoders raise an
ImportError naming the missing package.
Everything else is unaffected. Both encoders are selected per model and imported lazily, so a service that serves any other model family — Llama, Qwen, GLM, Kimi, Hermes, Mistral, and so on — never touches either package and behaves exactly as before on every platform.
When dsv4 / dsv41 is affected
The DeepSeek-V4/V4.1 path is selected by exactly two things
(chat_encoding.resolve_chat_encoding_spec): the model architecture, or an
explicit parser flag.
| Trigger | Example |
|---|---|
| The model architecture | DeepseekV4ForCausalLM, DeepseekV41ForCausalLM |
| An explicit parser flag | --tool-call-parser deepseekv4 / deepseekv41 |
| Model / setting | Encoding spec | Needs deepseek-recipe |
|---|---|---|
LlamaForCausalLM, Qwen2ForCausalLM, DeepseekV3ForCausalLM, … |
None |
no |
DeepseekV4ForCausalLM |
dsv4 |
yes |
DeepseekV41ForCausalLM |
dsv41 |
yes |
deepseekv32 is not affected — DeepSeek-V3.2 still renders through the
in-tree encoding_dsv32.py.
So: only serving a DeepSeek-V4/V4.1 checkpoint, or explicitly selecting that parser, is unavailable on Windows. Everything else works normally.
Two caveats on the ImportError:
- For
dsv4/dsv41, a checkpoint whose tokenizer has notokenizer.jsonfails earlier withValueError: deepseek-recipe needs the checkpoint's fast tokenizer, because the tokenizer check precedes the package import. Use a fast-tokenizer checkpoint to see the missing-package message. tml-rendererspublishescp311-abi3wheels only and ships no sdist, so theinklingextra requires Python >= 3.11 even though the base package supports 3.10.
Relative to v0.8.x, which shipped in-tree dsv4/dsv41 encoders, this is a
capability removal scoped to those two architectures on Windows; it follows
upstream sglang v0.5.23. The encoding_dsv4.py/encoding_dsv41.py module paths
no longer exist on any platform.
Serving several models from one process
Each TokenizerManager registers its config as a process-level default, so
the one constructed last wins. Single-model services are unaffected. A router
that builds more than one manager must scope both construction and request
handling, because the two groups read the global at different times:
| Field | When it is read | Scope needed |
|---|---|---|
hf_chat_template_name |
template initialisation | construction |
default_chat_template_kwargs |
OpenAIServingChat.__init__ |
construction |
encoding adapter's revision |
OpenAIServingChat.__init__ |
construction |
enable_cache_report |
per request | each request |
incremental_streaming_output |
per request | each request |
return_input_ids / return_output_ids |
per request | each request |
stream_response_default_include_usage |
per request | each request |
allow_auto_truncate |
per request | each request |
trust_request_chat_template |
per request | each request |
Scope construction, then scope each request:
from llm_router_utils.sglang.srt.runtime_context import use_runtime_context
# 1. Build each model's objects inside that model's scope.
with use_runtime_context(server_args=a_args, model_config=a_model_config):
manager = TokenizerManager(a_args, port_args)
template_manager = TemplateManager()
template_manager.initialize_templates(
tokenizer_manager=manager,
model_path=a_args.model_path,
chat_template=a_args.chat_template,
)
serving = OpenAIServingChat(manager, template_manager)
# 2. Serve each request inside the same scope, because the per-request
# fields above are read from the global on every call.
with use_runtime_context(server_args=a_args, model_config=a_model_config):
result = serving._process_messages(request, is_multimodal=False)
Repeat per model, so each instance is built while its own config is in scope.
Do not wrap only request handling. After model B is built, model A's already-constructed objects no longer see their own
hf_chat_template_nameordefault_chat_template_kwargs; a request-scopeduse_runtime_contextleaves A serving with B's setup-time values.
License
Apache 2.0, adapted from sglang.
This is a derivative work of sglang. The upstream copyright notice is retained
in LICENSE and NOTICE per Apache 2.0 §4(b)/§4(c).
Retained source files keep their upstream copyright headers; slimmed files
carry both the upstream header and a "Derivative work" notice. See
DEVELOPMENT.md for the trimming rules.
Metadata
Release files for llm-router-utils 0.9.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| llm_router_utils-0.9.0.tar.gz | 434.1 kB | With provenance | Details for llm_router_utils-0.9.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| llm_router_utils-0.9.0-py3-none-any.whl | Python 3 | none | any | Details for llm_router_utils-0.9.0-py3-none-any.whl |
Total release size: 947.8 kB
Release files / llm_router_utils-0.9.0.tar.gz
| Download URL | llm_router_utils-0.9.0.tar.gz |
|---|---|
| Size | 434.1 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
9c60532235bca37f179f871754c3d437f58f6c360e2014661c426cbcc4eb6af6
|
|
BLAKE2b-256 checksum How to use checksums |
104a722fd50aa423627c96e6a54f9b97b07a10a24b6bb058bca862e85b1d1a56
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 9, 2026.
Transparency logRelease files / llm_router_utils-0.9.0-py3-none-any.whl
| Download URL | llm_router_utils-0.9.0-py3-none-any.whl |
|---|---|
| Size | 513.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
800ae17bc3fea107d0d35c4cab1a8fcedf9cc431acb48cdfa7b01cef6968e41b
|
|
BLAKE2b-256 checksum How to use checksums |
fd21356e80a7d1b9cac82e6ac32368b9f31959bf034059d74bd224958875722c
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 9, 2026.
Transparency logSecurity for llm-router-utils 0.9.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for llm_router_utils-0.9.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 9, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.