ODS V3 Pre-Release: Public testing and refinement ahead of the official V3 launch. Turn your PC, Mac, or Linux box into a private AI server.
Python ai-agentsamdcomfyuidockerllama-cppllmlocal-ain8nnvidiaopen-webuiragself-hostedspeech-to-textstrix-halotext-to-speechworkflow-automation
"""ODS model-router: the stable-alias data plane (Switchboard PR 3).
One job: requests arrive for the public alias (``ods/current`` or a
compatibility alias), and the router forwards them to the concrete backend
and runtime model named by the host agent's ``model-state.json`` — rewriting
the request ``model`` on the way in and restoring the requested alias on the
way out (including every SSE chunk).
Security boundary (plan §3.6):
- Internal Compose service only; no host port. Only the explicit OpenAI
paths below are forwarded; everything else is rejected.
- ``endpointId`` resolves through a read-only allowlist file generated at
install; state can never name an arbitrary upstream.
- Hop-by-hop and client authorization headers are stripped; backend
credentials come from the router's own environment.
- Bounded body size, queue depth, and timeouts, all covered by tests.
Route evidence (plan §3.4): bounded in-memory records correlated by a
signed probe marker, exposed only on the internal network with a bearer
key. No prompts, generations, or credentials are ever stored.
"""
from __future__ import annotations
import asyncio
import base64
import copy
import hashlib
import hmac
import json
import logging
import os
import re
import time
import uuid
from collections import OrderedDict
from contextlib import suppress
from pathlib import Path
from typing import Any, AsyncIterator
import anyio
import httpx
from jsonschema import validators as jsonschema_validators
from jsonschema.exceptions import SchemaError, ValidationError, best_match
from fastapi import FastAPI, Request, Response
from fastapi.responses import JSONResponse, StreamingResponse
from .completed_tool_sse import (
CompletionStreamIdentityError, assemble_chat_completion_sse, response_reports_failure,
completion_stream_rejection_code,
)
from .probe_attempts import ProbeAttempts
from .tool_id_compat import normalize_history_tool_ids, route_requires_strict9_tool_ids
logging.basicConfig(level=os.environ.get("LOG_LEVEL", "INFO"))
logger = logging.getLogger("ods-model-router")
PUBLIC_ALIASES = ("ods/current", "default")
STATE_PATH = Path(os.environ.get("ODS_MODEL_STATE_PATH", "/state/model-state.json"))
ENDPOINTS_PATH = Path(
os.environ.get("ODS_ROUTER_ENDPOINTS_PATH", "/config/endpoints.json")
)
INTERNAL_KEY = os.environ.get("ODS_ROUTER_INTERNAL_KEY", "") or os.environ.get(
"DASHBOARD_API_KEY", ""
)
PROBE_KEY = os.environ.get("ODS_FLEET_PROBE_KEY", "")
_PROBE_KEY_PATH_VALUE = os.environ.get("ODS_FLEET_PROBE_KEY_PATH", "")
PROBE_KEY_PATH: Path | None = (
Path(_PROBE_KEY_PATH_VALUE) if _PROBE_KEY_PATH_VALUE else None
)
INSTANCE_ID = str(uuid.uuid4())
MAX_BODY_BYTES = int(os.environ.get("ODS_ROUTER_MAX_BODY_BYTES", str(16 * 1024 * 1024)))
MAX_QUEUE_DEPTH = int(os.environ.get("ODS_ROUTER_MAX_QUEUE_DEPTH", "64"))
QUEUE_WAIT_SECONDS = int(os.environ.get("ODS_ROUTER_QUEUE_WAIT_SECONDS", "600"))
UPSTREAM_TIMEOUT_SECONDS = float(os.environ.get("ODS_ROUTER_UPSTREAM_TIMEOUT", "600"))
UPSTREAM_MAX_CONNECTIONS = max(
1, int(os.environ.get(
"ODS_ROUTER_UPSTREAM_MAX_CONNECTIONS", str(MAX_QUEUE_DEPTH)
))
)
UPSTREAM_MAX_KEEPALIVE = max(
0, int(os.environ.get("ODS_ROUTER_UPSTREAM_MAX_KEEPALIVE", "20"))
)
TOKEN_SPY_URL = os.environ.get("TOKEN_SPY_URL", "").rstrip("/")
TOKEN_SPY_API_KEY = os.environ.get("TOKEN_SPY_API_KEY", "")
TELEMETRY_QUEUE_DEPTH = max(
1, int(os.environ.get("ODS_ROUTER_TELEMETRY_QUEUE_DEPTH", "1024"))
)
TELEMETRY_TIMEOUT_SECONDS = max(
0.1, float(os.environ.get("ODS_ROUTER_TELEMETRY_TIMEOUT", "3"))
)
EVIDENCE_LIMIT = 2048
EVIDENCE_TTL_SECONDS = 15 * 60
TOOL_EVIDENCE_MAX_COUNT = 256
TOOL_EVIDENCE_MAX_BYTES = 256 * 1024
MAX_COMPLETED_TOOL_STREAM_BYTES = 16 * 1024 * 1024
FORWARD_PATHS = {
"/v1/chat/completions": "POST",
"/v1/completions": "POST",
"/v1/responses": "POST",
}
_HOP_BY_HOP = {
"connection", "keep-alive", "proxy-authenticate", "proxy-authorization",
"te", "trailer", "transfer-encoding", "upgrade", "host", "authorization",
"content-length",
"x-ods-expected-catalog", "x-ods-expected-model", "x-ods-expected-route",
}
_PROBE_RE = re.compile(
r"\[ODS_PROBE id=([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}) "
r"sig=([A-Za-z0-9_-]+)\]"
)
_SSE_DELIMITER_RE = re.compile(rb"(?:\r\n|\r(?!\n)|(?<!\r)\n){2}")
_CHAT_TEMPLATE_ARTIFACTS = (
re.compile(r"<\|im_start\|>\s*(?:assistant|user|system|tool)?\s*<\|im_end\|>"),
re.compile(r"<\|start_header_id\|>\s*(?:assistant|user|system|tool)?\s*<\|end_header_id\|>"),
re.compile(r"<\|(?:im_start|im_end|eot_id|endoftext|end)\|>"),
)
_NATIVE_FUNCTION_NAME = r"[A-Za-z_][A-Za-z0-9_-]{0,127}"
_NATIVE_CALL = re.compile(
rf"<tool_call>\r?\n<function=({_NATIVE_FUNCTION_NAME})>\r?\n"
r"(.*?)\r?\n</function>\r?\n</tool_call>", re.DOTALL,
)
_NATIVE_PARAMETER = re.compile(
rf"<parameter=({_NATIVE_FUNCTION_NAME})>\r?\n(.*?)\r?\n</parameter>",
re.DOTALL,
)
_MAX_NATIVE_CALLS = 8
_MAX_NATIVE_MARKUP_CHARS = 32_768
def _schema_has_references(value: Any) -> bool:
"""Keep normalization local; advertised schemas must not resolve URLs."""
if isinstance(value, dict):
return any(
key in {"$ref", "$dynamicRef", "$recursiveRef"}
or _schema_has_references(child)
for key, child in value.items()
)
if isinstance(value, list):
return any(_schema_has_references(child) for child in value)
return False
def _complete_native_envelope_names(completion: dict[str, Any]) -> list[str] | None:
"""Recognize the whole native envelope before considering a repair.
This deliberately does not infer a tool from prose, examples, or a partial
prefix. Semantic checks against the request's tools happen separately.
"""
choices = completion.get("choices")
if not isinstance(choices, list) or len(choices) != 1:
return None
choice = choices[0]
if not isinstance(choice, dict) or choice.get("finish_reason") != "stop":
return None
message = choice.get("message")
if (not isinstance(message, dict) or message.get("role") != "assistant"
or "tool_calls" in message or message.get("refusal")):
return None
content = message.get("content")
if (not isinstance(content, str) or not content
or len(content) > _MAX_NATIVE_MARKUP_CHARS):
return None
markup = content.strip()
if not markup.startswith("<tool_call>"):
return None
names: list[str] = []
cursor = 0
while cursor < len(markup):
match = _NATIVE_CALL.match(markup, cursor)
if match is None or len(names) >= _MAX_NATIVE_CALLS:
return None
parameter_markup = match.group(2)
parameter_cursor = 0
while parameter_cursor < len(parameter_markup):
parameter_match = _NATIVE_PARAMETER.match(
parameter_markup, parameter_cursor,
)
if parameter_match is None:
return None
parameter_cursor = parameter_match.end()
if parameter_cursor < len(parameter_markup):
separator = re.match(r"\r?\n", parameter_markup[parameter_cursor:])
if separator is None:
return None
parameter_cursor += separator.end()
names.append(match.group(1))
cursor = match.end()
if cursor < len(markup):
separator = re.match(r"\r?\n", markup[cursor:])
if separator is None:
return None
cursor += separator.end()
return names or None
def _repairable_native_tool_request(payload: dict[str, Any]) -> bool:
offered = payload.get("tools")
if not isinstance(offered, list) or not offered:
return False
choice = payload.get("tool_choice", "auto")
if isinstance(choice, str):
return choice in {"auto", "required"}
return (isinstance(choice, dict) and choice.get("type") == "function"
and isinstance(choice.get("function"), dict)
and isinstance(choice["function"].get("name"), str))
def _native_tool_repair_feedback(
names: list[str], payload: dict[str, Any],
) -> str:
offered = [
item["function"]["name"]
for item in payload["tools"]
if isinstance(item, dict) and item.get("type") == "function"
and isinstance(item.get("function"), dict)
and isinstance(item["function"].get("name"), str)
]
# The original request retains the exact, authoritative JSON Schemas. Do
# not synthesize aliases or copy long tool descriptions into the context.
unknown = [name for name in names if name not in offered]
issue = ("Unknown function name(s): " + ", ".join(unknown) + ". "
if unknown else "The function arguments did not satisfy its advertised schema. ")
return (
"Tool protocol error: your previous completion was discarded before "
"any tool ran. " + issue + "Choose a function exactly from the "
"provided tools and follow its attached JSON parameter schema. "
"Available function names: " + ", ".join(offered) + ". "
"Return one valid tool call through the API tool-call channel, or "
"answer normally if no tool is appropriate."
)
def _complete_structured_tool_decision(completion: dict[str, Any]) -> bool:
"""Only a completed assistant call is eligible for protocol repair."""
choices = completion.get("choices")
if not isinstance(choices, list) or len(choices) != 1:
return False
choice = choices[0]
if not isinstance(choice, dict) or choice.get("finish_reason") != "tool_calls":
return False
if choice.get("index", 0) != 0:
return False
message = choice.get("message")
if (not isinstance(message, dict) or message.get("role") != "assistant"
or message.get("refusal")):
return False
calls = message.get("tool_calls")
if not isinstance(calls, list) or not calls:
return False
# A malformed transport envelope is not a model decision to retry.
for call in calls:
if (not isinstance(call, dict) or call.get("type") != "function"
or not isinstance(call.get("id"), str) or not call["id"]):
return False
function = call.get("function")
if (not isinstance(function, dict)
or not isinstance(function.get("name"), str) or not function["name"]
or not isinstance(function.get("arguments"), str)):
return False
return True
def _structured_tool_repair_feedback() -> str:
# Do not promote rejected model names or arguments into instructions.
# The unchanged request carries the authoritative tool schemas and policy.
return (
"Tool protocol error: your previous completion was discarded before any tool ran. "
"Return a valid function call through the API tool-call channel using exactly "
"the provided tools and their JSON parameter schemas. Respect tool_choice "
"and parallel_tool_calls. If tool_choice permits it and no tool is appropriate, "
"answer normally."
)
def _repaired_tool_decision_invalid(
completion: dict[str, Any], payload: dict[str, Any],
) -> bool:
"""Check the sole retry without executing or inventing a function call."""
names = _complete_native_envelope_names(completion)
if names is not None:
return not _normalize_native_tool_markup(completion, payload)
choices = completion.get("choices")
if not isinstance(choices, list) or len(choices) != 1:
return True
choice = choices[0]
message = choice.get("message") if isinstance(choice, dict) else None
if not isinstance(message, dict) or message.get("role") != "assistant":
return True
content = message.get("content")
if isinstance(content, str) and content.strip().startswith("<tool_call>"):
return True
calls = message.get("tool_calls")
if calls is None:
# A normal answer or refusal is valid only after a complete stop.
return (choice.get("finish_reason") != "stop"
or payload.get("tool_choice") == "required"
or isinstance(payload.get("tool_choice"), dict))
if not isinstance(calls, list) or not calls:
return True
if choice.get("finish_reason") != "tool_calls":
return True
if payload.get("parallel_tool_calls") is False and len(calls) > 1:
return True
tool_choice = payload.get("tool_choice")
forced_function = tool_choice.get("function") if isinstance(tool_choice, dict) else None
forced_name = (forced_function.get("name")
if isinstance(forced_function, dict) else None)
offered = {
item["function"]["name"]: item["function"].get("parameters")
for item in payload["tools"]
if isinstance(item, dict) and item.get("type") == "function"
and isinstance(item.get("function"), dict)
and isinstance(item["function"].get("name"), str)
}
for call in calls:
if (not isinstance(call, dict) or not isinstance(call.get("id"), str)
or not call["id"] or call.get("type") != "function"):
return True
function = call.get("function") if isinstance(call, dict) else None
name = function.get("name") if isinstance(function, dict) else None
schema = offered.get(name) if isinstance(name, str) else None
if (not isinstance(schema, dict) or _schema_has_references(schema)
or (forced_name is not None and name != forced_name)
or not isinstance(function.get("arguments"), str)):
return True
try:
args = json.loads(function["arguments"])
validator_class = jsonschema_validators.validator_for(schema)
validator_class.check_schema(schema)
validator_class(schema).validate(args)
except (ValueError, TypeError, SchemaError, ValidationError):
return True
return False
# A rejected tool decision is described by its shape only, for the router log
# and for the repair feedback: function names, the JSON Schema keyword that
# failed, the path to that point and argument key names. Argument values never
# appear in either; they can carry page or prompt text. The feedback names only
# what the request's own tool schemas declare.
_DIAGNOSTIC_NAME = re.compile(r"[A-Za-z0-9_.:-]{1,64}")
_MAX_DIAGNOSTIC_NAMES = 16
# A complete call whose only fault is its arguments against the offered
# function's schema can be repaired a second time; a model often fixes such a
# call once it is told which rule failed. Any other rejection keeps one repair.
_SCHEMA_REPAIR_LIMIT = 2
_BOUND_RULES = {"minLength", "maxLength", "minItems", "maxItems", "minimum", "maximum",
"exclusiveMinimum", "exclusiveMaximum", "minProperties", "maxProperties"}
def _diagnostic_names(values: Any) -> list[str]:
"""Bounded log form of model-produced names and indices, never a value."""
names = [str(value) if type(value) is int
else value if isinstance(value, str) and _DIAGNOSTIC_NAME.fullmatch(value)
else "?" for value in values]
return names[:_MAX_DIAGNOSTIC_NAMES] + (["..."] if len(names) > _MAX_DIAGNOSTIC_NAMES else [])
def _declared_names(values: Any, declared: set[str]) -> list[str]:
"""Log form of argument keys and paths: indices and names the schema declares.
Any other key comes from the arguments themselves (a map-shaped schema keys
by contact, file or user name), so it may be user data and logs as "*".
"""
names = [str(value) if type(value) is int
else value if isinstance(value, str) and value in declared and _DIAGNOSTIC_NAME.fullmatch(value)
else "*" for value in values]
return names[:_MAX_DIAGNOSTIC_NAMES] + (["..."] if len(names) > _MAX_DIAGNOSTIC_NAMES else [])
def _offered_function_schemas(payload: dict[str, Any]) -> dict[str, Any]:
offered = payload.get("tools")
return {
item["function"]["name"]: item["function"].get("parameters")
for item in (offered if isinstance(offered, list) else [])
if isinstance(item, dict) and item.get("type") == "function"
and isinstance(item.get("function"), dict)
and isinstance(item["function"].get("name"), str)
}
def _declared_property_names(schema: Any) -> set[str]:
"""Every property name a schema declares, at any depth (bounded walk)."""
names: set[str] = set()
pending, visited = [schema], 0
while pending and visited < 4096:
node = pending.pop()
visited += 1
if isinstance(node, dict):
properties = node.get("properties")
if isinstance(properties, dict):
names.update(key for key in properties if isinstance(key, str))
pending.extend(node.values())
elif isinstance(node, list):
pending.extend(node)
return names
def _closest_schema_error(error: ValidationError) -> ValidationError:
"""For oneOf/anyOf, the error of the one alternative the value came closest to."""
for _ in range(8):
if error.validator not in ("oneOf", "anyOf") or not error.context:
return error
branches: dict[Any, list[ValidationError]] = {}
for child in error.context:
branch = child.relative_schema_path[0] if child.relative_schema_path else None
branches.setdefault(branch, []).append(child)
fewest = min(len(errors) for errors in branches.values())
closest = [errors for errors in branches.values() if len(errors) == fewest]
if len(closest) != 1:
return error
error = best_match(closest[0])
return error
def _described_schema_error(error: ValidationError) -> dict[str, Any]:
"""The failed keyword, with a feedback clause built from schema names only."""
rule, value, instance = str(error.validator), error.validator_value, error.instance
described: dict[str, Any] = {"rule": rule}
if rule == "required" and isinstance(value, list):
missing = [name for name in value if isinstance(name, str)
and not (isinstance(instance, dict) and name in instance)]
described["missing"] = missing[:_MAX_DIAGNOSTIC_NAMES]
described["detail"] = ("it is missing the required "
+ ("property " if len(missing) == 1 else "properties ")
+ ", ".join(missing[:8]))
elif rule == "additionalProperties":
declared = error.schema.get("properties") if isinstance(error.schema, dict) else None
declared = declared if isinstance(declared, dict) else {}
if isinstance(instance, dict):
# Undeclared keys come from the arguments and may be user data: count them only.
described["unexpected"] = sum(1 for key in instance if isinstance(key, str) and key not in declared)
allowed = sorted(key for key in declared if isinstance(key, str))
described["detail"] = ("it has a property its schema does not allow"
+ ("; use only " + ", ".join(allowed[:24]) if allowed else ""))
elif rule == "enum" and isinstance(value, list):
options = [json.dumps(option, ensure_ascii=False)[:64] for option in value[:24]]
described["detail"] = ("the value must be one of " + ", ".join(options)
+ (", ..." if len(value) > 24 else ""))
elif rule == "const":
described["detail"] = "the value must be exactly " + json.dumps(value, ensure_ascii=False)[:64]
elif rule == "type" and isinstance(value, (str, list)):
types = [value] if isinstance(value, str) else [kind for kind in value if isinstance(kind, str)]
described["detail"] = "the value must be of type " + " or ".join(types)
elif rule in ("oneOf", "anyOf") and isinstance(value, list):
forms = ["{" + ", ".join(branch["required"]) + "}" for branch in value[:8]
if isinstance(branch, dict) and isinstance(branch.get("required"), list)
and branch["required"] and all(isinstance(name, str) for name in branch["required"])]
described["detail"] = ("it must match exactly one of its allowed forms"
+ (": " + " or ".join(forms) if forms else ""))
elif rule in _BOUND_RULES and type(value) in (int, float):
described["detail"] = f"the value does not meet its {rule} of {value}"
elif rule == "pattern" and isinstance(value, str):
described["detail"] = "the value must match the pattern " + value[:120]
else:
described["detail"] = f"the value does not satisfy its {rule} rule"
return described
def _schema_path_text(path: Any, declared: set[str]) -> str:
"""steps[3].locator, naming only properties the schema declares."""
text = ""
for part in path:
if type(part) is int:
text += f"[{part}]"
else:
name = part if isinstance(part, str) and part in declared and _DIAGNOSTIC_NAME.fullmatch(part) else "*"
text += ("." if text else "") + name
return text or "the top level"
def _type_only_tools(payload: dict[str, Any]) -> list[Any]:
"""The offered tools with each schema reduced to its property types.
The native envelope parser reads a string property verbatim and any other
as JSON. With every constraint removed, an envelope that parses this way
failed only its schema."""
tools = []
for item in payload.get("tools") or []:
function = item.get("function") if isinstance(item, dict) else None
schema = function.get("parameters") if isinstance(function, dict) else None
properties = schema.get("properties") if isinstance(schema, dict) else None
if not isinstance(properties, dict):
tools.append(item)
continue
reduced = {key: {"type": "string"} if isinstance(value, dict) and value.get("type") == "string" else {}
for key, value in properties.items()}
tools.append({**item, "function": {**function, "parameters": {"type": "object", "properties": reduced}}})
return tools
def _structured_calls(
completion: dict[str, Any], payload: dict[str, Any],
) -> tuple[list[dict[str, Any]] | None, dict[str, Any] | None]:
"""The calls of a structured decision, or why its envelope was rejected.
Mirrors the checks of _repaired_tool_decision_invalid before its schema check.
"""
def protocol(rule: str) -> tuple[None, dict[str, Any]]:
return None, {"kind": "protocol", "channel": "structured", "rule": rule}
choices = completion.get("choices")
if not isinstance(choices, list) or len(choices) != 1:
return protocol("choices")
choice = choices[0]
message = choice.get("message") if isinstance(choice, dict) else None
if not isinstance(message, dict) or message.get("role") != "assistant":
return protocol("message")
content = message.get("content")
if isinstance(content, str) and content.strip().startswith("<tool_call>"):
return None, {"kind": "native-markup", "channel": "native"}
calls = message.get("tool_calls")
if calls is None:
return protocol("answer")
if not isinstance(calls, list) or not calls or choice.get("finish_reason") != "tool_calls":
return protocol("finish_reason")
if payload.get("parallel_tool_calls") is False and len(calls) > 1:
return protocol("parallel_tool_calls")
for call in calls:
function = call.get("function") if isinstance(call, dict) else None
if (not isinstance(function, dict) or not isinstance(call.get("id"), str) or not call["id"]
or call.get("type") != "function" or not isinstance(function.get("name"), str)
or not isinstance(function.get("arguments"), str)):
return protocol("call")
tool_choice = payload.get("tool_choice")
forced = tool_choice.get("function") if isinstance(tool_choice, dict) else None
forced_name = forced.get("name") if isinstance(forced, dict) else None
if forced_name is not None and any(call["function"]["name"] != forced_name for call in calls):
return protocol("tool_choice")
return calls, None
def _tool_decision_rejection(
completion: dict[str, Any], payload: dict[str, Any],
) -> dict[str, Any]:
"""Why _repaired_tool_decision_invalid rejected a decision, by shape only.
kind is "schema" when every call names an offered function with a JSON
object of arguments and only that function's schema failed; otherwise
"unknown-function", "arguments", "native-markup" or "protocol" (with the
fixed name of the failed check). Side-effect free.
"""
offered = _offered_function_schemas(payload)
native_names = _complete_native_envelope_names(completion)
if native_names is not None:
channel, names = "native", native_names
else:
calls, envelope_rejection = _structured_calls(completion, payload)
if envelope_rejection is not None:
return envelope_rejection
channel, names = "structured", [call["function"]["name"] for call in calls]
functions = _diagnostic_names(names)
if any(name not in offered for name in names):
return {"kind": "unknown-function", "channel": channel, "functions": functions}
if native_names is not None:
parsed = copy.deepcopy(completion)
if not _normalize_native_tool_markup(parsed, {**payload, "tools": _type_only_tools(payload)}):
return {"kind": "native-markup", "channel": channel, "functions": functions}
calls = parsed["choices"][0]["message"]["tool_calls"]
for call in calls:
name, schema = call["function"]["name"], offered[call["function"]["name"]]
if not isinstance(schema, dict) or _schema_has_references(schema):
return {"kind": "protocol", "channel": channel, "rule": "schema", "functions": functions}
try:
args = json.loads(call["function"]["arguments"])
except ValueError:
return {"kind": "arguments", "channel": channel, "functions": functions}
validator_class = jsonschema_validators.validator_for(schema)
try:
validator_class.check_schema(schema)
except SchemaError:
return {"kind": "protocol", "channel": channel, "rule": "schema", "functions": functions}
try:
error = best_match(validator_class(schema).iter_errors(args))
except (ValueError, TypeError):
# The validator cannot evaluate these arguments (NaN against multipleOf);
# _repaired_tool_decision_invalid rejects them alike: one ordinary repair.
return {"kind": "protocol", "channel": channel, "rule": "unevaluable", "functions": functions}
if error is None:
continue
error = _closest_schema_error(error)
declared = _declared_property_names(schema)
return {
"kind": "schema", "channel": channel, "functions": functions, "function": name,
"at": "/".join(_declared_names(error.absolute_path, declared)),
"where": _schema_path_text(error.absolute_path, declared),
"keys": _declared_names(sorted(args), declared) if isinstance(args, dict) else [],
"keysAt": _declared_names(sorted(error.instance), declared) if isinstance(error.instance, dict) else [],
**_described_schema_error(error),
}
return {"kind": "protocol", "channel": channel, "rule": "unclassified", "functions": functions}
def _log_tool_rejection(stage: str, rejection: dict[str, Any]) -> None:
"""One bounded line per rejected decision: names, rule and path, no values."""
fields = {key: rejection[key] for key in (
"kind", "channel", "rule", "functions", "at", "missing", "unexpected", "keys", "keysAt",
) if key in rejection}
if "function" in rejection:
fields["function"] = _diagnostic_names([rejection["function"]])[0]
logger.warning("Rejected model tool decision (%s): %s", stage,
json.dumps(fields, sort_keys=True, separators=(",", ":")))
def _tool_repair_feedback(
rejection: dict[str, Any], payload: dict[str, Any], native_names: list[str] | None,
) -> str:
"""The repair instruction for this rejection, from schema names only."""
if rejection.get("kind") == "schema":
return (
"Tool protocol error: your previous completion was discarded before any tool ran. "
f"The arguments for {rejection['function']} did not satisfy its JSON parameter "
f"schema at {rejection['where']}: {rejection['detail']}. Call it again through "
"the API tool-call channel with arguments that follow that attached schema "
"exactly. Respect tool_choice and parallel_tool_calls. If tool_choice permits "
"it and no tool is appropriate, answer normally."
)
if native_names is not None:
return _native_tool_repair_feedback(native_names, payload)
if rejection.get("kind") == "unknown-function":
# The offered names come from the request; the rejected one is not repeated.
return (
"Tool protocol error: your previous completion was discarded before any tool ran. "
"It named a function that this request does not offer. Available function names: "
+ ", ".join(_offered_function_schemas(payload)) + ". Return a valid function call "
"through the API tool-call channel using exactly the provided tools and their "
"JSON parameter schemas. Respect tool_choice and parallel_tool_calls. If "
"tool_choice permits it and no tool is appropriate, answer normally."
)
return _structured_tool_repair_feedback()
app = FastAPI(title="ODS Model Router", docs_url=None, redoc_url=None,
openapi_url=None)
_inflight = 0
_inflight_lock = asyncio.Lock()
_waiting = 0
_swap_gate: dict[str, Any] | None = None
_state_cache: dict[str, Any] = {"mtime": None, "doc": None}
_endpoints_cache: dict[str, Any] = {"mtime": None, "endpoints": {}}
_probe_key_cache: dict[str, Any] = {"mtime": None, "key": ""}
_evidence: "OrderedDict[str, dict[str, Any]]" = OrderedDict()
_probe_attempts = ProbeAttempts()
def _begin_probe_attempt(probe_id, request_id, attempt, body, route):
if not probe_id:
return None
try:
return _probe_attempts.begin(probe_id, _current_probe_key(), request_id,
attempt, body, route)
except Exception:
return None # Optional diagnostics must never alter inference.
def _finish_probe_attempt(handle, status, http_status=None):
try:
_probe_attempts.finish(handle, status, http_status)
except Exception:
pass
def _observe_probe_response_model(handle, model):
try:
_probe_attempts.observe_response_model(handle, model)
except Exception:
pass # Optional diagnostics must never alter inference.
class _TelemetrySink:
"""Best-effort telemetry transport that never blocks model responses."""
def __init__(
self,
url: str,
api_key: str,
*,
client: httpx.AsyncClient | None = None,
) -> None:
self.url = url.rstrip("/")
self.api_key = api_key
self.enabled = bool(self.url and self.api_key)
self.queue: asyncio.Queue[dict[str, Any]] | None = (
asyncio.Queue(maxsize=TELEMETRY_QUEUE_DEPTH)
if self.enabled
else None
)
self.client = client
self.task: asyncio.Task[None] | None = None
self._last_warning = 0.0
async def start(self) -> None:
if not self.enabled:
return
if self.client is None:
self.client = httpx.AsyncClient(
follow_redirects=False,
timeout=TELEMETRY_TIMEOUT_SECONDS,
)
self.task = asyncio.create_task(
self._run(), name="model-router-token-spy"
)
def emit(self, event: dict[str, Any]) -> bool:
if self.queue is None:
return False
try:
self.queue.put_nowait(event)
return True
except asyncio.QueueFull:
self._warn("Token Spy telemetry queue is full; dropping event")
return False
async def _run(self) -> None:
assert self.queue is not None
assert self.client is not None
while True:
event = await self.queue.get()
try:
response = await self.client.post(
f"{self.url}/api/ingest/routed",
json=event,
headers={"Authorization": f"Bearer {self.api_key}"},
)
if response.status_code != 202:
self._warn(
"Token Spy rejected routed telemetry "
f"with HTTP {response.status_code}"
)
except (httpx.HTTPError, RuntimeError) as exc:
self._warn(f"Token Spy telemetry unavailable: {exc}")
finally:
self.queue.task_done()
def _warn(self, message: str) -> None:
now = time.monotonic()
if now - self._last_warning >= 60:
logger.warning(message)
self._last_warning = now
async def stop(self) -> None:
if self.queue is not None:
try:
await asyncio.wait_for(self.queue.join(), timeout=1.0)
except asyncio.TimeoutError:
self._warn("Timed out draining Token Spy telemetry queue")
if self.task is not None:
self.task.cancel()
try:
await self.task
except asyncio.CancelledError:
pass
if self.client is not None:
await self.client.aclose()
def _usage_from_response(payload: Any) -> tuple[dict[str, int], str]:
"""Normalize OpenAI Chat/Completions and Responses API usage fields."""
if not isinstance(payload, dict):
payload = {}
response = payload.get("response")
source = response if isinstance(response, dict) else payload
usage = source.get("usage")
usage = usage if isinstance(usage, dict) else {}
prompt_details = usage.get("prompt_tokens_details")
if not isinstance(prompt_details, dict):
prompt_details = usage.get("input_tokens_details")
prompt_details = prompt_details if isinstance(prompt_details, dict) else {}
normalized = {
"input_tokens": _nonnegative_int(
usage.get("prompt_tokens", usage.get("input_tokens", 0))
),
"output_tokens": _nonnegative_int(
usage.get("completion_tokens", usage.get("output_tokens", 0))
),
"cache_read_tokens": _nonnegative_int(
prompt_details.get("cached_tokens", usage.get("cache_read_tokens", 0))
),
"cache_write_tokens": _nonnegative_int(
usage.get("cache_write_tokens", 0)
),
}
stop_reason = source.get("stop_reason") or source.get("status") or ""
choices = source.get("choices")
if isinstance(choices, list) and choices and isinstance(choices[0], dict):
stop_reason = choices[0].get("finish_reason") or stop_reason
return normalized, str(stop_reason)[:128]
def _nonnegative_int(value: Any) -> int:
if isinstance(value, bool):
return 0
try:
return max(0, int(value))
except (TypeError, ValueError, OverflowError):
return 0
def _build_telemetry_event(
payload: dict[str, Any],
*,
raw_body_bytes: int,
model: str,
backend: str,
path: str,
duration_ms: int,
usage: dict[str, int],
stop_reason: str,
) -> dict[str, Any]:
messages = payload.get("messages")
messages = messages if isinstance(messages, list) else []
roles = [
item.get("role")
for item in messages
if isinstance(item, dict)
]
tools = payload.get("tools")
tools = tools if isinstance(tools, list) else []
event = {
"agent": "model-router",
"model": str(model)[:512],
"provider_name": str(backend or "unknown")[:128],
"path": path,
"request_body_bytes": min(max(raw_body_bytes, 0), MAX_BODY_BYTES),
"message_count": min(len(messages), 100_000),
"user_message_count": min(roles.count("user"), 100_000),
"assistant_message_count": min(roles.count("assistant"), 100_000),
"tool_count": min(len(tools), 100_000),
"input_tokens": min(
_nonnegative_int(usage.get("input_tokens")), 2_000_000_000
),
"output_tokens": min(
_nonnegative_int(usage.get("output_tokens")), 2_000_000_000
),
"cache_read_tokens": min(
_nonnegative_int(usage.get("cache_read_tokens")), 2_000_000_000
),
"cache_write_tokens": min(
_nonnegative_int(usage.get("cache_write_tokens")), 2_000_000_000
),
"duration_ms": min(max(duration_ms, 0), 86_400_000),
"stop_reason": str(stop_reason or "")[:128],
}
# Provider prompt/input counts include cached tokens. Token Spy stores
# disjoint categories; partition once, after any stream aggregation.
event["cache_read_tokens"] = min(event["cache_read_tokens"], event["input_tokens"])
remaining = event["input_tokens"] - event["cache_read_tokens"]
event["cache_write_tokens"] = min(event["cache_write_tokens"], remaining)
event["input_tokens"] = remaining - event["cache_write_tokens"]
return event
def _emit_telemetry(event: dict[str, Any]) -> bool:
sink: _TelemetrySink | None = getattr(app.state, "telemetry", None)
if sink is None:
return False
try:
return sink.emit(event)
except Exception as exc:
logger.warning("Token Spy telemetry enqueue failed: %s", exc)
return False
class RouterError(Exception):
def __init__(self, status: int, code: str, message: str) -> None:
super().__init__(message)
self.status = status
self.code = code
self.message = message
# ODS thinking levels. A vllm endpoint maps each to the served model's own
# chat-template arguments (config/model-library.json thinking_template_kwargs,
# rendered into endpoints.json as "thinking").
THINKING_LEVELS = ("off", "low", "medium", "high")
# OpenAI reasoning_effort values, read as ODS levels.
_REASONING_EFFORT_LEVELS = {
"none": "off", "off": "off", "minimal": "low", "low": "low",
"medium": "medium", "high": "high", "xhigh": "high",
}
def _valid_thinking(value: Any) -> bool:
"""An endpoint ``thinking`` map: {"default": level, "templateKwargs": {level: {...}}}."""
if not _has_keys(value, {"default", "templateKwargs"}, {"default", "templateKwargs"}):
return False
levels = value["templateKwargs"]
return (
value["default"] in THINKING_LEVELS
and isinstance(levels, dict)
and set(levels) == set(THINKING_LEVELS)
and all(isinstance(kwargs, dict) and all(isinstance(key, str) for key in kwargs)
for kwargs in levels.values())
)
def _load_endpoints() -> dict[str, dict[str, Any]]:
"""Allowlist endpointId -> {baseUrl, apiKeyEnv?, thinking?}, re-read when
the file changes on disk (activation re-renders it). Retains the last good
allowlist while the file is missing or invalid. An endpoint whose thinking
map is malformed is left out, so its route fails closed."""
try:
stat = ENDPOINTS_PATH.stat()
except OSError as exc:
if _endpoints_cache["mtime"] is None:
logger.error("endpoints allowlist unavailable: %s", exc)
return _endpoints_cache["endpoints"]
mtime = (stat.st_mtime_ns, stat.st_size)
if _endpoints_cache["mtime"] == mtime:
return _endpoints_cache["endpoints"]
endpoints: dict[str, dict[str, Any]] = {}
try:
raw = json.loads(ENDPOINTS_PATH.read_text(encoding="utf-8"))
for entry in raw.get("endpoints", []):
endpoint_id = str(entry.get("id") or "")
base_url = str(entry.get("baseUrl") or "")
if not endpoint_id or not base_url.startswith(("http://", "https://")):
continue
thinking = entry.get("thinking")
if thinking is not None and not _valid_thinking(thinking):
logger.error("endpoint %s has a malformed thinking map; it is not allowlisted", endpoint_id)
continue
endpoints[endpoint_id] = {
"baseUrl": base_url.rstrip("/"),
"apiKeyEnv": str(entry.get("apiKeyEnv") or ""),
"thinking": thinking,
}
except (OSError, ValueError) as exc:
logger.error("endpoints allowlist unreadable; retaining previous: %s", exc)
return _endpoints_cache["endpoints"]
_endpoints_cache["mtime"] = mtime
_endpoints_cache["endpoints"] = endpoints
return endpoints
def _has_keys(value: Any, required: set[str], allowed: set[str]) -> bool:
return (
isinstance(value, dict)
and required <= set(value)
and set(value) <= allowed
)
def _is_nonnegative_int(value: Any) -> bool:
return type(value) is int and value >= 0
def _validate_state_schema(doc: Any) -> bool:
"""Validate the checked-in ``ods.model-state.v1`` contract."""
root_keys = {
"schema", "seq", "routeSeq", "operation", "desired", "active",
"history", "availability",
}
if not _has_keys(
doc,
{"schema", "seq", "routeSeq", "desired", "active", "history",
"availability"},
root_keys,
):
return False
if doc["schema"] != "ods.model-state.v1":
return False
if not _is_nonnegative_int(doc["seq"]) or not _is_nonnegative_int(doc["routeSeq"]):
return False
operation = doc.get("operation")
if operation is not None:
if not _has_keys(
operation,
{"id", "phase", "requestedModelId", "startedAt"},
{"id", "phase", "requestedModelId", "startedAt", "error"},
):
return False
if not isinstance(operation["id"], str) or not operation["id"]:
return False
if operation["phase"] not in {
"requested", "staging", "verifying", "publishing", "flipping",
"serving", "failed", "rolling_back",
}:
return False
if not isinstance(operation["requestedModelId"], str):
return False
if not isinstance(operation["startedAt"], str):
return False
if "error" in operation and operation["error"] is not None \
and not isinstance(operation["error"], str):
return False
desired = doc["desired"]
if desired is not None:
if not _has_keys(desired, {"catalogId"}, {"catalogId"}):
return False
if not isinstance(desired["catalogId"], str) or not desired["catalogId"]:
return False
active = doc["active"]
if active is not None:
active_keys = {
"routeSeq", "catalogId", "runtimeModelId", "publicModel", "backend",
"contextLength", "capabilities", "verifiedAt", "reconstructed", "proof",
}
if not _has_keys(
active,
{"routeSeq", "catalogId", "runtimeModelId", "publicModel", "backend",
"contextLength", "capabilities", "verifiedAt", "proof"},
active_keys,
):
return False
if not _is_nonnegative_int(active["routeSeq"]):
return False
for key in ("catalogId", "runtimeModelId", "publicModel"):
if not isinstance(active[key], str) or not active[key]:
return False
if not _is_nonnegative_int(active["contextLength"]):
return False
if active["verifiedAt"] is not None and not isinstance(active["verifiedAt"], str):
return False
if "reconstructed" in active and type(active["reconstructed"]) is not bool:
return False
backend = active["backend"]
if not _has_keys(
backend, {"kind", "endpointId"}, {"kind", "endpointId", "nativeRoute"}
):
return False
# A pre-round-F state names the retired "lemonade" kind. It stays
# readable for one release so the host agent can replace it (contract
# section 6.7); no route path treats it specially.
if backend["kind"] not in {"llama-server", "vllm", "lemonade", "hipfire", "unknown"}:
return False
if not isinstance(backend["endpointId"], str) or not backend["endpointId"]:
return False
if "nativeRoute" in backend and backend["nativeRoute"] is not None \
and not isinstance(backend["nativeRoute"], str):
return False
capabilities = active["capabilities"]
capability_keys = {"chat", "tools", "vision", "agentViable"}
if not _has_keys(capabilities, capability_keys, capability_keys):
return False
if any(type(capabilities[key]) is not bool for key in capability_keys):
return False
proof = active["proof"]
if not _has_keys(proof, {"identity", "completion"}, {"identity", "completion"}):
return False
if proof["identity"] is not None and not isinstance(proof["identity"], str):
return False
if type(proof["completion"]) is not bool:
return False
history = doc["history"]
if not isinstance(history, list) or len(history) > 10:
return False
for entry in history:
if not isinstance(entry, dict) or not {
"routeSeq", "catalogId", "runtimeModelId", "verifiedAt"
} <= set(entry):
return False
if not _is_nonnegative_int(entry["routeSeq"]):
return False
if not isinstance(entry["catalogId"], str):
return False
if not isinstance(entry["runtimeModelId"], str):
return False
if entry["verifiedAt"] is not None and not isinstance(entry["verifiedAt"], str):
return False
availability = doc["availability"]
if not _has_keys(
availability, {"mode", "queueDeadline"}, {"mode", "queueDeadline"}
):
return False
if availability["mode"] not in {"serve_active", "queue"}:
return False
if availability["queueDeadline"] is not None \
and not isinstance(availability["queueDeadline"], str):
return False
return True
def _has_verified_active_route(doc: dict[str, Any]) -> bool:
active = doc.get("active")
if not isinstance(active, dict) or active.get("reconstructed") is True:
return False
proof = active.get("proof")
runtime_model = active.get("runtimeModelId")
return (
isinstance(runtime_model, str)
and bool(runtime_model)
and isinstance(active.get("verifiedAt"), str)
and bool(active["verifiedAt"])
and isinstance(proof, dict)
and proof.get("completion") is True
and proof.get("identity") == runtime_model
and active.get("routeSeq") == doc.get("routeSeq")
and doc.get("routeSeq", 0) <= doc.get("seq", -1)
)
def _read_state() -> dict[str, Any] | None:
"""Return only verified, monotonic state, retaining verified last-known-good."""
try:
stat = STATE_PATH.stat()
except OSError:
return _state_cache["doc"]
mtime = (stat.st_mtime_ns, stat.st_size)
if _state_cache["mtime"] == mtime:
return _state_cache["doc"]
try:
doc = json.loads(STATE_PATH.read_text(encoding="utf-8"))
except (OSError, ValueError):
return _state_cache["doc"]
if not _validate_state_schema(doc) or not _has_verified_active_route(doc):
logger.warning("rejecting invalid or unverified model state")
return _state_cache["doc"]
cached = _state_cache["doc"]
if cached is not None:
if doc["seq"] < cached["seq"] or doc["routeSeq"] < cached["routeSeq"]:
logger.warning("rejecting regressed model state sequence")
return cached
if doc["seq"] == cached["seq"] and doc != cached:
logger.warning("rejecting mutated model state at unchanged sequence")
return cached
_state_cache["mtime"] = mtime
_state_cache["doc"] = doc
return doc
def _active_route() -> dict[str, Any]:
doc = _read_state()
active = (doc or {}).get("active")
if not isinstance(active, dict):
raise RouterError(503, "no_active_route",
"No verified active model route is available yet")
endpoint_id = str(((active.get("backend") or {}).get("endpointId")) or "")
endpoint = _load_endpoints().get(endpoint_id)
if endpoint is None:
raise RouterError(503, "endpoint_not_allowlisted",
f"Active endpointId {endpoint_id!r} is not in the "
"router allowlist")
availability = (doc or {}).get("availability") or {}
return {
"routeSeq": int(active.get("routeSeq") or 0),
"catalogId": str(active.get("catalogId") or ""),
"runtimeModelId": str(active.get("runtimeModelId") or ""),
"contextLength": active["contextLength"],
"capabilities": dict(active["capabilities"]),
"backendKind": str((active.get("backend") or {}).get("kind") or "unknown"),
"endpointId": endpoint_id,
"baseUrl": endpoint["baseUrl"],
"apiKeyEnv": endpoint["apiKeyEnv"],
"thinking": endpoint.get("thinking"),
"queueMode": str(availability.get("mode") or "serve_active") == "queue",
}
def _llama_tool_compat(route: dict[str, Any]) -> bool:
"""Whether the router's llama.cpp tool-call workarounds apply to a route.
Only llama-server routes get them: buffered tool streams, the non-stream
request for thinking-enabled tool streams, bounded tool-protocol repair
and native tool-markup cleanup (tool_id_compat keeps its Nemo tool-id
rewrite llama-server-only too). Other kinds are forwarded unchanged; a
vllm route parses tool calls and reasoning itself with its own
--tool-call-parser and --reasoning-parser.
"""
return route["backendKind"] == "llama-server"
def _thinking_level(payload: dict[str, Any], default: str) -> str:
"""The ODS thinking level a chat request asks for.
A ``reasoning_effort`` names it, top-level (OpenAI's field) or in
``chat_template_kwargs`` (vLLM passes both to the template alike);
otherwise the ODS consumers' on/off switch,
``chat_template_kwargs.enable_thinking`` (false is off, true the route's
default level, at least medium); otherwise the default.
"""
options = payload.get("chat_template_kwargs")
options = options if isinstance(options, dict) else {}
effort = payload.get("reasoning_effort")
if effort is None:
effort = options.get("reasoning_effort")
if effort is not None:
level = _REASONING_EFFORT_LEVELS.get(effort.strip().lower()) if isinstance(effort, str) else None
if level is None:
raise RouterError(400, "invalid_request_error",
"reasoning_effort must be one of " + ", ".join(_REASONING_EFFORT_LEVELS))
return level
enabled = options.get("enable_thinking")
if enabled is False:
return "off"
if enabled is True and default == "off":
return "medium"
return default
def _vllm_thinking_payload(payload: dict[str, Any], thinking: dict[str, Any]) -> tuple[dict[str, Any], str]:
"""The request with its thinking level in the served model's own template terms.
Chat templates disagree: GLM-5.3 reads only reasoning_effort low or high
(any other value thinks at "max", about twice as slow) and Qwen3.8 fails
with HTTP 400 on any reasoning_effort but xhigh, medium and low, so no
level, reasoning_effort or enable_thinking is forwarded as sent. The
level's arguments replace them; the other chat_template_kwargs a client
sends are the model's own and stay. Returns the new payload and the level.
"""
options = payload.get("chat_template_kwargs")
if options is not None and not isinstance(options, dict):
raise RouterError(400, "invalid_request_error", "chat_template_kwargs must be an object")
level = _thinking_level(payload, thinking["default"])
kwargs = {
**thinking["templateKwargs"][level],
**{key: value for key, value in (options or {}).items()
if key not in {"enable_thinking", "reasoning_effort"}},
}
translated = {key: value for key, value in payload.items()
if key not in {"reasoning_effort", "chat_template_kwargs"}}
if kwargs:
translated["chat_template_kwargs"] = kwargs
return translated, level
def _offered_tool_evidence(payload: dict[str, Any]) -> dict[str, Any]:
"""Fingerprint the outgoing tools, never retain their names or schema text.
Called only for signed probes. This measures router input to the backend,
not schema acceptance, evaluated plugin code, or successful tool execution.
Object-key order is normalized; array order and missing-vs-empty are not.
Diagnostic limits must never alter inference or its ordinary validation.
"""
result = {
"schemaVersion": 1,
"boundary": "router-forwarded-tools-not-execution-proof",
"encoding": "json-sort-keys-ascii-v1",
"state": "unavailable", "count": None, "sha256": None,
}
present = "tools" in payload
tools = payload.get("tools", [])
if type(tools) is not list or len(tools) > TOOL_EVIDENCE_MAX_COUNT:
return result
try:
encoded = json.dumps({"present": present, "tools": tools}, sort_keys=True,
separators=(",", ":"), ensure_ascii=True,
allow_nan=False).encode("ascii")
if len(encoded) > TOOL_EVIDENCE_MAX_BYTES:
return result
return {**result, "state": "observed", "count": len(tools),
"sha256": hashlib.sha256(encoded).hexdigest()}
except (TypeError, ValueError, RecursionError):
return result
def _record_evidence(record: dict[str, Any]) -> None:
now = time.monotonic()
record["storedAt"] = now
record["instanceId"] = INSTANCE_ID
_evidence[record["probeId"]] = record
while len(_evidence) > EVIDENCE_LIMIT:
_evidence.popitem(last=False)
stale = [k for k, v in _evidence.items()
if now - v["storedAt"] > EVIDENCE_TTL_SECONDS]
for key in stale:
_evidence.pop(key, None)
def _current_probe_key() -> str:
"""Fleet probe key: file-based (mtime-cached re-read) when
ODS_FLEET_PROBE_KEY_PATH is configured and the file holds a value,
falling back to the ODS_FLEET_PROBE_KEY environment value. The file
form lets the fleet harness rotate or remove the key without
recreating the router (which would destroy in-memory evidence)."""
if PROBE_KEY_PATH is None:
return PROBE_KEY
try:
stat = PROBE_KEY_PATH.stat()
except OSError:
_probe_key_cache["mtime"] = None
_probe_key_cache["key"] = ""
return PROBE_KEY
mtime = (stat.st_mtime_ns, stat.st_size)
if _probe_key_cache["mtime"] != mtime:
try:
key = PROBE_KEY_PATH.read_text(encoding="utf-8").strip()
except OSError:
_probe_key_cache["mtime"] = None
_probe_key_cache["key"] = ""
return PROBE_KEY
_probe_key_cache["mtime"] = mtime
_probe_key_cache["key"] = key
return _probe_key_cache["key"] or PROBE_KEY
def _verify_probe_marker(body_text: str) -> str | None:
"""Return the probe UUID only for exactly one validly signed marker."""
probe_key = _current_probe_key()
if not probe_key:
return None
matches = _PROBE_RE.findall(body_text)
if len(matches) != 1:
return None
probe_id, signature = matches[0]
expected = base64.urlsafe_b64encode(
hmac.new(probe_key.encode("utf-8"), probe_id.encode("utf-8"),
hashlib.sha256).digest()
).rstrip(b"=").decode("ascii")
if not hmac.compare_digest(expected, signature):
return None
return probe_id
def _sanitize_headers(request: Request) -> dict[str, str]:
headers: dict[str, str] = {}
connection_fields = {
token.strip().lower()
for value in request.headers.getlist("connection")
for token in value.split(",")
}
for name, value in request.headers.items():
if name.lower() in _HOP_BY_HOP or name.lower() in connection_fields:
continue
headers[name] = value
headers["content-type"] = "application/json"
return headers
def _strip_chat_template_artifacts(text: str) -> str:
cleaned = text
for pattern in _CHAT_TEMPLATE_ARTIFACTS:
cleaned = pattern.sub("", cleaned)
return cleaned
def _sanitize_content_value(value: Any) -> tuple[Any, bool]:
if isinstance(value, str):
cleaned = _strip_chat_template_artifacts(value)
return cleaned, cleaned != value
if isinstance(value, list):
changed = False
cleaned_items: list[Any] = []
for item in value:
if isinstance(item, dict):
item = dict(item)
for key in ("text", "content"):
if isinstance(item.get(key), str):
item[key], item_changed = _sanitize_content_value(item[key])
changed = changed or item_changed
cleaned_items.append(item)
return cleaned_items, changed
return value, False
def _sanitize_choice_content(obj: dict[str, Any]) -> bool:
changed = False
choices = obj.get("choices")
if not isinstance(choices, list):
return False
for choice in choices:
if not isinstance(choice, dict):
continue
for container_key in ("message", "delta"):
container = choice.get(container_key)
if isinstance(container, dict) and "content" in container:
container["content"], item_changed = _sanitize_content_value(
container["content"]
)
changed = changed or item_changed
if "text" in choice:
choice["text"], item_changed = _sanitize_content_value(choice["text"])
changed = changed or item_changed
return changed
def _rewrite_sse_event(
event: bytes, alias: str
) -> tuple[bytes, list[str], list[dict[str, Any]], bool]:
"""Join an event's data fields before decoding JSON and observing metadata."""
lines: list[tuple[bytes, bytes]] = []
data_indices: list[int] = []
data_values: list[bytes] = []
for line in event.splitlines(keepends=True):
content = line.rstrip(b"\r\n")
lines.append((content, line[len(content):]))
field, _, value = content.partition(b":")
if field == b"data":
data_indices.append(len(lines) - 1)
# SSE removes exactly one optional space after the colon, then
# joins all data fields with LF, including fields without a colon.
data_values.append(value.removeprefix(b" "))
payload = b"\n".join(data_values)
if payload.strip() == b"[DONE]":
return event, [], [], True
try:
obj = json.loads(payload)
except ValueError:
return event, [], [], False
if not isinstance(obj, dict):
return event, [], [], False
models: list[str] = []
model_objects = [obj]
# Responses lifecycle events wrap their response object. Observe the
# concrete identity before restoring either top-level or nested aliases.
if (isinstance(obj.get("type"), str)
and obj["type"].startswith("response.")
and isinstance(obj.get("response"), dict)):
model_objects.append(obj["response"])
for model_object in model_objects:
if isinstance(model_object.get("model"), str):
if model_object["model"]:
models.append(model_object["model"])
model_object["model"] = alias
_sanitize_choice_content(obj)
# Emit one compact data field, preserving comments and other SSE fields.
# The last retained line inherits the original final ending so deleting
# later data fields cannot introduce an extra blank event delimiter.
first_data = data_indices[0]
removed = set(data_indices[1:])
retained = [line for index, line in enumerate(lines) if index not in removed]
retained[first_data] = (
b"data: " + json.dumps(obj, separators=(",", ":")).encode("utf-8"),
lines[first_data][1],
)
retained[-1] = (retained[-1][0], lines[-1][1])
return b"".join(content + ending for content, ending in retained), models, [obj], False
def _normalize_native_tool_markup(
completion: dict[str, Any], request_payload: dict[str, Any],
) -> bool:
"""Recover a *complete* native tool envelope from a tool-bearing response.
Some GGUF chat templates teach the model an XML tool-call grammar, while a
local backend may occasionally return that exact envelope as plain text.
This adapter has no tool-selection policy: it accepts only names advertised
in this request and arguments valid against their advertised JSON Schemas.
Normal prose, mixed/partial markup, or an explicit tool_choice=none remains
text. The agent and ODS tool gates still authorize any resulting action.
"""
if request_payload.get("tool_choice") == "none":
return False
choice_constraint = request_payload.get("tool_choice", "auto")
forced_name: str | None = None
if isinstance(choice_constraint, dict):
function = choice_constraint.get("function")
if (choice_constraint.get("type") != "function"
or not isinstance(function, dict)
or not isinstance(function.get("name"), str)):
return False
forced_name = function["name"]
elif not isinstance(choice_constraint, str) or choice_constraint not in {"auto", "required"}:
return False
offered_tools = request_payload.get("tools")
if not isinstance(offered_tools, list):
return False
parallel = request_payload.get("parallel_tool_calls")
if parallel is not None and type(parallel) is not bool:
return False
advertised: dict[str, dict[str, Any]] = {}
for item in offered_tools:
if not isinstance(item, dict) or item.get("type") != "function":
continue
function = item.get("function")
if not isinstance(function, dict):
continue
name, schema = function.get("name"), function.get("parameters")
if (not isinstance(name, str) or not isinstance(schema, dict)
or name in advertised):
return False
advertised[name] = schema
if not advertised:
return False
choices = completion.get("choices")
if not isinstance(choices, list) or len(choices) != 1:
return False
choice = choices[0]
if not isinstance(choice, dict) or choice.get("finish_reason") != "stop":
return False
message = choice.get("message")
if (not isinstance(message, dict) or message.get("role") != "assistant"
or "tool_calls" in message or message.get("refusal")):
return False
content = message.get("content")
if (not isinstance(content, str) or not content
or len(content) > _MAX_NATIVE_MARKUP_CHARS):
return False
markup = content.strip()
if not markup.startswith("<tool_call>"):
return False
calls: list[dict[str, Any]] = []
cursor = 0
while cursor < len(markup):
match = _NATIVE_CALL.match(markup, cursor)
if match is None or len(calls) >= _MAX_NATIVE_CALLS:
return False
name, parameter_markup = match.group(1), match.group(2)
schema = advertised.get(name)
if schema is None or (forced_name is not None and name != forced_name):
return False
if _schema_has_references(schema):
return False
properties = schema.get("properties")
if not isinstance(properties, dict):
return False
arguments: dict[str, Any] = {}
parameter_cursor = 0
while parameter_cursor < len(parameter_markup):
parameter_match = _NATIVE_PARAMETER.match(
parameter_markup, parameter_cursor,
)
if parameter_match is None:
return False
key, raw_value = parameter_match.group(1), parameter_match.group(2)
property_schema = properties.get(key)
if key in arguments or not isinstance(property_schema, dict):
return False
if property_schema.get("type") == "string":
value: Any = raw_value
else:
try:
value = json.loads(raw_value)
except (ValueError, TypeError):
# An untyped/union string can still be valid JSON Schema.
value = raw_value
arguments[key] = value
parameter_cursor = parameter_match.end()
if parameter_cursor < len(parameter_markup):
separator = re.match(r"\r?\n", parameter_markup[parameter_cursor:])
if separator is None:
return False
parameter_cursor += separator.end()
try:
validator_class = jsonschema_validators.validator_for(schema)
validator_class.check_schema(schema)
validator_class(schema).validate(arguments)
except (SchemaError, ValidationError, ValueError, TypeError):
return False
calls.append({
"id": f"call_ods_{uuid.uuid4().hex}", "type": "function",
"function": {"name": name, "arguments": json.dumps(
arguments, separators=(",", ":"), ensure_ascii=False,
)},
})
cursor = match.end()
if cursor < len(markup):
separator = re.match(r"\r?\n", markup[cursor:])
if separator is None:
return False
cursor += separator.end()
if not calls or (parallel is False and len(calls) > 1):
return False
message["content"] = None
message["tool_calls"] = calls
choice["finish_reason"] = "tool_calls"
return True
def _completed_chat_as_sse(completion: dict[str, Any]) -> bytes:
"""Present one completed Chat response as a standards-shaped SSE stream.
llama.cpp's incremental tool parser can retract a previously detected tool
call and terminate the stream. Its completed response has no incremental
tool-call diff to reconcile. Keep the original call IDs and full arguments;
only add the per-stream index required by ChatCompletionChunk.
"""
choices = completion.get("choices")
if not isinstance(choices, list) or not choices:
raise ValueError("Chat completion has no choices")
if not isinstance(completion.get("model"), str) or not completion["model"]:
raise ValueError("Chat completion has no model identity")
base = {
"id": str(completion.get("id") or f"ods-{uuid.uuid4().hex}"),
"object": "chat.completion.chunk",
"created": completion.get("created")
if type(completion.get("created")) is int else int(time.time()),
"model": completion.get("model"),
}
if "system_fingerprint" in completion:
base["system_fingerprint"] = completion["system_fingerprint"]
events: list[dict[str, Any]] = []
endings: list[dict[str, Any]] = []
for position, choice in enumerate(choices):
if not isinstance(choice, dict) or not isinstance(choice.get("message"), dict):
raise ValueError("Chat completion choice has no message")
message = choice["message"]
index = choice.get("index", position)
if type(index) is not int or index < 0:
raise ValueError("Chat completion choice has an invalid index")
finish_reason = choice.get("finish_reason")
if not isinstance(finish_reason, str) or not finish_reason:
raise ValueError("Chat completion choice has no terminal reason")
delta = {key: value for key, value in message.items() if key != "tool_calls"}
delta.setdefault("role", "assistant")
if "tool_calls" in message:
calls = message["tool_calls"]
if not isinstance(calls, list):
raise ValueError("Chat completion tool calls are malformed")
delta["tool_calls"] = []
for call_index, call in enumerate(calls):
function = call.get("function") if isinstance(call, dict) else None
if (not isinstance(call, dict)
or not isinstance(call.get("id"), str)
or not call["id"]
or call.get("type") != "function"
or not isinstance(function, dict)
or not isinstance(function.get("name"), str)
or not function["name"]
or not isinstance(function.get("arguments"), str)):
raise ValueError("Chat completion tool call is malformed")
delta["tool_calls"].append({**call, "index": call_index})
events.append({
**base,
"choices": [{"index": index, "delta": delta, "finish_reason": None}],
})
endings.append({
"index": index, "delta": {}, "finish_reason": finish_reason,
})
terminal = {**base, "choices": endings}
if isinstance(completion.get("usage"), dict):
terminal["usage"] = completion["usage"]
events.append(terminal)
return b"".join(
b"data: " + json.dumps(event, separators=(",", ":")).encode("utf-8") + b"\n\n"
for event in events
) + b"data: [DONE]\n\n"
def _is_terminal_stream_payload(payload: dict[str, Any]) -> bool:
"""Recognize terminal Chat/Completions and Responses API stream events."""
choices = payload.get("choices")
if isinstance(choices, list) and any(
isinstance(choice, dict) and choice.get("finish_reason") is not None
for choice in choices
):
return True
event_type = payload.get("type")
if event_type == "response.completed":
return True
response = payload.get("response")
if isinstance(response, dict) and response.get("status") == "completed":
return True
return payload.get("status") == "completed"
class _SSERewriter:
"""Incrementally frames SSE so transport chunk boundaries are irrelevant."""
def __init__(self, alias: str, expected_model: str) -> None:
self.alias = alias
self.expected_model = expected_model
self.buffer = b""
# Evidence needs only an irreversible mismatch verdict. Retaining one
# decoded model string per token makes long responses grow in memory.
self.identity_matches = True
self.response_model: str | None = None
self.response_model_consistent = True
self.response_error = False
self.usage = {
"input_tokens": 0,
"output_tokens": 0,
"cache_read_tokens": 0,
"cache_write_tokens": 0,
}
self.stop_reason = ""
self.completed = False
def _observe(
self, payloads: list[dict[str, Any]], *, saw_done: bool = False
) -> None:
self.completed = self.completed or saw_done
for payload in payloads:
self.response_error = self.response_error or response_reports_failure(payload)
usage, stop_reason = _usage_from_response(payload)
for key, value in usage.items():
self.usage[key] = max(self.usage[key], value)
if stop_reason:
self.stop_reason = stop_reason
self.completed = self.completed or _is_terminal_stream_payload(payload)
def _observe_models(self, models: list[str]) -> None:
self.identity_matches = self.identity_matches and all(
model == self.expected_model for model in models
)
for model in models:
# A receipt reports the backend identity actually observed, but
# must not hide a mid-stream identity change or retain unbounded
# backend-controlled strings.
if len(model) > 256:
self.response_model_consistent = False
elif self.response_model is None:
self.response_model = model
elif model != self.response_model:
self.response_model_consistent = False
def feed(self, chunk: bytes) -> list[bytes]:
self.buffer += chunk
output: list[bytes] = []
while match := _SSE_DELIMITER_RE.search(self.buffer):
if match.end() == len(self.buffer) and self.buffer.endswith(b"\r"):
# A transport split may put the LF of CRLF in the next chunk.
break
event = self.buffer[:match.start()]
delimiter = self.buffer[match.start():match.end()]
self.buffer = self.buffer[match.end():]
rewritten, models, payloads, saw_done = _rewrite_sse_event(
event, self.alias
)
self._observe_models(models)
self._observe(payloads, saw_done=saw_done)
output.append(rewritten + delimiter)
return output
def finish(self) -> bytes:
if not self.buffer:
return b""
rewritten, models, payloads, saw_done = _rewrite_sse_event(
self.buffer, self.alias
)
self._observe_models(models)
self._observe(payloads, saw_done=saw_done)
self.buffer = b""
return rewritten
async def _read_bounded_body(request: Request) -> bytes:
"""Read the ASGI body incrementally and stop at the configured limit."""
content_length = request.headers.get("content-length")
if content_length:
try:
if int(content_length) > MAX_BODY_BYTES:
raise RouterError(413, "payload_too_large",
"Request body exceeds the router limit")
except ValueError:
pass
chunks: list[bytes] = []
size = 0
async for chunk in request.stream():
size += len(chunk)
if size > MAX_BODY_BYTES:
raise RouterError(413, "payload_too_large",
"Request body exceeds the router limit")
chunks.append(chunk)
return b"".join(chunks)
async def _release_admission() -> None:
global _inflight
with anyio.CancelScope(shield=True):
async with _inflight_lock:
_inflight -= 1
class _OwnedStream(StreamingResponse):
"""Response, not its possibly unstarted iterator, owns upstream admission."""
def __init__(self, *args, cleanup, **kwargs):
super().__init__(*args, **kwargs)
self._cleanup = cleanup
self._closed = False
async def close(self):
with anyio.CancelScope(shield=True):
if not self._closed:
self._closed = True
await self._cleanup()
async def __call__(self, scope, receive, send):
try:
# ASGI 2.4 lets StreamingResponse rely only on a failed send.
# Inference can stay silent during prefill or buffered output, so
# always observe disconnects while awaiting the next upstream byte.
stream = asyncio.create_task(self.stream_response(send))
watcher = asyncio.create_task(self.listen_for_disconnect(receive))
try:
done, _ = await asyncio.wait((stream, watcher), return_when=asyncio.FIRST_COMPLETED)
for task in done:
await task
finally:
with anyio.CancelScope(shield=True):
for task in (stream, watcher):
if not task.done():
task.cancel()
await asyncio.gather(stream, watcher, return_exceptions=True)
if self.background is not None:
await self.background()
finally:
await self.close()
async def _while_connected(request, operation):
"""Propagate client cancellation while queued or waiting for model headers."""
stopped = False
async def disconnected():
while not stopped:
if await request.is_disconnected():
return
if stopped:
return
await asyncio.sleep(0.25)
work = asyncio.create_task(operation)
watcher = asyncio.create_task(disconnected())
handed_off = False
try:
done, _ = await asyncio.wait((work, watcher), return_when=asyncio.FIRST_COMPLETED)
if watcher in done:
await watcher
return Response(status_code=499)
result = await work
handed_off = True
return result
finally:
stopped = True
with anyio.CancelScope(shield=True):
watcher.cancel()
with suppress(asyncio.CancelledError, Exception):
await watcher
if not work.done():
work.cancel()
with suppress(asyncio.CancelledError):
await work
# Completion and disconnect can arrive together. Dispose of the
# ready streaming response if no caller accepted its ownership.
if not handed_off and work.done() and not work.cancelled() and work.exception() is None:
orphan = work.result()
if isinstance(orphan, _OwnedStream):
await orphan.close()
def _expire_swap_gate_locked() -> None:
"""Expire an abandoned admission gate while holding ``_inflight_lock``."""
global _swap_gate
if _swap_gate is not None and time.monotonic() >= _swap_gate["expiresAt"]:
logger.warning("model-swap admission gate lease expired; reopening admission")
_swap_gate = None
async def _admit_request() -> tuple[bool, str]:
"""Atomically wait out a model swap and reserve an upstream slot.
The swap controller and this function share ``_inflight_lock``. Once the
controller closes the gate, no request can slip between an idle check and
the runtime restart. Waiting requests are bounded separately from active
upstream work, so a closed gate can drain to a mechanically stable zero.
"""
global _inflight, _waiting
deadline = time.monotonic() + QUEUE_WAIT_SECONDS
async with _inflight_lock:
_expire_swap_gate_locked()
if _inflight + _waiting >= MAX_QUEUE_DEPTH:
return False, "queue_full"
_waiting += 1
admitted = False
try:
while True:
async with _inflight_lock:
_expire_swap_gate_locked()
if _swap_gate is None:
_waiting -= 1
_inflight += 1
admitted = True
return True, ""
if time.monotonic() >= deadline:
return False, "model_swap_in_progress"
await asyncio.sleep(0.25)
finally:
if not admitted:
with anyio.CancelScope(shield=True):
async with _inflight_lock:
_waiting -= 1
@app.get("/health")
async def health() -> dict[str, Any]:
doc = _read_state()
endpoints = _load_endpoints()
async with _inflight_lock:
_expire_swap_gate_locked()
active_requests = _inflight
queued_requests = _waiting
swap_gate_active = _swap_gate is not None
# Body-level signal only: with an empty allowlist every forward answers
# endpoint_not_allowlisted, but the HTTP status stays 200 so the compose
# healthcheck does not cascade a config gap into container restarts.
return {
"status": "ok" if endpoints else "degraded",
"endpointCount": len(endpoints),
"hasRoute": bool((doc or {}).get("active")),
"seq": (doc or {}).get("seq"),
"routeSeq": (doc or {}).get("routeSeq"),
"instanceId": INSTANCE_ID,
"probeKeyConfigured": bool(_current_probe_key()),
"activeRequests": active_requests,
"queuedRequests": queued_requests,
"modelSwapGateActive": swap_gate_active,
}
@app.get("/v1/models")
async def list_models() -> dict[str, Any]:
data = [{"id": alias, "object": "model", "owned_by": "ods"}
for alias in PUBLIC_ALIASES]
try:
route = _active_route()
metadata = {"routedModel": route["runtimeModelId"],
"catalogId": route["catalogId"],
"backend": route["backendKind"],
"routeSeq": route["routeSeq"], "contextLength": route["contextLength"],
"capabilities": route["capabilities"]}
except RouterError:
metadata = {"routedModel": None, "catalogId": None, "backend": None, "routeSeq": None}
return {"object": "list", "data": data, "ods": metadata}
@app.get("/internal/route-evidence/{probe_id}")
async def route_evidence(probe_id: str, request: Request) -> Response:
provided = request.headers.get("authorization", "")
if not INTERNAL_KEY or provided != f"Bearer {INTERNAL_KEY}":
return JSONResponse({"error": "unauthorized"}, status_code=401)
record = _evidence.get(probe_id)
attempts = _probe_attempts.public(probe_id, _current_probe_key())
if record is None or time.monotonic() - record["storedAt"] > EVIDENCE_TTL_SECONDS:
if attempts is None:
return JSONResponse({"error": "not_found"}, status_code=404)
public = {"probeId": probe_id, "instanceId": INSTANCE_ID}
else:
public = {k: v for k, v in record.items() if k != "storedAt"}
if attempts is not None:
public["upstreamAttempts"] = attempts
return JSONResponse(public)
@app.post("/internal/route-evidence/{probe_id}/capture")
async def capture_probe_attempts(probe_id: str, request: Request) -> Response:
"""Arm one signed probe, never ordinary traffic or raw-payload logging."""
if not INTERNAL_KEY or request.headers.get("authorization", "") != f"Bearer {INTERNAL_KEY}":
return JSONResponse({"error": "unauthorized"}, status_code=401)
try:
body = bytearray()
async for chunk in request.stream():
body.extend(chunk)
if len(body) > 512:
return JSONResponse({"error": "body_too_large"}, status_code=413)
value = json.loads(body)
if type(value) is not dict or set(value) != {"ttlSeconds", "maxAttempts"}:
raise ValueError("Invalid lease")
result = _probe_attempts.arm(probe_id, value["ttlSeconds"], value["maxAttempts"],
_current_probe_key())
except FileExistsError:
return JSONResponse({"error": "capture_exists"}, status_code=409)
except (ValueError, TypeError):
return JSONResponse({"error": "invalid_capture_lease"}, status_code=400)
return JSONResponse({**result, "instanceId": INSTANCE_ID}, status_code=201)
@app.post("/internal/model-swap/admission")
async def model_swap_admission(request: Request) -> Response:
"""Lease the request-admission gate for a serialized runtime swap.
This endpoint is reachable only inside the Compose network and requires
the router's internal bearer key. Leases are deliberately short: the
upgrader renews while it owns the lifecycle lock, and a killed upgrader
cannot strand the router closed.
"""
provided = request.headers.get("authorization", "")
if not INTERNAL_KEY or provided != f"Bearer {INTERNAL_KEY}":
return JSONResponse({"error": "unauthorized"}, status_code=401)
try:
body = await request.json()
except (ValueError, json.JSONDecodeError):
return JSONResponse({"error": "invalid_json"}, status_code=400)
if not isinstance(body, dict):
return JSONResponse({"error": "invalid_request"}, status_code=400)
action = body.get("action")
token = body.get("token")
if action not in {"begin", "end"} or not isinstance(token, str) \
or not re.fullmatch(r"[A-Za-z0-9._-]{16,128}", token):
return JSONResponse({"error": "invalid_request"}, status_code=400)
global _swap_gate
async with _inflight_lock:
_expire_swap_gate_locked()
if action == "end":
if _swap_gate is None:
return JSONResponse({"status": "open", "activeRequests": _inflight})
if _swap_gate["token"] != token:
return JSONResponse({"error": "gate_owned"}, status_code=409)
_swap_gate = None
return JSONResponse({"status": "open", "activeRequests": _inflight})
lease_seconds = body.get("leaseSeconds", 30)
if not isinstance(lease_seconds, int) or isinstance(lease_seconds, bool) \
or not 5 <= lease_seconds <= 120:
return JSONResponse({"error": "invalid_lease"}, status_code=400)
if _swap_gate is not None and _swap_gate["token"] != token:
return JSONResponse({"error": "gate_owned"}, status_code=409)
_swap_gate = {
"token": token,
"expiresAt": time.monotonic() + lease_seconds,
}
return JSONResponse({
"status": "closed",
"activeRequests": _inflight,
"queuedRequests": _waiting,
"leaseSeconds": lease_seconds,
})
@app.api_route("/{full_path:path}", methods=["GET", "POST", "PUT", "DELETE",
"PATCH", "HEAD", "OPTIONS", "CONNECT"])
async def forward(full_path: str, request: Request) -> Response:
path = "/" + full_path
method = FORWARD_PATHS.get(path)
if method is None or request.method != method:
return JSONResponse(
{"error": {"message": f"Path not served by the ODS model router: {path}",
"type": "not_forwarded", "code": "404"}},
status_code=404,
)
try:
body = await _read_bounded_body(request)
except RouterError as exc:
return JSONResponse(
{"error": {"message": exc.message, "type": exc.code,
"code": str(exc.status)}},
status_code=exc.status,
)
try:
payload = json.loads(body.decode("utf-8"))
if not isinstance(payload, dict):
raise ValueError("body must be a JSON object")
except (ValueError, UnicodeDecodeError) as exc:
return JSONResponse(
{"error": {"message": f"Invalid JSON body: {exc}",
"type": "invalid_request_error", "code": "400"}},
status_code=400,
)
requested_alias = str(payload.get("model") or PUBLIC_ALIASES[0])
return await _while_connected(request, _forward_admitted(request, path, payload, requested_alias, body))
async def _forward_admitted(request, path, payload, requested_alias, body):
admitted, reason = await _admit_request()
if not admitted:
if reason == "queue_full":
return JSONResponse(
{"error": {"message": "Router queue is full",
"type": "overloaded", "code": "503"}},
status_code=503, headers={"Retry-After": "5"},
)
return JSONResponse(
{"error": {"message": "A model swap is in progress",
"type": "model_swap_in_progress", "code": "503"}},
status_code=503, headers={"Retry-After": "10"},
)
stream_owns_admission = False
try:
response, stream_owns_admission = await _forward_inner(
request, path, payload, requested_alias, body
)
return response
finally:
if not stream_owns_admission:
await _release_admission()
async def _forward_inner(request: Request, path: str, payload: dict[str, Any],
requested_alias: str,
raw_body: bytes) -> tuple[Response, bool]:
deadline = time.monotonic() + QUEUE_WAIT_SECONDS
while True:
try:
route = _active_route()
except RouterError as exc:
return JSONResponse(
{"error": {"message": exc.message, "type": exc.code,
"code": str(exc.status)}},
status_code=exc.status,
headers={"Retry-After": "5"} if exc.status == 503 else {},
), False
if not route["queueMode"]:
break
if time.monotonic() >= deadline:
return JSONResponse(
{"error": {"message": "A model swap is in progress",
"type": "model_swap_in_progress", "code": "503"}},
status_code=503, headers={"Retry-After": "10"},
), False
await asyncio.sleep(0.25)
# Additive precondition for inference-only sharing. It is checked after
# admission/queueing and before any upstream bytes are sent. Legacy clients
# omit all three headers and retain their existing alias behavior.
pin_names = ("x-ods-expected-catalog", "x-ods-expected-model", "x-ods-expected-route")
pinned_route = any(name in request.headers for name in pin_names)
if pinned_route:
values = [request.headers.getlist(name) for name in pin_names]
if (any(len(value) != 1 or not value[0] for value in values)
or not re.fullmatch(r"0|[1-9][0-9]{0,15}", values[2][0])
or int(values[2][0]) > 2**53 - 1):
return JSONResponse({"error": {"message": "Invalid route precondition",
"type": "route_precondition_invalid", "code": "400"}}, status_code=400), False
if (values[0][0] != route["catalogId"] or values[1][0] != route["runtimeModelId"]
or int(values[2][0]) != route["routeSeq"]):
return JSONResponse({"error": {"message": "The selected model route changed",
"type": "route_changed", "code": "409"}}, status_code=409), False
payload["model"] = route["runtimeModelId"]
thinking_level = None
if path == "/v1/chat/completions" and route["backendKind"] == "vllm" and route["thinking"]:
try:
payload, thinking_level = _vllm_thinking_payload(payload, route["thinking"])
except RouterError as exc:
return JSONResponse(
{"error": {"message": exc.message, "type": exc.code, "code": str(exc.status)}},
status_code=exc.status,
), False
# The stable client alias hides the selected template from agents. Adapt
# only outgoing Nemo history after resolving the current route; audit and
# response IDs remain unchanged, including across model switches.
if (path == "/v1/chat/completions"
and route_requires_strict9_tool_ids(route["runtimeModelId"], route["backendKind"])):
messages, changed = normalize_history_tool_ids(payload.get("messages"))
if changed:
payload["messages"] = messages
request_id = str(uuid.uuid4())
probe_id = _verify_probe_marker(raw_body.decode("utf-8", "replace"))
is_stream = bool(payload.get("stream"))
completed_tool_stream = (
is_stream
and path == "/v1/chat/completions"
and _llama_tool_compat(route)
and isinstance(payload.get("tools"), list)
and bool(payload["tools"])
)
thinking_options = payload.get("chat_template_kwargs")
thinking_tool_compat = (
completed_tool_stream
and isinstance(thinking_options, dict)
and thinking_options.get("enable_thinking") is True
)
if thinking_tool_compat:
# Live thinking-enabled llama.cpp emitted a JSON description of a
# function as text when streaming, but a structured API call when
# nonstreaming. Keep its prior single-request behavior. Stop remains
# limited by that backend's nonstream cancellation semantics.
payload["stream"] = False
payload.pop("stream_options", None)
elif completed_tool_stream:
# Keep the upstream stream open while _while_connected watches Stop.
# Buffer and verify its complete decision before sending any tool call
# to the client; partial llama.cpp tool deltas are never exposed.
options = payload.get("stream_options")
payload["stream_options"] = {
**(options if isinstance(options, dict) else {}),
"include_usage": True,
}
headers = _sanitize_headers(request)
api_key = os.environ.get(route["apiKeyEnv"], "") if route["apiKeyEnv"] else ""
if api_key:
headers["authorization"] = f"Bearer {api_key}"
ods_headers = {
"X-ODS-Request-Id": request_id,
"X-ODS-Requested-Model": requested_alias,
"X-ODS-Routed-Model": route["runtimeModelId"],
"X-ODS-Backend": route["backendKind"],
"X-ODS-Route-Seq": str(route["routeSeq"]),
}
if thinking_tool_compat:
ods_headers["X-ODS-Tool-Stream-Compatibility"] = "thinking-nonstream"
if thinking_level is not None:
ods_headers["X-ODS-Thinking-Level"] = thinking_level
url = route["baseUrl"] + path
client: httpx.AsyncClient = app.state.http
telemetry_started = time.monotonic()
evidence_base = {
"probeId": probe_id,
"requestId": request_id,
"requestedModel": requested_alias,
"routedModel": route["runtimeModelId"],
"backend": route["backendKind"],
"endpointId": route["endpointId"],
"routeSeq": route["routeSeq"],
"path": path,
**({"offeredTools": _offered_tool_evidence(payload)} if probe_id else {}),
}
attempt_handle = None
response_metadata = {"failed": False}
next_attempt = 2
try:
forwarded_body = json.dumps(payload).encode("utf-8")
attempt_handle = _begin_probe_attempt(probe_id, request_id, 1, forwarded_body, route)
if thinking_tool_compat:
upstream = await client.post(
url, content=forwarded_body, headers=headers,
timeout=UPSTREAM_TIMEOUT_SECONDS,
)
_finish_probe_attempt(attempt_handle, "complete", upstream.status_code)
elif completed_tool_stream:
upstream_request = client.build_request(
"POST", url, content=forwarded_body,
headers=headers, timeout=UPSTREAM_TIMEOUT_SECONDS,
)
streaming_upstream = await client.send(upstream_request, stream=True)
try:
chunks: list[bytes] = []
byte_count = 0
async for chunk in streaming_upstream.aiter_bytes():
byte_count += len(chunk)
if byte_count > MAX_COMPLETED_TOOL_STREAM_BYTES:
_finish_probe_attempt(attempt_handle, "stream-error",
streaming_upstream.status_code)
return JSONResponse({"error": {
"message": "Backend tool response exceeded the stream limit",
"type": "upstream_invalid_response", "code": "502",
}}, status_code=502, headers=ods_headers), False
chunks.append(chunk)
raw_stream = b"".join(chunks)
fallback = False
decoded_headers = {
name: value for name, value in streaming_upstream.headers.items()
if name.lower() not in {
"content-encoding", "content-length", "transfer-encoding",
}
}
if 200 <= streaming_upstream.status_code < 300:
try:
complete = assemble_chat_completion_sse(
raw_stream, route["runtimeModelId"],
max_bytes=MAX_COMPLETED_TOOL_STREAM_BYTES,
response_metadata=response_metadata,
)
except CompletionStreamIdentityError as exc:
rejection = completion_stream_rejection_code(exc)
logger.warning("Completed tool stream rejected: %s", rejection)
_finish_probe_attempt(attempt_handle, "stream-error",
streaming_upstream.status_code)
return JSONResponse({"error": {
"message": f"Backend response identity changed [{rejection}]",
"type": "response_identity_mismatch", "code": "502",
"diagnosticCode": rejection,
}}, status_code=502, headers=ods_headers), False
except ValueError as exc:
rejection = completion_stream_rejection_code(exc)
# Some backends ignore stream:true and return a
# completed JSON response. Process that one response
# without issuing a second inference.
try:
complete = json.loads(raw_stream.decode("utf-8"))
except (ValueError, UnicodeDecodeError):
complete = None
if (not isinstance(complete, dict)
or not isinstance(complete.get("choices"), list)
and not isinstance(complete.get("error"), dict)):
_finish_probe_attempt(attempt_handle, "stream-error",
streaming_upstream.status_code)
logger.warning("Completed tool stream rejected: %s", rejection)
return JSONResponse({"error": {
"message": f"Backend returned an invalid completed tool stream [{rejection}]",
"type": "upstream_invalid_response", "code": "502",
"diagnosticCode": rejection,
}}, status_code=502, headers=ods_headers), False
if ("error" not in complete
and complete.get("model") != route["runtimeModelId"]):
_finish_probe_attempt(attempt_handle, "stream-error",
streaming_upstream.status_code)
return JSONResponse({"error": {
"message": "Backend response identity changed",
"type": "response_identity_mismatch", "code": "502",
}}, status_code=502, headers=ods_headers), False
decoded_headers["content-type"] = "application/json"
upstream = httpx.Response(
streaming_upstream.status_code, content=raw_stream,
headers=decoded_headers,
)
else:
invalid = _repaired_tool_decision_invalid(complete, payload)
if (invalid and _complete_native_envelope_names(complete) is None
and not _complete_structured_tool_decision(complete)):
_log_tool_rejection("stream", _tool_decision_rejection(complete, payload))
_finish_probe_attempt(attempt_handle, "stream-error",
streaming_upstream.status_code)
return JSONResponse({"error": {
"message": "Backend returned an invalid tool decision",
"type": "tool_protocol_invalid", "code": "502",
}}, status_code=502, headers=ods_headers), False
if invalid:
# A complete rejected decision can use the single
# shared repair before any call reaches the agent.
ods_headers["X-ODS-Tool-Stream-Repair"] = "true"
decoded_headers["content-type"] = "application/json"
upstream = httpx.Response(
streaming_upstream.status_code,
content=json.dumps(complete).encode("utf-8"),
headers=decoded_headers,
)
elif (streaming_upstream.status_code == 500
and b"Invalid diff: now finding less tool calls!" in raw_stream):
# Older llama.cpp builds cannot complete streamed tool
# diffs. Retain their complete-response compatibility path.
fallback = True
else:
upstream = httpx.Response(
streaming_upstream.status_code, content=raw_stream,
headers=decoded_headers,
)
_finish_probe_attempt(attempt_handle,
"stream-error" if fallback else "complete",
streaming_upstream.status_code)
if fallback:
fallback_payload = {**payload, "stream": False}
fallback_payload.pop("stream_options", None)
fallback_body = json.dumps(fallback_payload).encode("utf-8")
attempt_handle = _begin_probe_attempt(
probe_id, request_id, next_attempt, fallback_body, route,
)
response_metadata = {"failed": False}
next_attempt += 1
ods_headers["X-ODS-Tool-Stream-Fallback"] = "true"
remaining = UPSTREAM_TIMEOUT_SECONDS - (
time.monotonic() - telemetry_started
)
if remaining <= 0:
raise httpx.ReadTimeout("tool stream fallback deadline expired")
upstream = await client.post(
url, content=fallback_body, headers=headers, timeout=remaining,
)
_finish_probe_attempt(attempt_handle, "complete",
upstream.status_code)
finally:
await streaming_upstream.aclose()
elif is_stream:
upstream_request = client.build_request(
"POST", url, content=forwarded_body,
headers=headers, timeout=UPSTREAM_TIMEOUT_SECONDS,
)
upstream = await client.send(upstream_request, stream=True)
async def cleanup_stream():
try:
with suppress(httpx.HTTPError, OSError):
await upstream.aclose()
finally:
_finish_probe_attempt(attempt_handle, "cancelled", upstream.status_code)
await _release_admission()
async def stream_body() -> AsyncIterator[bytes]:
rewriter = _SSERewriter(requested_alias, route["runtimeModelId"])
completed = False
disconnected = False
try:
async for chunk in upstream.aiter_bytes():
events = rewriter.feed(chunk)
if pinned_route and not rewriter.identity_matches:
raise RouterError(502, 'response_identity_mismatch', 'Backend response identity changed')
for event in events:
yield event
if await request.is_disconnected():
disconnected = True
break
tail = rewriter.finish()
if pinned_route and not rewriter.identity_matches:
raise RouterError(502, 'response_identity_mismatch', 'Backend response identity changed')
if tail:
yield tail
completed = True
except asyncio.CancelledError:
_finish_probe_attempt(attempt_handle, "cancelled", upstream.status_code)
raise
except Exception:
_finish_probe_attempt(attempt_handle, "stream-error", upstream.status_code)
raise
finally:
_finish_probe_attempt(attempt_handle,
"complete" if completed and not disconnected else "cancelled", upstream.status_code)
if (
completed
and rewriter.completed
and probe_id
and 200 <= upstream.status_code < 300
and rewriter.response_model_consistent
):
if not rewriter.response_error:
_observe_probe_response_model(attempt_handle, rewriter.response_model)
_record_evidence({
**evidence_base,
"status": upstream.status_code,
# The selected route is already reported separately.
# Never present it as a backend identity when the
# stream supplied no model field to observe.
"responseModel": rewriter.response_model or "",
})
if (
completed
and rewriter.completed
and 200 <= upstream.status_code < 300
):
_emit_telemetry(_build_telemetry_event(
payload,
raw_body_bytes=len(raw_body),
model=route["runtimeModelId"],
backend=route["backendKind"],
path=path,
duration_ms=int(
(time.monotonic() - telemetry_started) * 1000
),
usage=rewriter.usage,
stop_reason=rewriter.stop_reason,
))
media_type = upstream.headers.get("content-type",
"text/event-stream")
return _OwnedStream(
stream_body(), status_code=upstream.status_code,
media_type=media_type, headers=ods_headers, cleanup=cleanup_stream,
), True
else:
upstream = await client.post(
url, content=forwarded_body, headers=headers,
timeout=UPSTREAM_TIMEOUT_SECONDS,
)
_finish_probe_attempt(attempt_handle, "complete", upstream.status_code)
except asyncio.CancelledError:
_finish_probe_attempt(attempt_handle, "cancelled")
raise
except httpx.TimeoutException:
_finish_probe_attempt(attempt_handle, "timeout")
return JSONResponse(
{"error": {"message": "Upstream model runtime timed out",
"type": "upstream_timeout", "code": "504"}},
status_code=504, headers=ods_headers,
), False
except httpx.HTTPError as exc:
_finish_probe_attempt(attempt_handle, "transport-error")
logger.warning("Upstream model runtime unavailable: %s", exc)
return JSONResponse(
{"error": {"message": "Upstream model runtime unavailable",
"type": "upstream_unavailable", "code": "502"}},
status_code=502, headers=ods_headers,
), False
# Bounded protocol repair, only before the agent has seen a tool call: one
# repair, or _SCHEMA_REPAIR_LIMIT while the latest decision's only fault is
# its arguments against the offered schema. A complete native envelope is a
# model decision, not an executed action; no host/tool operation is
# replayed here. Every rejected decision is logged by shape, never values.
if (path == "/v1/chat/completions"
and _llama_tool_compat(route)
and _repairable_native_tool_request(payload)
and isinstance(payload.get("messages"), list)
and 200 <= upstream.status_code < 300):
try:
initial_decision = json.loads(upstream.content.decode("utf-8"))
except (ValueError, UnicodeDecodeError):
initial_decision = None
if isinstance(initial_decision, dict):
if not response_metadata["failed"] and not response_reports_failure(initial_decision):
_observe_probe_response_model(attempt_handle, initial_decision.get("model"))
native_names = _complete_native_envelope_names(initial_decision)
native_invalid = native_names is not None and not _normalize_native_tool_markup(
initial_decision, payload,
)
structured_invalid = (native_names is None
and _complete_structured_tool_decision(initial_decision)
and _repaired_tool_decision_invalid(initial_decision, payload))
if native_invalid or structured_invalid:
if ((pinned_route or structured_invalid) and initial_decision.get("model")
!= route["runtimeModelId"]):
return JSONResponse({'error': {'message': 'Backend response identity changed',
'type': 'response_identity_mismatch', 'code': '502'}},
status_code=502, headers=ods_headers), False
rejection = _tool_decision_rejection(initial_decision, payload)
_log_tool_rejection("initial", rejection)
repairs = 0
while True:
repairs += 1
remaining = UPSTREAM_TIMEOUT_SECONDS - (time.monotonic() - telemetry_started)
if remaining <= 0:
return JSONResponse({"error": {
"message": "Upstream model runtime timed out during tool protocol repair",
"type": "upstream_timeout", "code": "504",
}}, status_code=504, headers=ods_headers), False
repair_payload = {**payload, "stream": False,
"messages": [*payload["messages"], {"role": "user",
"content": _tool_repair_feedback(rejection, payload, native_names)}]}
repair_payload.pop("stream_options", None)
repair_handle = None
try:
repair_body = json.dumps(repair_payload).encode("utf-8")
repair_handle = _begin_probe_attempt(
probe_id, request_id, next_attempt, repair_body, route,
)
next_attempt += 1
upstream = await client.post(
url, content=repair_body,
headers=headers, timeout=remaining,
)
_finish_probe_attempt(repair_handle, "complete", upstream.status_code)
# The common response parser must attribute the repaired
# response to this send, not to the original tool decision.
attempt_handle = repair_handle
response_metadata = {"failed": False}
except asyncio.CancelledError:
_finish_probe_attempt(repair_handle, "cancelled")
raise
except httpx.TimeoutException:
_finish_probe_attempt(repair_handle, "timeout")
return JSONResponse({"error": {
"message": "Upstream model runtime timed out during tool protocol repair",
"type": "upstream_timeout", "code": "504",
}}, status_code=504, headers=ods_headers), False
except httpx.HTTPError as exc:
_finish_probe_attempt(repair_handle, "transport-error")
logger.warning("Upstream model runtime unavailable during tool protocol repair: %s", exc)
return JSONResponse({"error": {
"message": "Upstream model runtime unavailable during tool protocol repair",
"type": "upstream_unavailable", "code": "502",
}}, status_code=502, headers=ods_headers), False
if not 200 <= upstream.status_code < 300:
break
try:
repaired = json.loads(upstream.content.decode("utf-8"))
except (ValueError, UnicodeDecodeError):
repaired = None
if isinstance(repaired, dict) and not response_reports_failure(repaired):
_observe_probe_response_model(repair_handle, repaired.get("model"))
if (structured_invalid and isinstance(repaired, dict)
and repaired.get("model") != route["runtimeModelId"]):
return JSONResponse({"error": {
"message": "Backend response identity changed",
"type": "response_identity_mismatch", "code": "502",
}}, status_code=502, headers=ods_headers), False
if (isinstance(repaired, dict)
and not _repaired_tool_decision_invalid(repaired, payload)):
break
rejection = (_tool_decision_rejection(repaired, payload)
if isinstance(repaired, dict) else {"kind": "protocol", "rule": "response"})
_log_tool_rejection(f"repair {repairs}", rejection)
if repairs >= (_SCHEMA_REPAIR_LIMIT if rejection["kind"] == "schema" else 1):
return JSONResponse({"error": {
"message": "Model returned an invalid tool decision after "
+ ("one protocol repair" if repairs == 1 else f"{repairs} protocol repairs"),
"type": "tool_protocol_invalid", "code": "502",
}}, status_code=502, headers=ods_headers), False
native_names = _complete_native_envelope_names(repaired)
response_model = None
response_usage = {
"input_tokens": 0,
"output_tokens": 0,
"cache_read_tokens": 0,
"cache_write_tokens": 0,
}
stop_reason = ""
content = upstream.content
parsed: dict[str, Any] | None = None
try:
decoded = json.loads(content.decode("utf-8"))
if isinstance(decoded, dict):
parsed = decoded
response_usage, stop_reason = _usage_from_response(parsed)
response_model = parsed.get("model")
if not response_metadata["failed"] and not response_reports_failure(parsed):
_observe_probe_response_model(attempt_handle, response_model)
if "model" in parsed:
parsed["model"] = requested_alias
_sanitize_choice_content(parsed)
content = json.dumps(parsed).encode("utf-8")
except (ValueError, UnicodeDecodeError):
pass
if pinned_route and 200 <= upstream.status_code < 300 and response_model != route['runtimeModelId']:
return JSONResponse({'error': {'message': 'Backend response identity changed',
'type': 'response_identity_mismatch', 'code': '502'}}, status_code=502, headers=ods_headers), False
if (parsed is not None and 200 <= upstream.status_code < 300
and path == "/v1/chat/completions"
and _llama_tool_compat(route)
and isinstance(payload.get("tools"), list) and payload["tools"]
and _normalize_native_tool_markup(parsed, payload)):
content = json.dumps(parsed).encode("utf-8")
stop_reason = "tool_calls"
completed_stream_body: bytes | None = None
if completed_tool_stream and 200 <= upstream.status_code < 300:
try:
if parsed is None:
raise ValueError("Backend returned a non-JSON Chat completion")
completed_stream_body = _completed_chat_as_sse(parsed)
except ValueError as exc:
logger.warning("invalid completed tool response from model backend: %s", exc)
return JSONResponse({"error": {
"message": "Backend returned an invalid completed tool response",
"type": "upstream_invalid_response", "code": "502",
}}, status_code=502, headers=ods_headers), False
if probe_id:
_record_evidence({**evidence_base,
"status": upstream.status_code,
"responseModel": str(response_model or "")})
if 200 <= upstream.status_code < 300:
_emit_telemetry(_build_telemetry_event(
payload,
raw_body_bytes=len(raw_body),
model=route["runtimeModelId"],
backend=route["backendKind"],
path=path,
duration_ms=int((time.monotonic() - telemetry_started) * 1000),
usage=response_usage,
stop_reason=stop_reason,
))
if completed_stream_body is not None:
return Response(content=completed_stream_body, status_code=200,
media_type="text/event-stream", headers=ods_headers), False
media_type = upstream.headers.get("content-type", "application/json")
return Response(content=content, status_code=upstream.status_code,
media_type=media_type, headers=ods_headers), False
@app.on_event("startup")
async def _startup() -> None:
app.state.http = httpx.AsyncClient(
follow_redirects=False,
limits=httpx.Limits(
max_connections=UPSTREAM_MAX_CONNECTIONS,
max_keepalive_connections=min(
UPSTREAM_MAX_KEEPALIVE, UPSTREAM_MAX_CONNECTIONS
),
),
)
app.state.telemetry = _TelemetrySink(TOKEN_SPY_URL, TOKEN_SPY_API_KEY)
await app.state.telemetry.start()
_load_endpoints()
@app.on_event("shutdown")
async def _shutdown() -> None:
telemetry: _TelemetrySink | None = getattr(app.state, "telemetry", None)
if telemetry is not None:
await telemetry.stop()
await app.state.http.aclose()