Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 155 additions & 1 deletion app/cetirun-ai-gateway/cetirun_ai_gateway/guard.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,16 @@
CetiRun operator issued gets the 403 above for any request of its own to a
decision model.

A router's request to a decision model to classify a request is held to the
model's context. LiteLLM sends a jev classifier the caller's whole system
prompt and its latest user messages, however long they are;
Microsoft-Decision-1 refused a request over its 32,768 tokens with 422, and
the router then classified the request with its fallback instead, without an
error. Such a request is shortened to as many bytes as the model takes tokens,
less its questions and a reserve: the newest message stays whole where it
fits, the rest keeps its beginning and its end, and each change is logged. A
client's own call to the Decisions API is left as it is.

Error messages returned to callers no longer include LiteLLM's internal list of
deployments in cooldown: when no deployment of a model is available, LiteLLM's
message lists the IDs of every deployment in cooldown, of any model. The proxy
Expand Down Expand Up @@ -92,6 +102,7 @@
sight. LiteLLM's own rule decides, read from LiteLLM, and each change is logged.
"""

import json
import re
import sys

Expand Down Expand Up @@ -165,6 +176,29 @@
# The modes of a model Agents can hold a conversation with; a deployment without one counts.
CHAT_MODES = (None, "", "chat", "completion", "responses")

# The line LiteLLM's complexity router writes before the newest user message in
# the request it sends a classifier, last; the caller's system prompt, earlier
# user messages and the conversation's length come before it
# (complexity_router.py, _build_classifier_user_payload).
CLASSIFY_MARKER = "\nClassify this message:\n"
# Microsoft-Decision-1's context in tokens, for a decision model whose
# deployments state none in model_info.max_input_tokens. It refuses a longer
# request with 422: "invalid model request: Question prompt exceeds the
# 32768-token context limit including the decision token".
DECISION_CONTEXT_TOKENS = 32768
# Bytes left for the service's own template around the request and for the
# decision token, and the fewest bytes a request is shortened to.
DECISION_RESERVE_BYTES = 512
DECISION_MINIMUM_BYTES = 1024
# LiteLLM quotes a long message by its beginning and its end, 30% and 70% of
# the room (complexity_router.py, _truncate); the guard splits the same way.
HEAD_SHARE = 0.3
ELISION = "\n[...]\n"
# What a shortened request keeps, for the warning.
KEPT_NEWEST = "the newest message whole and the beginning and the end of the rest"
KEPT_BOTH_ENDS = "the beginning and the end of the newest message and of the rest"
KEPT_REQUEST_ENDS = "the beginning and the end of the request"


def mark_encrypted_content(encrypted_content, model_id):
"""encrypted_content with the producing deployment's ID, in the Gateway's form."""
Expand Down Expand Up @@ -583,6 +617,119 @@ def evaluation_only(deployment):
return isinstance(info, dict) and info.get("mode") == "evaluation"


def decision_context(deployments):
"""The decision model's context in tokens: the smallest model_info.max_input_tokens its deployments
state, or Microsoft-Decision-1's when none states one."""
sizes = []
for deployment in deployments:
info = deployment.get("model_info") if isinstance(deployment, dict) else None
size = info.get("max_input_tokens") if isinstance(info, dict) else None
if isinstance(size, int) and not isinstance(size, bool) and size > 0:
sizes.append(size)
return min(sizes) if sizes else DECISION_CONTEXT_TOKENS


def utf8_size(text):
"""The bytes text takes as UTF-8. A lone surrogate, which JSON can carry, counts as three."""
return len(text.encode("utf-8", "surrogatepass"))


def utf8_head(text, size):
"""The longest beginning of text that takes at most size bytes of UTF-8, cut between characters."""
return text.encode("utf-8", "surrogatepass")[:max(size, 0)].decode("utf-8", "ignore")


def utf8_tail(text, size):
"""The longest end of text that takes at most size bytes of UTF-8, cut between characters."""
if size <= 0:
return ""
data = text.encode("utf-8", "surrogatepass")
if size >= len(data):
return text
return data[len(data) - size:].decode("utf-8", "ignore")


