# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Export editor schemas from the configuration types, without constructing an LLM.""" from __future__ import annotations import argparse import copy import json import runpy from functools import cache from pathlib import Path from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from pydantic.json_schema import JsonSchemaValue from pydantic_core import core_schema _DOCS_URL = "https://nvidia.github.io/TensorRT-LLM" _JSON_TYPES = {"string", "number", "integer", "boolean", "null", "array", "object"} SERVE_SCHEMA = "trtllm-serve-config.schema.json" DISAGG_SCHEMA = "trtllm-serve-disagg-config.schema.json" VISUAL_GEN_SCHEMA = "trtllm-serve-visual-gen-config.schema.json" _SCHEMA_COMMANDS = { SERVE_SCHEMA: "trtllm-serve --config", DISAGG_SCHEMA: "trtllm-serve disaggregated --config", VISUAL_GEN_SCHEMA: "trtllm-serve --visual_gen_args", } class _ServeSchemaGeneratorMixin: """Keep YAML-representable union branches and ignore autodoc-only type labels.""" # Recheck these overrides on Pydantic upgrades; they inspect its schema internals. def handle_invalid_for_json_schema( self, schema: core_schema.CoreSchema, error_info: str ) -> JsonSchemaValue: # Reject unsupported values without dropping the field or its nullable/union alternatives. return {"not": {}} def generate_inner(self, schema: core_schema.CoreSchema) -> JsonSchemaValue: metadata = schema.get("metadata", {}) extra = metadata.get("pydantic_js_extra") if isinstance(extra, dict) and isinstance(extra.get("type"), str): if extra["type"] not in _JSON_TYPES: schema = { **schema, "metadata": { **metadata, "pydantic_js_extra": { key: value for key, value in extra.items() if key != "type" }, }, } return super().generate_inner(schema) def model_fields_schema(self, schema: core_schema.ModelFieldsSchema) -> JsonSchemaValue: result = super().model_fields_schema(schema) properties = result["properties"] for field in schema["fields"].values(): aliases = field.get("validation_alias") if isinstance(aliases, list): names = [ alias[0] for alias in aliases if isinstance(alias, list) and len(alias) == 1 and isinstance(alias[0], str) ] if names and names[0] in properties: for name in names[1:]: properties[name] = copy.deepcopy(properties[names[0]]) return result def tagged_union_schema(self, schema: core_schema.TaggedUnionSchema) -> JsonSchemaValue: result = super().tagged_union_schema(schema) # Pydantic emits the tag's JSON name (alias resolved) only for field discriminators. tag = result.get("discriminator", {}).get("propertyName") if tag is not None: # Validation reads the tag before choosing a branch, so a mapping without it is # rejected even when the branch model defaults the field. Require it on the union # branches only; the shared definitions keep their Python defaults. for branch in result.get("oneOf", []): required = branch.setdefault("required", []) if tag not in required: required.append(tag) return result def dataclass_schema(self, schema: core_schema.DataclassSchema) -> JsonSchemaValue: result = super().dataclass_schema(schema) # These configs are constructed with **yaml_dict, which rejects unknown arguments. self.resolve_ref_schema(result)["additionalProperties"] = False return result @cache def _schema_generator() -> type: """Create the Pydantic generator only when full schema generation is requested.""" from pydantic.json_schema import GenerateJsonSchema class ServeSchemaGenerator(_ServeSchemaGeneratorMixin, GenerateJsonSchema): pass return ServeSchemaGenerator def _schema_for(annotation: Any, parent: dict | None = None) -> dict: from pydantic import TypeAdapter schema = TypeAdapter(annotation).json_schema(schema_generator=_schema_generator()) if parent is not None: definitions = parent.setdefault("$defs", {}) for name, definition in schema.pop("$defs", {}).items(): if name in definitions and definitions[name] != definition: raise ValueError(f"Conflicting schema definition: {name}") definitions[name] = definition return schema def _nullable(schema: dict) -> dict: return {"anyOf": [schema, {"type": "null"}]} def _dwdp_launch_rules() -> list[dict]: """``if``/``then`` rules mirroring ``TorchLlmArgs.validate_dwdp_launch()``. They hold only for values the YAML sets: a default, a ``--set`` value from the command line and, in a disaggregated configuration, a value a server inherits from the top level are left to runtime validation, so no rule requires a field. """ def when(dwdp: dict, **then: dict) -> dict: return { "if": { "properties": {"dwdp_config": {"type": "object", **dwdp}}, "required": ["dwdp_config"], }, "then": {"properties": then}, } def dwdp_fields(required: tuple[str, ...] = (), **values: object) -> dict: return { "properties": {name: {"const": value} for name, value in values.items()}, "required": list(required), } unset = {"type": "null"} return [ # Expert DWDP (enable_experts, True by default): a DWDP group of complete model replicas, # no CUDA graphs. when( dwdp_fields(enable_experts=True), dwdp_config={"properties": {"dwdp_size": {"minimum": 2}}}, cuda_graph_config=unset, pipeline_parallel_size={"const": 1}, context_parallel_size={"const": 1}, ), # Dense DWDP in either mode: eager execution and the features it rules out. when( dwdp_fields(("enable_dense",), enable_dense=True), cuda_graph_config=unset, torch_compile_config=unset, prefill_cuda_graph_backend={"const": "disabled"}, sleep_config=unset, lora_config=unset, speculative_config=unset, enable_locality_domains={"const": False}, pipeline_parallel_size={"const": 1}, context_parallel_size={"const": 1}, ), # Attached to expert DWDP: tensor parallel size 1, the overlap scheduler off. when( dwdp_fields(("enable_dense",), enable_dense=True, enable_experts=True), tensor_parallel_size={"const": 1}, disable_overlap_scheduler={"const": True}, ), # Standalone on an attention-DP instance. when( dwdp_fields(("enable_experts",), enable_experts=False), tensor_parallel_size={"minimum": 2}, enable_attention_dp={"const": True}, ), ] def _is_set_to(name: str, schema: dict) -> dict: """The mapping sets ``name`` (it is required) to a value that matches ``schema``.""" return {"properties": {name: schema}, "required": [name]} # KvCacheConfig fields of the overlap loop's deferred releases and KV cache host helper, with the # value that turns each on (llm_args._KV_CACHE_HOST_HELPER_FIELDS). _HOST_HELPER_FIELDS_ON = { "defer_generation_only_release": {"const": True}, "defer_context_only_release": {"const": True}, "deferred_release_thread": {"const": True}, "context_claim_ahead": {"type": "integer", "minimum": 1}, "context_prefetch_blocks": {"type": "integer", "minimum": 1}, } def _launch_rules() -> list[dict]: """Top-level ``if``/``then`` rules: DWDP and ``validate_defer_generation_only_release()``. ``_dwdp_launch_rules()``, plus ``TorchLlmArgs.validate_defer_generation_only_release()`` (the overlap loop without pipeline parallelism, for every host helper field). As there, values the YAML does not set are left to runtime validation. """ return _dwdp_launch_rules() + [ { "if": _is_set_to("kv_cache_config", {"type": "object", **_is_set_to(name, on)}), "then": { "properties": { "disable_overlap_scheduler": {"not": {"const": True}}, "pipeline_parallel_size": {"maximum": 1}, } }, } for name, on in _HOST_HELPER_FIELDS_ON.items() ] def _cross_field_rules(definitions: dict) -> None: """Mirror the model validators of the KV cache, scheduler and attention-DP options. They hold only for values the YAML sets; defaults are taken from the models. """ from tensorrt_llm.llmapi.llm_args import SchedulerConfig, WaitingQueuePolicy def default(model: type, name: str) -> dict: return {"const": model.model_fields[name].default} def when(condition: dict, then: dict) -> dict: return {"if": condition, "then": then} # RemoteCacheConfig.validate_remote_cache(). definitions["RemoteCacheConfig"]["anyOf"] = [ {"required": ["donor"], "properties": {"donor": {"type": "object"}}}, {"required": ["level"], "properties": {"level": {"type": "object"}}}, ] # KvCacheConfig.validate_remote_cache_config() and validate_defer_generation_only_release() (the host # helper fields). kv_v2 = {"properties": {"use_kv_cache_manager_v2": {"not": {"const": False}}}} definitions["KvCacheConfig"].setdefault("allOf", []).extend( [ when(_is_set_to("remote_cache_config", {"type": "object"}), kv_v2), *(when(_is_set_to(name, on), kv_v2) for name, on in _HOST_HELPER_FIELDS_ON.items()), when( _is_set_to("deferred_release_thread", {"const": True}), { "anyOf": [ _is_set_to("defer_generation_only_release", {"const": True}), _is_set_to("defer_context_only_release", {"const": True}), ] }, ), *( when( _is_set_to(name, _HOST_HELPER_FIELDS_ON[name]), {"properties": {"enable_block_reuse": {"not": {"const": False}}}}, ) for name in ("context_claim_ahead", "context_prefetch_blocks") ), # validate_disk_cache_config(): a page_staging_depth above 1 refuses busy-stream skipping. when( _is_set_to("page_staging_depth", {"type": "integer", "minimum": 2}), {"properties": {"copy_stream_busy_skip": {"maximum": 0}}}, ), when( _is_set_to("remote_cache_config", _is_set_to("level", {"type": "object"})), { "properties": { "disk_cache_size": {"enum": [0, None]}, "enable_kv_pool_rebalance": {"not": {"const": True}}, } }, ), ] ) # BlockReuseConfig.validate_drop_extended_turns_policy(). definitions["BlockReuseConfig"].setdefault("allOf", []).append( when( _is_set_to("drop_extended_turns", {"const": True}), _is_set_to("policy", {"const": "per_conversation"}), ) ) # AttentionDpConfig.validate_attention_dp_config(). home_wait = _is_set_to("kv_cache_routing_home_wait_rounds", {"type": "integer"}) definitions["AttentionDpConfig"].setdefault("allOf", []).extend( [ when(home_wait, _is_set_to("kv_cache_routing_conversation_affinity", {"const": True})), when( home_wait, { "properties": { "kv_cache_routing_strict_conversation_affinity": {"not": {"const": True}} } }, ), ] ) # SchedulerConfig.validate_waiting_queue_max_wait_s(). definitions["SchedulerConfig"].setdefault("allOf", []).append( when( { "not": _is_set_to( "waiting_queue_policy", {"const": WaitingQueuePolicy.PRIORITY.value}, ) }, { "properties": { "waiting_queue_max_wait_s": default(SchedulerConfig, "waiting_queue_max_wait_s") } }, ) ) def _any_case(token: str) -> str: """A pattern matching ``token`` in any case; JSON Schema patterns take no flags.""" return "".join(f"[{char}{char.upper()}]" if char.isalpha() else char for char in token) def _stripped_whitespace() -> str: r"""A pattern class of the characters ``str.strip()`` removes. ``\s`` is not that set: it also matches U+FEFF, which ``strip()`` keeps, and misses U+001C-U+001F and U+0085, which it removes. """ spaces = (char for char in map(chr, range(0x10000)) if char.isspace()) return "[" + "".join(f"\\u{ord(char):04x}" for char in spaces) + "]" def _moe_tactic_schema() -> dict: """The MoE tactics the runtime accepts, as far as patterns can tell. Every segment is ``*`` or a segment value in any case, around the whitespace the runtime strips, and not every segment is ``*``. Which values combine into an implementation id is left to the runtime. """ from dataclasses import fields from tensorrt_llm._torch.moe.fused_moe.impl_identity import MoEImplId from tensorrt_llm._torch.moe.fused_moe.moe_resolution import MOE_IMPL_REGISTRY values = "|".join(_any_case(token) for token in sorted(MOE_IMPL_REGISTRY.known_tokens())) segment = rf"(\*|{values})" more = len(fields(MoEImplId)) - 1 space = _stripped_whitespace() return { "type": "string", "pattern": rf"^{space}*{segment}(\.{segment}){{0,{more}}}{space}*$", "not": {"pattern": rf"^{space}*\*(\.\*){{0,{more}}}{space}*$"}, } def generate_serve_schema() -> dict: """Describe the YAML fragment merged with ordinary serving CLI arguments.""" schema = _serve_schema() _cross_field_rules(schema["$defs"]) return schema def _serve_schema() -> dict: """The serve schema without ``_cross_field_rules``, so that later merges see unmodified definitions.""" from tensorrt_llm.llmapi.disagg_utils import DisaggClusterConfig, InternalRequestAuthKey from tensorrt_llm.llmapi.llm_args import ( SERVE_CONFIG_ALIASES, MoeLoadBalancerConfig, MoePerLayerDynamicLoadBalancerConfig, TorchLlmArgs, ) # Annotated fields are derived; config changes still require snapshot regeneration and CPU tests. schema = _schema_for(TorchLlmArgs) # MODEL is supplied on the command line; nested required fields still apply. schema["required"] = [name for name in schema.get("required", []) if name != "model"] properties = schema["properties"] for alias, name in SERVE_CONFIG_ALIASES.items(): properties[alias] = copy.deepcopy(properties[name]) # Keep server-only fields aligned with serve.py. properties.update( allow_request_chat_template={"type": "boolean", "default": False}, internal_request_auth_key=_schema_for(InternalRequestAuthKey), disagg_cluster=_nullable(_schema_for(DisaggClusterConfig, schema)), ) # Serving treats null as unset before constructing the non-optional telemetry model. properties["telemetry_config"] = _nullable(properties["telemetry_config"]) # Keep accepted forms aligned with TorchLlmArgs.validate_load_balancer(): a mapping # without mode is standard EPLB, so only the per-layer dynamic form requires it. standard, per_layer_dynamic = ( {"$ref": f"#/$defs/{model.__name__}"} for model in (MoeLoadBalancerConfig, MoePerLayerDynamicLoadBalancerConfig) ) schema["$defs"]["MoeConfig"]["properties"]["load_balancer"]["anyOf"] = [ standard, {**per_layer_dynamic, "required": ["mode"]}, {"type": ["string", "null"]}, ] # The model validator allows at most one non-null preemption bound. schema["$defs"]["GenPreemptionConfig"]["anyOf"] = [ {"properties": {name: {"type": "null"}}} for name in ("tpot_budget", "target_output_tps") ] # Mirror DwdpConfig._validate_modes(): without expert DWDP, dense DWDP is on and the expert # fields keep their defaults; contention_opt, which selects batched copies, rules out another # copy_mode; and gather_kernel needs copy_mode gather. dwdp = schema["$defs"]["DwdpConfig"] expert_fields = ( "dwdp_size", "num_groups", "num_experts_per_worker", "num_prefetch_experts", "contention_opt", "num_prefetch_slots", ) dwdp["allOf"] = [ { "if": { "properties": {"enable_experts": {"const": False}}, "required": ["enable_experts"], }, "then": { "properties": { "enable_dense": {"const": True}, **{ name: {"const": dwdp["properties"][name]["default"]} for name in expert_fields }, }, "required": ["enable_dense"], }, }, { "if": { "properties": {"contention_opt": {"const": True}}, "required": ["contention_opt"], }, "then": {"properties": {"copy_mode": {"enum": ["batched", None]}}}, }, { "if": { "properties": {"gather_kernel": {"enum": ["register", "tma"]}}, "required": ["gather_kernel"], }, "then": { "properties": {"copy_mode": {"const": "gather"}}, "required": ["copy_mode"], }, }, ] # Mirror DwdpConfig._validate_expert_partition(): both fields 0 (or absent), or both positive. pair = ("num_experts_per_worker", "num_prefetch_experts") dwdp["anyOf"] = [ {"properties": {name: {"const": 0} for name in pair}}, {"properties": {name: {"minimum": 1} for name in pair}, "required": list(pair)}, ] # Mirror the MoE tactic validators of MoeConfig and of every decoding # config as far as a schema can, and that a tactic excludes any backend # but AUTO (or unset, where that is allowed). schema["$defs"]["MoeTactic"] = _moe_tactic_schema() def mirror_moe_tactic_validators( config_schema: dict, backend: str, tactic: str, admitted_backend: dict ) -> None: branches = config_schema["properties"][tactic]["anyOf"] branches[:] = [ {"$ref": "#/$defs/MoeTactic"} if branch.get("type") == "string" else branch for branch in branches ] config_schema["not"] = { "required": [backend, tactic], "properties": {backend: {"not": admitted_backend}, tactic: {"type": "string"}}, } mirror_moe_tactic_validators( schema["$defs"]["MoeConfig"], "backend", "tactic", {"const": "AUTO"} ) for definition in schema["$defs"].values(): if "moe_tactic" in definition.get("properties", {}): mirror_moe_tactic_validators( definition, "moe_backend", "moe_tactic", {"enum": ["AUTO", None]} ) # MultimodalConfig normalizes encoder backend names before Literal validation. encoder_backend = schema["$defs"]["MultimodalConfig"]["properties"][ "encoder_attention_backend" ]["anyOf"][0]["additionalProperties"] alternatives = [ "".join(f"[{char}{char.lower()}]" for char in name) for name in encoder_backend.pop("enum") ] encoder_backend["pattern"] = "^(?:" + "|".join(alternatives) + r")$(?![\s\S])" # These object/Any annotations are Python API hooks, not arbitrary YAML mappings. # Update these restrictions when hooks are added or gain YAML construction support. for name in ("batched_logits_processor", "checkpoint_loader", "_mpi_session"): properties[name] = { "type": "null", "description": "Live objects require the Python LLM API.", } schema["allOf"] = _launch_rules() schema["$defs"]["RayPlacementConfig"]["properties"]["placement_groups"] = {"type": "null"} user_draft = schema["$defs"]["UserProvidedDecodingConfig"]["properties"] user_draft["drafter"] = {"not": {}, "description": "A Drafter requires the Python LLM API."} user_draft["resource_manager"] = {"type": "null"} # Update this mapping exception when the YAML loader changes legacy DecodingConfig support. properties["decoding_config"] = {"type": ["object", "null"]} return schema def _router_schema(router_type: dict) -> dict: """A disaggregated server block's ``router`` mapping, with pooled generation dispatch's startup rules. Mirrors extract_disagg_cfg() (``max_queue_wait_s`` needs ``max_requests_per_server``), create_router() (pooling needs the ``load_balancing`` type, matched case-insensitively), PooledLoadBalancingRouter (no ``use_tokens``) and SeatPool (seats an integer >= 1, wait > 0). A null value is unset, as at runtime. """ pooled_type = "load_balancing" any_case = "".join(f"[{c.lower()}{c.upper()}]" if c.isalpha() else c for c in pooled_type) falsy = [False, None, 0, "", [], {}] return { "type": "object", "properties": { "type": router_type, "max_requests_per_server": { "type": ["integer", "null"], "minimum": 1, "description": "Pooled generation dispatch: requests each generation server runs at once " "(load_balancing generation router only).", }, "max_queue_wait_s": { "type": ["number", "null"], "exclusiveMinimum": 0, "description": "Pooled generation dispatch: seconds after which a waiting request goes " "first (needs max_requests_per_server).", }, }, "additionalProperties": True, "allOf": [ { "if": _is_set_to("max_queue_wait_s", {"type": "number"}), "then": _is_set_to("max_requests_per_server", {"type": "integer"}), }, { "if": _is_set_to("max_requests_per_server", {"type": "integer"}), "then": { "properties": { "type": {"type": "string", "pattern": f"^{any_case}$"}, "use_tokens": {"enum": falsy}, }, "required": ["type"], }, }, ], } def generate_disagg_schema() -> dict: """Describe orchestrator options and the inherited per-role worker options.""" from tensorrt_llm.llmapi.disagg_utils import ( DISAGG_NODE_ID_BITS, ConditionalDisaggConfig, OtlpConfig, RouterConfig, extract_ctx_gen_cfgs, extract_disagg_cfg, ) from tensorrt_llm.llmapi.llm_args import SERVE_CLI_CONFIG_FIELDS, TorchLlmArgs schema = _serve_schema() properties = schema["properties"] for config_name, aliases in SERVE_CLI_CONFIG_FIELDS.items(): config = _schema_for(TorchLlmArgs.model_fields[config_name].annotation, schema) for name, field in aliases.items(): properties[name] = copy.deepcopy(config["properties"][field]) worker = _schema_for(extract_ctx_gen_cfgs, schema) # Only type is required and supplied internally; revisit if worker inputs gain required fields. worker["properties"].pop("type") worker.pop("required", None) worker["properties"] = properties | worker["properties"] # YAML flattens router-specific args alongside the shared type field. Unknown args stay accepted; # the pooled generation dispatch keys are typed. worker["properties"]["router"] = _router_schema( _schema_for(RouterConfig, schema)["properties"]["type"] ) worker["additionalProperties"] = False worker["allOf"] = _launch_rules() schema["$defs"]["DisaggServerBlock"] = worker orchestrator = _schema_for(extract_disagg_cfg, schema)["properties"] # Update these refinements when extract_disagg_cfg() changes its untyped mapping inputs. for name in ("context_servers", "generation_servers"): orchestrator[name] = _nullable({"$ref": "#/$defs/DisaggServerBlock"}) # PooledLoadBalancingRouter refuses the context role. orchestrator["context_servers"]["anyOf"][0] = { "allOf": [ {"$ref": "#/$defs/DisaggServerBlock"}, { "properties": { "router": {"properties": {"max_requests_per_server": {"type": "null"}}} } }, ] } orchestrator["conditional_disagg_config"] = _nullable( _schema_for(ConditionalDisaggConfig, schema) ) orchestrator["otlp_config"] = _nullable(_schema_for(OtlpConfig, schema)) orchestrator["disagg_cluster"] = properties["disagg_cluster"] orchestrator["internal_request_auth_key"] = properties["internal_request_auth_key"] # Mirror extract_disagg_cfg()'s node_id validation; the bit limit is shared. orchestrator["node_id"] = { "type": ["integer", "null"], "minimum": 0, "maximum": (1 << DISAGG_NODE_ID_BITS) - 1, } properties.update(orchestrator) # Mirror extract_disagg_cfg(): output-length prediction needs the context-first schedule. schema.setdefault("allOf", []).append( { "if": _is_set_to("output_length_prediction", {"type": "object"}), "then": {"properties": {"schedule_style": {"not": {"const": "generation_first"}}}}, } ) _cross_field_rules(schema["$defs"]) return schema def generate_visual_gen_schema() -> dict: """Describe the separate VisualGen engine-args YAML file.""" from tensorrt_llm.visual_gen.args import VisualGenArgs return _schema_for(VisualGenArgs) def _source_version() -> str: version_file = Path(__file__).resolve().parents[1] / "tensorrt_llm/version.py" version = runpy.run_path(str(version_file)).get("__version__") if not isinstance(version, str) or not version: raise ValueError(f"Missing __version__ string in {version_file}") return version def _set_schema_version_metadata(schema: dict, filename: str, command: str, version: str) -> None: schema["$id"] = f"{_DOCS_URL}/{version}/_static/schemas/{filename}" schema["title"] = f"TensorRT-LLM {version} {command}" def _set_schema_metadata(schema: dict, filename: str, command: str, version: str) -> None: schema.update( { "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. " "All rights reserved. SPDX-License-Identifier: Apache-2.0. " "Generated by scripts/generate_trtllm_serve_schemas.py; do not edit by hand.", "$schema": "https://json-schema.org/draft/2020-12/schema", "description": "Static YAML checks only; runtime validation remains authoritative.", } ) _set_schema_version_metadata(schema, filename, command, version) def _raise_stale(stale: list[str], *, sync_version: bool = False) -> None: if stale: command = "python3 scripts/generate_trtllm_serve_schemas.py" if sync_version: command += " --sync-version" raise ValueError( f"Missing or stale configuration schemas: {', '.join(stale)}. " f"Run {command} and commit the updated JSON." ) def write_schemas(output_dir: Path, *, check: bool = False) -> list[Path]: """Write or check self-contained schemas for the source package version.""" version = _source_version() schemas = { SERVE_SCHEMA: generate_serve_schema(), DISAGG_SCHEMA: generate_disagg_schema(), VISUAL_GEN_SCHEMA: generate_visual_gen_schema(), } if not check: output_dir.mkdir(parents=True, exist_ok=True) paths = [] stale = [] for filename, command in _SCHEMA_COMMANDS.items(): schema = schemas[filename] _set_schema_metadata(schema, filename, command, version) path = output_dir / filename content = json.dumps(schema, indent=2, sort_keys=True) + "\n" if check: if not path.is_file() or path.read_text(encoding="utf-8") != content: stale.append(filename) else: path.write_text(content, encoding="utf-8") paths.append(path) _raise_stale(stale) return paths def sync_schema_version_metadata(output_dir: Path, *, check: bool = False) -> list[Path]: """Update version-derived metadata without importing TensorRT-LLM or Pydantic.""" version = _source_version() paths = [] updates = {} missing = [] for filename, command in _SCHEMA_COMMANDS.items(): path = output_dir / filename paths.append(path) if not path.is_file(): missing.append(filename) continue schema = json.loads(path.read_text(encoding="utf-8")) original_metadata = (schema.get("$id"), schema.get("title")) _set_schema_version_metadata(schema, filename, command, version) if original_metadata != (schema["$id"], schema["title"]): updates[path] = json.dumps(schema, indent=2, sort_keys=True) + "\n" if missing: raise ValueError( f"Cannot sync version metadata for missing schemas: {', '.join(missing)}. " "Run python3 scripts/generate_trtllm_serve_schemas.py with a matching build first." ) if check: _raise_stale([path.name for path in updates], sync_version=True) else: for path, content in updates.items(): path.write_text(content, encoding="utf-8") return paths def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--output-dir", type=Path, default=Path(__file__).resolve().parents[1] / "tensorrt_llm/schemas", help="Destination directory (defaults to the checked-in schemas).", ) parser.add_argument( "--check", action="store_true", help="Fail on missing or stale schemas without writing." ) parser.add_argument( "--sync-version", action="store_true", help="Update only version-derived metadata without importing project dependencies.", ) args = parser.parse_args() writer = sync_schema_version_metadata if args.sync_version else write_schemas for path in writer(args.output_dir, check=args.check): print(path) if __name__ == "__main__": main()