def beginning_and_end(text, size):
"""text in at most size bytes of UTF-8: whole when it fits, else its beginning and its end with an
elision line between."""
if utf8_size(text) <= size:
return text
room = size - len(ELISION)
if room <= 0:
return utf8_tail(text, size)
head = int(room * HEAD_SHARE)
return utf8_head(text, head) + ELISION + utf8_tail(text, room - head)


def question_size(questions):
"""The bytes the questions take as compact JSON, which the decision model reads with the request."""
try:
text = json.dumps(questions, ensure_ascii=False, separators=(",", ":"), default=str)
except (TypeError, ValueError, RecursionError):
text = repr(questions)
return utf8_size(text)


def bounded_classifier_state(state, budget):
"""(the request a router sends a decision model in at most budget bytes of UTF-8, what it keeps);
(state, None) when it fits already, so a second pass changes nothing.

The newest message, after the last "Classify this message:" line, which LiteLLM writes last, is kept
whole when it fits in the budget less what the rest needs, a quarter of the budget at most; otherwise
the line and the message's beginning and end. The rest, the caller's system prompt and earlier
messages, keeps its beginning and its end in the room left. Without that line, the request keeps its
beginning and its end.
"""
if utf8_size(state) <= budget:
return state, None
split = state.rfind(CLASSIFY_MARKER)
if split < 0:
return beginning_and_end(state, budget), KEPT_REQUEST_ENDS
rest, newest = state[:split], state[split:]
reserved = min(utf8_size(rest), budget // 4)
if budget - reserved < len(CLASSIFY_MARKER):
return beginning_and_end(state, budget), KEPT_REQUEST_ENDS
kept = KEPT_NEWEST
if utf8_size(newest) > budget - reserved:
message = newest[len(CLASSIFY_MARKER):]
newest = CLASSIFY_MARKER + beginning_and_end(message, budget - reserved - len(CLASSIFY_MARKER))
kept = KEPT_BOTH_ENDS
return beginning_and_end(rest, budget - utf8_size(newest)) + newest, kept


def bound_classifier_request(request_kwargs, deployments):
"""Shorten, in place, the request a router sends a decision model to classify, to fit the model's
context: (bytes before, bytes after, the context in tokens, what it keeps), or None when it fits or is
not such a request.

LiteLLM's complexity router sends a jev classifier the caller's whole system prompt, up to three
earlier user messages and the newest one, however long they are. Microsoft-Decision-1 refuses a
request over its context, and the router then classified the request with its fallback instead. The
decision model takes as many tokens as its context, less the questions, the service's own template
and the decision token. A token of the byte-level tokenizers decision models use is at least one
byte of UTF-8 (Microsoft-Decision-1 is post-trained from Qwen3.5-9B), so a request of at most that
many bytes fits in any language: Chinese text takes about three bytes a token, English about four.
That leaves several times what the router needs; LiteLLM quotes at most 8,000 characters of earlier
messages.

Only a router's own call is changed: marked as the classifier's, with the Decisions API's state and
questions. A client's own call to the Decisions API, and a classifier call that asks a chat model,
are left as they are.
"""
if not classifier_call(request_kwargs):
return None
state, questions = request_kwargs.get("state"), request_kwargs.get("questions")
if not isinstance(state, str) or not isinstance(questions, dict):
return None
context = decision_context(deployments)
budget = max(context - question_size(questions) - DECISION_RESERVE_BYTES, DECISION_MINIMUM_BYTES)
shortened, kept = bounded_classifier_state(state, budget)
if kept is None:
return None
request_kwargs["state"] = shortened
return utf8_size(state), utf8_size(shortened), context, kept


def has_deployment(name, router):
"""Whether the name is a model with a deployment of its own. A Team's router is registered under the
same name as its access group, so being one of the key's groups does not make a name a placeholder.
Expand Down Expand Up @@ -679,7 +826,8 @@ async def async_filter_deployments(
auto router's tier selection goes through this again with the same
request, so a tier is held to the same rules. A request for a decision
model through any API but the Decisions API is refused, for every
caller. While encrypted content
caller. A router's call to a decision model to classify a request is
shortened to fit the model's context. While encrypted content
affinity applies to the model, unmarked or shortened encrypted reasoning
is removed from a Responses API request first. A fallback after a
deployment refused the request's encrypted reasoning is ended here, so
Expand Down Expand Up @@ -729,6 +877,12 @@ async def async_filter_deployments(
return allowed
raise ModelRefused(model)
kept = allowed
shortened = bound_classifier_request(request_kwargs, kept) if kept else None
if shortened is not None:
before, after, context, what = shortened
verbose_proxy_logger.warning(
"CetiRun guard: shortened a router's request to the decision model %s from %d to %d bytes, to fit "
"its %d-token context; kept %s.", model, before, after, context, what)
if isinstance(request_kwargs, dict) and kept:
router = routing_router(model, request_kwargs)
target = f"the router {router} sent to" if router else "for"
Expand Down
36 changes: 34 additions & 2 deletions app/cetirun-ai-gateway/chart/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -894,7 +894,8 @@ different strings that are not blank, as LiteLLM 1.105.1 requires; the chart
rejects anything else rather than let the proxy refuse to start.

**The agent keeps its conversation and its limits.** Unless a router sets them,
the chart changes three of LiteLLM 1.105.1's router defaults:
the chart changes three of LiteLLM 1.105.1's router defaults, and a fourth for
a router with `classifier_type: jev`:

- `context_compaction: false`. LiteLLM would otherwise rewrite the
conversation history near the chosen model's input limit, with extra model
Expand All @@ -907,6 +908,17 @@ the chart changes three of LiteLLM 1.105.1's router defaults:
it, and the provider would refuse it. LiteLLM moves it to the lowest tier
with a model whose declared window fits; set `max_input_tokens` in each
model's `model_info` for that.
- `classifier_fallback: default_model`, with `classifier_type: jev`. A request
the decision model could not classify, for example while it is unavailable,
would otherwise be classified by LiteLLM's heuristic scorer, which placed 15
of 40 English and 11 of 40 Chinese prompts on the expected tier in our
tests. It goes to the router's `complexity_router_default_model` instead;
without one, LiteLLM uses the first model of the medium tier, or of the
simple tier. It is not moved to another tier, by its length or by the
escalation keyword. The response header `x-litellm-complexity-router-cause`
and the request log's `routing_cause` say `default_model_fallback`, with no
tier. A router that sets `classifier_fallback` keeps its own value; one with
its own `tier_definitions` uses its `fallback_tier`, and gets no default.

**A router is granted only with its models.** With `operatorIntegration`, the
CetiRun operator puts a router on an Agent's key only when the Agent may use
Expand Down Expand Up @@ -1393,6 +1405,26 @@ the console cannot remove it. It:
router classifying with it used its default classifier, for every caller.
The Decisions API and a router's own classifier calls reach the model as
before; a key the operator issued keeps the 403 above;
- shortens the request a router with a jev classifier sends its decision model
to as many bytes as the model takes tokens: the smallest
`model_info.max_input_tokens` of the decision model's deployments, or 32,768
when none sets it, less the questions LiteLLM asks and 512 bytes for the
service's own template. LiteLLM sends the classifier the caller's whole
system prompt and its latest user messages, however long they are.
Microsoft-Decision-1 takes 32,768 tokens and refused a longer request with a
422; the router then classified the request with its fallback, without an
error. Each token of a decision model stands for at least one byte of text,
so the shortened request fits in any language. It keeps the newest user
message whole where it fits, and the beginning and the end of the rest; a
newest message that does not fit keeps its beginning and its end. The
Gateway logs a warning with the decision model and the sizes, not the
content. A client's own calls to the Decisions API are left as they are.
Measured on LiteLLM 1.105.1 with Microsoft-Decision-1: requests with a
system prompt of 40,000 English words or 60,000 Chinese characters, or with
a 120 KB log as the message, were shortened to 31.7 KB, which
Microsoft-Decision-1 counted at 5,687 to 13,300 tokens, and the decision
model classified each; without the guard it refused each, and the heuristic
scorer classified them;
- keeps a key the CetiRun operator issued from listing what it cannot talk to:
`GET /v1/models` (and `/model/info`) leaves out the key's access groups that
LiteLLM lists as if they were models, such as an Agent's Copilot group before
Expand Down Expand Up @@ -1436,7 +1468,7 @@ the console cannot remove it. It:
Gateway's own log and the request log keep the full message.

With `operatorIntegration` off, the guard's request fields, its decision model
rule, its parameter changes and its error messages apply all the same; a
rules, its parameter changes and its error messages apply all the same; a
standalone Gateway has no `cetirun-copilot-` groups for it to separate, and no
keys the operator issued.

Expand Down
10 changes: 10 additions & 0 deletions app/cetirun-ai-gateway/chart/templates/configmap.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,13 @@ data:
tier model's ceiling, and a request too long for the decided tier's
models moved to a tier whose models can hold it, rather than refused.

A router with a jev classifier sends a request it could not classify,
for example while the decision model is unavailable, to its default
model rather than to LiteLLM's heuristic scorer, unless it sets
classifier_fallback itself. A router with its own tier_definitions
routes such a request to its fallback_tier, and LiteLLM refuses
classifier_fallback default_model next to them.

Added after the ID above, so the binding stays the administrator's
configuration. */}}
{{- $params := $model.litellm_params | default dict }}
Expand All @@ -66,6 +73,9 @@ data:
{{- if not (hasKey $config "enable_context_window_escalation") }}
{{- $_ := set $config "enable_context_window_escalation" true }}
{{- end }}
{{- if and (eq (toString (get $config "classifier_type")) "jev") (not (hasKey $config "classifier_fallback")) (not (kindIs "slice" (get $config "tier_definitions"))) }}
{{- $_ := set $config "classifier_fallback" "default_model" }}
{{- end }}
{{- $_ := set $params "complexity_router_config" $config }}
{{- $_ = set $model "litellm_params" $params }}
{{- end }}
Expand Down
3 changes: 2 additions & 1 deletion app/cetirun-ai-gateway/entrypoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,8 @@ def gateway(args, environ=None):
change the Gateway for one call, keeps per-Agent GitHub Copilot routes to
the keys that hold them, keeps operator-issued keys to the deployments of
their access groups, also when an auto router picks the model, refuses a
request for a decision model through any API but the Decisions API, removes
request for a decision model through any API but the Decisions API,
shortens a router's request to a decision model to fit its context, removes
encrypted reasoning without the Gateway's mark while encrypted content
affinity is on, writes that mark in a form clients keep, ends fallbacks
after a deployment refused a request's encrypted reasoning, removes the
Expand Down
4 changes: 4 additions & 0 deletions app/cetirun-operator/api/v1alpha1/agent_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -675,6 +675,10 @@ type AIGatewayCatalog struct {
// While the Gateway blocks requests for unpriced models, they leave out
// the models it would refuse.
SharedModels []AIGatewayCatalogModel `json:"sharedModels"`
// DecisionModels are the shared decision models, such as
// Microsoft-Decision-1, that a Team router's jev classifier may use.
// Agents are not configured with them.
DecisionModels []string `json:"decisionModels,omitempty"`
// GitHubCopilot reports whether the deployment gives Agents a GitHub
// Copilot proxy. Without it, an Agent's GitHub Copilot switch adds no
// models.
Expand Down
7 changes: 5 additions & 2 deletions app/cetirun-operator/api/v1alpha1/team_model_router_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,9 @@ func TestTeamModelRouterSchema(t *testing.T) {
for _, value := range classifier.Properties["type"].Enum {
types = append(types, strings.Trim(string(value.Raw), `"`))
}
// LiteLLM's licence-limited classifier types are not offered.
if !slices.Equal(types, []string{ModelRouterClassifierHeuristic, ModelRouterClassifierLLM}) {
// LiteLLM's licence-limited classifier types are not offered; jev,
// with LiteLLM's own instructions, is not limited.
if !slices.Equal(types, []string{ModelRouterClassifierHeuristic, ModelRouterClassifierLLM, ModelRouterClassifierJev}) {
t.Fatalf("%s: classifier types = %v", path, types)
}
if len(classifier.XValidations) != 1 {
Expand All @@ -111,7 +112,9 @@ func TestTeamModelRouterSchema(t *testing.T) {
}{
{map[string]any{"type": "heuristic"}, true},
{map[string]any{"type": "llm", "model": "small-model"}, true},
{map[string]any{"type": "jev", "model": "decision-model"}, true},
{map[string]any{"type": "llm"}, false},
{map[string]any{"type": "jev"}, false},
{map[string]any{"type": "heuristic", "model": "small-model"}, false},
{map[string]any{"model": "small-model"}, false},
{map[string]any{}, true},
Expand Down
Loading
Loading