65 / MODEL GATEWAY · MODEL ROUTING / MODEL ROUTER
65 / PRODUCTION / PROVIDER ABSTRACTION · ENFORCEMENT · ROUTING · HEALTH

MODEL GATEWAY
& ROUTING.

Model Gateway — единая production-граница между приложением и моделями/провайдерами. Он нормализует API, применяет policy, quotas, credentials, observability, retries/fallbacks и выдаёт стабильный внутренний contract. Model Routing выбирает конкретный model/provider/serving endpoint для данного запроса по capability, policy, risk, cost, latency, availability и quality requirements.

Главный принцип: бизнес-логика не должна быть пришита к одному provider SDK. Приложение говорит: «мне нужна capability с такими constraints», а gateway/router выбирает допустимый target и обеспечивает единые правила execution.
00. ARCHITECTURAL STATUS

MODEL GATEWAY НУЖЕН ПО УМОЛЧАНИЮ, КАК ТОЛЬКО ЕСТЬ БОЛЬШЕ ОДНОЙ МОДЕЛИ ИЛИ PRODUCTION ENFORCEMENT

Даже при одном provider gateway полезен как стабильный seam: credentials, timeouts, budgets, tracing, request normalization, policy и model metadata находятся в одном месте. Multi-provider routing можно добавить позже без переписывания core modules.
TYPEPRODUCTIONModel access / enforcement infrastructure.
DEFAULTONМинимальный gateway layer включён всегда.
ENABLE WHENMODEL CALL EXISTSRouting sophistication grows with model fleet.
SEPARATE COMPONENTYESLogical access boundary.
LIVES INMODEL ROUTERRuntime module R09.
COMPLEXITYLOW → HIGHWrapper first; dynamic routing later.
IMPLEMENT: YES
Минимум 80% ценности: provider-agnostic request/response contract, model registry/capability metadata, one gateway client, credentials hidden host-side, policy/data-residency enforcement, timeouts/retry/fallback, quotas/budgets, cost/tokens/latency tracing, health-aware target selection, exact model/version in provenance and a deterministic route decision record. Не нужен LLM-router для большинства cases.
01A. ARCHITECTURE BOUNDARIES & OPERATIONS

EXPLICIT SYSTEM CONTRACT

A. BOUNDARY WITH NEIGHBORS

№34 Model Escalation владеет cognitive policy: когда дешёвой модели недостаточно и нужен более сильный tier; №65 исполняет route к допустимой model/provider capacity. №04 Routing шире и выбирает исполнителя/agent/tool path; №65 routing ограничен model targets. №63 Fallbacks отвечает на availability failures; gateway является enforcement point для model fallback. №64 Limits/Budgets владеет counters/ceilings; gateway проверяет их перед model execution. №51 Permissions/Secrets владеет credentials/scopes; gateway использует host-side provider credentials. №70 Model Serving владеет inference servers, batching and runtime capacity; gateway выбирает serving endpoint, но не управляет kernel-level inference internals.

B. PREREQUISITES / CROSS-REFERENCES

Prerequisites: №04 Routing, №34 Model Escalation, №46 Observability, №48 Guardrails, №50 Contracts, №51 Permissions & Secrets, №63 Resilience, №64 Limits/Budgets. Forward references: №70 Model Serving, №71 Local LLM, №72 Quantization, №73 Multimodal AI, №76 Governance.

C. PLANE PLACEMENT

REQUEST-TIME: YES — every model call passes through gateway/router. CONTROL PLANE: model registry, capabilities, route policies, credentials refs, price/latency classes, region/data restrictions. DATA PLANE: normalized requests/responses, route decisions, usage/health signals. OFFLINE: routing evals, model comparisons, canary/shadow, cost-quality calibration.

D. FAILURE & OPERATIONS CONTRACT

Success: request routed to an eligible target and returns normalized output within deadline/budget/policy. Retryable: transient provider/endpoint failure. Permanent: no eligible model, unsupported capability, policy/data-residency conflict, invalid request. Idempotency: model generation itself is usually not side-effecting; tool calls emitted by model are separate operations. Persist/trace: route decision, candidate targets, selected model/provider/version, latency/tokens/cost, fallback/escalation reason. Security: model cannot choose provider credential or bypass route policy.

E. WHAT THIS TOPIC DOES NOT OWN

№65 не владеет task decomposition, agent routing generally, model training, serving internals, cognitive escalation criteria or user-facing quality verification. Она владеет STANDARDIZED MODEL ACCESS AND ENFORCED SELECTION OF ELIGIBLE MODEL/PROVIDER/SERVING TARGETS.

01. WHY A GATEWAY

НЕ РАЗМАЗЫВАТЬ PROVIDER SDK ПО ВСЕЙ СИСТЕМЕ

WITHOUT GATEWAY

R01 calls SDK A. R06 calls SDK B. Tool wrapper embeds provider C. Each has own retries, auth and response format.

GATEWAY

One internal contract, one enforcement boundary, one registry and routing policy.

PROVIDERS / LOCAL

Cloud A, Cloud B, local vLLM-like endpoint, specialized multimodal model.

Главная ценность gateway — decoupling + centralized enforcement. Multi-provider cost optimization — уже второй слой.
02. NORMALIZED MODEL CONTRACT

ВНУТРЕННИЙ API ДОЛЖЕН БЫТЬ СТАБИЛЬНЕЕ, ЧЕМ PROVIDER APIs

{
  "request_id": "MR-...",
  "task_class": "RESEARCH_SYNTHESIS",
  "messages": [...],
  "input_artifacts": [...],
  "required": {
    "modalities": ["text"],
    "structured_output": "answer.v3",
    "tool_calling": true,
    "min_context_tokens": 64000
  },
  "constraints": {
    "deadline_ms": 12000,
    "max_cost": "...",
    "data_region": "EU",
    "risk": "MEDIUM",
    "preferred_tier": "STANDARD"
  },
  "routing": {
    "policy": "route-v8",
    "allow_fallback": true
  }
}
NORMALIZED RESPONSE

Provider details do not leak upward

  • output / structured payload;
  • finish reason;
  • tool calls in one internal schema;
  • input/output token usage;
  • latency;
  • provider/model/version;
  • route/fallback metadata;
  • safety/provider flags normalized;
  • raw provider response only behind debug/artifact ref if needed.
03. PROVIDER ADAPTERS

АДАПТЕР ПЕРЕВОДИТ INTERNAL CONTRACT В КОНКРЕТНЫЙ API

REQUEST MAP

Internal → provider

Messages, tools, JSON schema, multimodal inputs, max tokens, reasoning controls.

AUTH

Credential injection

Provider secret resolved host-side from secure secret store.

ERROR MAP

Provider → typed errors

429, timeout, invalid schema, unsupported capability mapped to common reason codes.

USAGE MAP

Normalized accounting

Tokens, cached tokens, audio/image units, latency and provider-specific billing units.

TOOL MAP

Function calling

Provider tool-call shape normalized into internal tool request contract.

STREAM MAP

Streaming events

Text deltas, tool-call deltas, usage/final events converted to stable internal stream.

Provider adapter should be thin. Cognitive logic, prompt architecture and tool semantics should remain outside adapters.
04. MODEL REGISTRY

ROUTER НЕ МОЖЕТ ВЫБИРАТЬ МОДЕЛЬ, ЕСЛИ НЕ ЗНАЕТ ЕЁ CAPABILITIES И CONSTRAINTS

{
  "model_ref": "model://providerA/model-x",
  "provider": "providerA",
  "model_id": "model-x",
  "status": "ACTIVE",
  "capabilities": {
    "text": true,
    "vision": true,
    "audio": false,
    "tool_calling": true,
    "structured_output": true,
    "context_tokens": 128000
  },
  "classes": {
    "quality_tier": "HIGH",
    "latency_tier": "MEDIUM",
    "cost_tier": "HIGH"
  },
  "deployment": {
    "regions": ["EU", "US"],
    "data_policy": ["CONFIDENTIAL_OK"]
  },
  "health_ref": "health://...",
  "pricing_version": "2026-08-31"
}
REGISTRY FIELDS

Enough for deterministic eligibility

  • provider/model/endpoint;
  • active/deprecated status;
  • modality support;
  • tool/structured-output support;
  • context/output limits;
  • quality/latency/cost tiers;
  • region/data handling policy;
  • health/capacity;
  • pricing/version metadata;
  • eval score refs per task segment.
Registry может быть простой YAML/JSON/Postgres table. Не нужен отдельный «model discovery agent».
05. ELIGIBILITY FIRST, RANKING SECOND

СНАЧАЛА УБРАТЬ НЕДОПУСТИМЫЕ МОДЕЛИ, ПОТОМ ВЫБИРАТЬ ЛУЧШУЮ

ALL TARGETSRegistry candidates.
CAPABILITY FILTERModality/tools/context/schema.
POLICY FILTERRegion/data/risk/provider allowlist.
HEALTH FILTERActive, breaker state, capacity.
BUDGET FILTEREstimated cost/rate/concurrency fits.
RANKQuality/latency/cost/affinity.
SELECTRecord decision + fallback list.
Routing score never должен «компенсировать» hard policy mismatch. Неподходящий region/provider не становится допустимым только потому, что он дешевле.
06. ROUTING INPUTS

MODEL SELECTION ДОЛЖЕН СМОТРЕТЬ НА TASK + CONSTRAINTS + SYSTEM STATE

TASK

Capability need

Classification, extraction, code, research synthesis, vision, multimodal, long-context.

QUALITY

Required floor

Task/risk segment evals define which models are sufficient.

LATENCY

Deadline/SLA

Interactive 2 s vs offline 5 min can route differently.

COST

Budget

Estimated prompt/output/tool behavior must fit resource budget.

POLICY

Data/risk/provider

Region, confidentiality, tenant allowlist, regulated workload.

HEALTH

Availability

Breaker, recent error/latency, capacity headroom.

CONTEXT

Size / modality

Required context window and supported media.

AFFINITY

Operational preference

Warm local model, cached prefix, tenant deployment, session stickiness where useful.

07. ROUTING DECISION CONTRACT

ВЫБОР МОДЕЛИ ДОЛЖЕН БЫТЬ AUDITABLE

{
  "route_id": "ROUTE-...",
  "request_id": "MR-...",
  "policy_version": "route-v8",
  "task_class": "RESEARCH_SYNTHESIS",
  "required": {
    "min_quality_tier": "STANDARD",
    "tool_calling": true,
    "context_tokens": 64000
  },
  "eligible": [
    "model://A/x",
    "model://B/y"
  ],
  "excluded": [
    {
      "model": "model://C/z",
      "reason": "DATA_REGION_MISMATCH"
    }
  ],
  "selected": "model://B/y",
  "selection_reason": "BEST_SCORE",
  "fallback_order": ["model://A/x"],
  "score": {
    "quality": 0.92,
    "latency": 0.78,
    "cost": 0.71,
    "health": 1.0
  }
}
WHY RECORD DECISION

Routing becomes explainable

  • debug unexpected model use;
  • compare quality/cost by route policy;
  • prove policy/region compliance;
  • replay eval with same candidate set;
  • measure fallback/escalation behavior;
  • attribute incident to router vs model.
08. STATIC ROUTING

СТАТИЧЕСКАЯ ТАБЛИЦА — ПРАВИЛЬНЫЙ MVP

task_class -> preferred target

CLASSIFY_SMALL
  -> local-small

EXTRACT_STRUCTURED
  -> cloud-fast-json

GENERAL_ASSIST
  -> standard-model

RESEARCH_SYNTHESIS
  -> strong-model

VISION_PARSE
  -> multimodal-model

CODE_REVIEW
  -> code-capable-model

fallback:
  preferred unavailable
  -> compatible alternate
Начинайте с explicit deterministic mapping. Dynamic scoring добавляется только когда evals показывают, что static policy оставляет заметные деньги/latency/quality на столе.
09. POLICY-BASED ROUTING

RULES ДОЛЖНЫ БЫТЬ ЧИТАЕМЫМИ И TESTABLE

CAPABILITY RULE

Must support

requires_vision = true → vision models only.

DATA RULE

Where data may go

confidential → approved local/private providers.

RISK RULE

Quality floor

risk=HIGH → models with verified score ≥ threshold + stronger verification.

LATENCY RULE

Interactive class

deadline < 2s → fast tier with sufficient quality.

COST RULE

Budget-aware

estimated cost > remaining → cheaper eligible model or degrade.

HEALTH RULE

No dead targets

breaker=open / headroom low → remove or strongly penalize target.

Rules должны быть testable offline against routing fixtures. Не прятать критические constraints в giant prompt для «router model».
10. SCORE-BASED ROUTING

ПОСЛЕ HARD FILTERS МОЖНО РАНЖИРОВАТЬ ДОПУСТИМЫЕ TARGETS

score(model, request) =
    0.45 * quality_fit
  + 0.20 * latency_fit
  + 0.15 * cost_fit
  + 0.10 * health
  + 0.10 * affinity

subject to HARD constraints:
  capability == satisfied
  policy == allowed
  context >= required
  budget == fits
  region == allowed
  breaker != OPEN
DON'T WORSHIP WEIGHTS

Weights are policy, not science

Weights должны калиброваться через offline evals and production metrics.

Для большинства систем полезнее иметь 3–5 явных route classes, чем один «магический» universal score.

11. MODEL ESCALATION

№34 ОПРЕДЕЛЯЕТ «НУЖНА ЛИ БОЛЕЕ СИЛЬНАЯ МОДЕЛЬ», №65 НАХОДИТ КУДА ИМЕННО ИДТИ

STANDARD ROUTE

Task starts on cheap sufficient tier.

№34 ESCALATION SIGNAL

Verifier failure, uncertainty, capability mismatch, high risk.

№65 GATEWAY

Select eligible stronger target under policy, health and budget.

Не смешивать escalation trigger и gateway target selection. Это позволяет отдельно измерять: «правильно ли решили усилиться?» и «правильно ли выбрали model endpoint?»
12. FALLBACK ROUTING

AVAILABILITY FALLBACK — ДРУГОЙ СИГНАЛ, ЧЕМ QUALITY ESCALATION

SCENARIO
TRIGGER
ACTION
QUALITY
BUDGET
OWNER
ESCALATION
quality/uncertainty
stronger eligible tier
higher target
may cost more
№34 + №65
FALLBACK
outage/429/health
compatible alternate
must meet floor
must fit
№63 + №65
DEGRADE
budget/capacity
cheaper/reduced capability
explicitly lower
protect cap
№64 + №65
Все три path changes должны иметь разные reason codes. Иначе невозможно понять, почему система использовала конкретную модель.
13. HEALTH-AWARE ROUTING

MODEL ROUTER ДОЛЖЕН ЗНАТЬ НЕ ТОЛЬКО «MODEL ACTIVE», НО И RECENT HEALTH

ERROR RATE

Provider health

Recent timeout/5xx/429 by endpoint/model/region.

P95 LATENCY

Slow is unhealthy too

Route away when deadline cannot be met.

BREAKER

Open/half-open

№63 breaker state is a hard/strong routing signal.

HEADROOM

Rate/concurrency

№64 remaining RPM/TPM/concurrency reduces overload routing.

Не делать роутинг purely reactive after provider returns 429. If headroom known, gateway can proactively spread traffic.
14. HEALTH MODEL

STATUS = ACTIVE НЕДОСТАТОЧНО

{
  "target": "model://providerA/x/eu1",
  "status": "DEGRADED",
  "window": "5m",
  "success_rate": 0.94,
  "p50_latency_ms": 820,
  "p95_latency_ms": 4100,
  "rate_limit_headroom": 0.18,
  "concurrency_headroom": 0.31,
  "breaker": "CLOSED",
  "last_error": "RATE_LIMITED",
  "updated_at": "..."
}
HEALTH CLASSES

Operational simplification

  • HEALTHY
  • DEGRADED
  • SATURATED
  • UNAVAILABLE
  • UNKNOWN

Routing can filter/penalize by class while retaining raw metrics for observability.

15. PROVIDER QUOTAS & COSTS

GATEWAY — ЕСТЕСТВЕННЫЙ ENFORCEMENT POINT ДЛЯ MODEL RESOURCE CONTROL

ESTIMATE TOKENSPrompt/context + max output.
№64 CHECKTask/tenant/provider budget and RPM/TPM.
ROUTEEligible target with capacity.
RESERVEProvider/model usage if needed.
EXECUTENormalized provider call.
COMMIT USAGEActual tokens/cost/latency.
Router should not «discover» that provider quota exhausted only from failures. Budget/headroom is part of route context.
16. DATA RESIDENCY & PRIVACY ROUTING

НЕ КАЖДАЯ МОДЕЛЬ МОЖЕТ ПОЛУЧИТЬ КАЖДЫЕ ДАННЫЕ

REGION

Where processed

EU-only, on-prem-only, tenant-specific deployment.

DATA CLASS

Sensitivity

Public, internal, confidential, regulated classes map to approved targets.

RETENTION

Provider handling

Route only to endpoints whose data handling matches policy.

LOCAL ROUTE

Private fallback

Local/self-hosted target may be required for restricted data even if cloud model is stronger.

Data policy is a hard eligibility filter. A more accurate model cannot win routing if it is not allowed to process the input.
17. LOCAL + CLOUD HYBRID

ЛОКАЛЬНАЯ МОДЕЛЬ — ЕЩЁ ОДИН TARGET В MODEL FLEET

LOCAL FAST

Cheap/private

Classification, extraction, simple rewriting, offline/private workloads.

CLOUD STRONG

High capability

Hard reasoning, complex multimodal, long-context when policy allows.

ROUTER

Unified selection

Same request contract; local serving differences hidden behind adapter/gateway.

№71 Local LLM later раскрывает self-hosting trade-offs. Architecturally local endpoint should look like a model target, not a separate parallel universe with different core contracts.
18. CONTEXT WINDOW ROUTING

MODEL CAPABILITY — ЭТО НЕ ТОЛЬКО QUALITY SCORE

ConstraintRoute consequence
Input + tools + output need 90k tokensModels below required context are ineligible.
Need native visionText-only targets are ineligible unless upstream preprocessing changes task.
Need structured JSON schemaPrefer/require targets with tested structured-output compliance.
Need tool callingTarget must support compatible tool-call contract or use alternate orchestration pattern.
Need realtime streamingRoute to endpoints with streaming/realtime capability and latency profile.
Router should use required capability, not generic brand/model rank.
19. TASK-SPECIFIC EVAL SCORES

«ЛУЧШАЯ МОДЕЛЬ» НЕ СУЩЕСТВУЕТ БЕЗ TASK SEGMENT

EXTRACTION

Model A

May beat larger model on strict schema adherence and speed.

CODE

Model B

Different model may lead on executable correctness.

RESEARCH

Model C

Stronger synthesis/evidence use may justify higher cost.

VISION

Model D

Specialized multimodal target may be required.

Routing registry should reference eval results by task segment. №47 Evals measures capability; №65 consumes those measurements as routing metadata.
20. ROUTING EVALS

ОЦЕНИВАТЬ НЕ ТОЛЬКО MODELS, НО И САМУ ROUTING POLICY

QUALITY

Pass rate

Does policy choose models that meet quality floor by segment?

COST

Expected spend

Cost per successful task vs always-strong baseline.

LATENCY

Deadline success

p50/p95 and SLA compliance by route.

VIOLATIONS

Hard errors

Capability/policy/region/budget-invalid routes. Target 0.

ESC

Escalation efficiency

How often cheap-first works vs requires expensive escalation.

FB

Fallback quality

Availability recovery without dropping below floor.

REGRET

Routing regret

Difference vs best eligible target known from offline eval.

STABILITY

Route churn

Avoid oscillating targets due to noisy short-window metrics.

21. SHADOW & CANARY ROUTING

НОВУЮ MODEL/POLICY ЛУЧШЕ СРАВНИТЬ ДО ПОЛНОГО SWITCH

SHADOW

No user effect

Selected production request also evaluated on candidate target offline/async; compare quality/cost/latency.

CANARY

Small production share

1–5% eligible traffic goes to new model/policy with rollback threshold.

PROMOTE

Evidence-based

Increase share only after eval/production metrics remain acceptable.

Shadow can double model cost, so №64 budget applies. Использовать sampling, not «mirror every call forever».
22. STICKINESS & AFFINITY

ИНогда СТАБИЛЬНОСТЬ TARGET ВАЖНЕЕ МИКРО-ОПТИМИЗАЦИИ

SESSION

Conversation consistency

Keep same compatible model within session when behavior continuity matters.

PREFIX CACHE

Operational affinity

Provider/model with warm prefix/cache may reduce latency/cost if policy supports it.

LOCALITY

Region/tenant deployment

Prefer nearby/private endpoint to reduce latency and data movement.

Affinity is a soft score after hard eligibility. It must not trap traffic on unhealthy or underperforming target.
23. MODEL VERSION CHANGE

MODEL ID МОЖЕТ ОСТАТЬСЯ ТЕМ ЖЕ, А BEHAVIOR — ИЗМЕНИТЬСЯ

PIN

Exact version if available

Prefer explicit version/revision for reproducibility when provider supports it.

DETECT

Behavior drift

Continuous evals detect quality/schema/tool changes after provider updates.

RECORD

Provenance

Store actual provider/model/version metadata returned at execution.

ROLLBACK

Route policy

Disable/deprioritize target if regression exceeds threshold.

Gateway centralization makes model drift manageable because version/metrics capture happens once, not in every feature team.
24. TOOL CALLING THROUGH GATEWAY

MODEL МОЖЕТ ПРЕДЛОЖИТЬ TOOL CALL, НО GATEWAY НЕ ИСПОЛНЯЕТ SIDE EFFECT КАК МАГИЮ

MODEL REQUESTTools exposed as schemas.
PROVIDER MODELReturns tool-call proposal.
NORMALIZEProvider shape → internal tool request.
R07 TOOL ENGINEValidate policy/permissions/args/approval.
EXECUTEActual tool side effect outside model gateway.
Gateway normalizes tool-call syntax. №12 Tools/Function Calling + R07 Tool Engine own actual tool semantics and execution.
25. STRUCTURED OUTPUTS

PROVIDER-SPECIFIC JSON FEATURES ДОЛЖНЫ СХОДИТЬСЯ В ОДИН INTERNAL CONTRACT

REQUEST

Internal schema

Gateway accepts canonical JSON Schema / contract ref from №50.

ADAPTER

Translate feature

Maps to provider-native structured output / constrained decoding / tool trick as supported.

VALIDATE

Host-side final check

Never trust provider guarantee alone; validate normalized result against canonical schema.

Unsupported target is either ineligible or routed through an explicitly different fallback path. Нельзя silently drop schema requirement.
26. STREAMING

STREAM НУЖНО НОРМАЛИЗОВАТЬ ТАК ЖЕ, КАК FINAL RESPONSE

Internal eventMeaning
TEXT_DELTAIncremental assistant text.
TOOL_CALL_DELTAIncremental structured tool proposal fields.
USAGE_UPDATEOptional provider usage/cost signal.
ROUTE_METADATASelected target/fallback/escalation metadata.
FINALNormalized final result + finish reason.
ERRORTyped error; retry/fallback may occur depending on stage.
Mid-stream failure complicates fallback: нельзя безопасно склеить текст двух моделей без explicit orchestration. Часто correct behavior — abort stream and restart with clear state, or fail.
27. SECURITY

MODEL GATEWAY — CRITICAL TRUST BOUNDARY

SECRETS

Host-side only

Provider API keys never placed in prompt/model-visible config.

TENANT

Scope derived

Caller cannot spoof route to another tenant's deployment/credential.

DATA POLICY

Hard filter

Sensitive payload only to approved regions/providers/endpoints.

LOGGING

Minimize content

Trace metadata without dumping sensitive prompts/responses by default.

MODEL INPUT

Untrusted content

Gateway transport does not elevate retrieved/user text into trusted instructions.

ALLOWLIST

Registered models only

Model IDs/endpoints are selected from registry, not arbitrary user/model-provided URLs.

POLICY VERSION

Auditable

Every route decision references policy/version and identity context.

FALLBACK

No policy downgrade

Availability fallback cannot widen region/data/permission constraints.

28. OBSERVABILITY

МОДЕЛЬ НУЖНО ВИДЕТЬ КАК DEPENDENCY + ECONOMIC RESOURCE + QUALITY COMPONENT

REQ

Requests

Calls by model/provider/task/tenant/route policy.

LAT

Latency

p50/p95/p99 by target and task class.

TOK

Tokens

Input/output/cached tokens or equivalent units.

COST

Cost

Estimated/actual spend by route/task/tenant.

ERR

Error rate

429/timeout/5xx/schema/tool-call failures.

ESC

Escalation

Cheap-first → strong model transitions.

FB

Fallback

Availability route changes and quality outcome.

Q

Quality by target

Verification/eval pass rates per task segment.

29. FAILURE MODES

КАК MODEL GATEWAY ПРЕВРАЩАЕТСЯ В НОВЫЙ MONOLITHIC GOD SERVICE

SDK EVERYWHERE
Features depend on provider-specific request/response semantics.
ONE INTERNAL CONTRACT
ROUTER = LLM PROMPT
Hard policy/cost/region decisions become nondeterministic.
RULES FIRST
QUALITY ONLY
Router always chooses strongest/most expensive model.
SUFFICIENT QUALITY + COST/LATENCY
COST ONLY
Cheap model repeatedly fails and causes escalation/retry cost.
END-TO-END SUCCESS COST
NO HARD ELIGIBILITY
Scoring sends restricted data to forbidden provider.
FILTER THEN RANK
NO VERSION RECORD
Model drift/regression cannot be attributed.
PROVENANCE
FALLBACK = ANY MODEL
Availability recovery violates schema/quality/policy.
COMPATIBLE TESTED TARGETS
GATEWAY EXECUTES TOOLS
Provider tool syntax bypasses R07 permissions/guardrails.
NORMALIZE, THEN TOOL ENGINE
DYNAMIC TOO EARLY
Complex scoring before stable eval baselines.
STATIC ROUTES FIRST
30. ROUTING METRICS

ЧТО ИЗМЕРЯТЬ

PASS

Quality Pass Rate

Verified/eval success by routed model and task segment.

$

Cost per Success

Total model cost including escalation/fallback divided by successful tasks.

P95

Latency

End-to-end model-stage latency by route policy.

ESC

Escalation Rate

Share of cheap-first calls requiring stronger model.

FB

Fallback Rate

Availability-driven alternate target usage.

REG

Route Violations

Capability/policy/region-invalid selection. Target 0.

REGRET

Routing Regret

Quality/cost gap vs best eligible target under offline oracle.

CHURN

Route Churn

Unnecessary target oscillation driven by noisy metrics.

31. ROUTING TESTS

ROUTER НУЖНО ТЕСТИРОВАТЬ КАК POLICY ENGINE

CAP

Capability

Vision/tool/context requirements exclude incompatible targets.

POL

Policy

Restricted data never routes to disallowed provider/region.

BUD

Budget

Expensive target rejected/degraded when reservation doesn't fit.

HLT

Health

Open breaker removes target; recovery returns it gradually.

FB

Fallback

Primary outage selects only compatible tested alternates.

ESC

Escalation

Stronger tier selection follows escalation signal and hard filters.

VER

Version

Registry/model version changes create expected route/canary behavior.

DET

Determinism

Same inputs/control-plane state produce same route decision.

32. MVP IMPLEMENTATION

ONE PYTHON MODULE + REGISTRY + ADAPTERS УЖЕ МОГУТ БЫТЬ ПРАВИЛЬНЫМ GATEWAY

model_gateway/
├── contracts.py
├── registry.py
├── router.py
├── policies.py
├── health.py
├── usage.py
├── adapters/
│   ├── provider_a.py
│   ├── provider_b.py
│   └── local.py
└── tests/

route(request, ctx):
  candidates = registry.active()

  candidates = filter_capability(
    candidates, request.required
  )

  candidates = filter_policy(
    candidates, ctx.tenant, ctx.data_class
  )

  candidates = filter_health(candidates)

  candidates = filter_budget(
    candidates, ctx.remaining_budget
  )

  selected = static_or_score(candidates)

  return RouteDecision(
    selected=selected,
    fallback_order=...
  )

generate(request):
  decision = route(...)
  reserve_usage(...)
  call adapter
  normalize response
  commit usage
  record route + provenance
  return response
80% VALUE MVP

Boring gateway first

  • One internal request/response contract.
  • 2–6 explicit model registry entries.
  • Thin provider/local adapters.
  • Static task-class routing.
  • Capability + region/data policy filters.
  • №64 budget/rate check.
  • №63 retry/fallback wrapper.
  • Health/breaker signal.
  • Normalized token/cost/latency metrics.
  • Exact model/provider/version provenance.
  • Offline routing fixtures/evals.

No LLM router, no reinforcement-learning router, no complex bandit required initially.

33. WHEN TO UPGRADE

ДИНАМИКА ПОЯВЛЯЕТСЯ ПОСЛЕ СТАБИЛЬНОГО STATIC BASELINE

SignalPotential upgrade
Many models/providers with overlapping capabilitiesScore-based routing by eval/cost/latency/health.
Rapid provider price/latency variationDynamic cost/health metadata and short-lived route weights.
High traffic / meaningful route regretContextual bandit/online optimization after strong guardrails and offline eval.
Local model clusterServing-aware capacity routing integrated with №70.
Data residency per tenant/regionRegion-aware deployment registry and hard route constraints.
Many model versionsCanary/shadow automation and continuous routing eval pipeline.
34. PRACTICAL DECISION

СТОИТ ЛИ ДЕЛАТЬ ОТДЕЛЬНЫЙ КОМПОНЕНТ?

ВопросОтвет
Стоит ли реализовывать?Да. Даже one-provider system выигрывает от стабильного gateway seam; routing complexity может оставаться минимальной.
Separate Component?YES логически. На старте может быть module/library внутри R09 Model Router, не отдельный network service.
Минимум 80% ценности?Internal contract, registry, static routing, capability/policy filter, budget/health checks, adapters, fallback, metrics, provenance.
Когда overkill?LLM-router/bandit/real-time dynamic scoring для трёх моделей без стабильных eval baselines.
Trigger?Minimum gateway ON for any production model call; advanced routing once there are multiple eligible targets and meaningful trade-offs.
Как измерить uplift?Cost per successful task, p95 latency, quality pass rate, route violations, provider outage impact, escalation efficiency, model-switch migration effort.
Можно ли rule/tool/code вместо LLM-agent?Да, и это default. Hard constraints and most routing are deterministic. LLM-based routing is optional only for semantic task classification after strict outer filters.
35. DESIGN RULES

ПРАВИЛА ДЛЯ РЕАЛЬНОЙ СИСТЕМЫ

RULE 01

One model boundary

Core modules call gateway, not provider SDKs directly.

RULE 02

Filter before rank

Capability/policy/region/budget are hard eligibility constraints.

RULE 03

Static before dynamic

Explicit task-class mapping is the right first router.

RULE 04

Escalation ≠ fallback

Quality-driven strengthening and outage-driven alternate routing have different owners/reasons.

RULE 05

Route by task segment

No universal «best model» without capability/eval context.

RULE 06

Record exact target

Provider/model/version/endpoint belongs in route decision and provenance.

RULE 07

Health and budget are live inputs

Don't route purely from static model rankings.

RULE 08

Tools stay outside gateway

Normalize model tool proposals, execute only through R07.

RULE 09

Evaluate the router

Measure policy quality/cost/latency, not only individual model benchmarks.

36. FINAL MAP

ONE STABLE MODEL ACCESS LAYER, MANY POSSIBLE TARGETS

R01 / R02 / R03 / R06 / R08
        ↓
MODEL REQUEST CONTRACT
  task_class
  messages/context
  modality
  tools
  structured output
  deadline
  risk
  data class / region
  budget
        ↓
R09 MODEL GATEWAY
        ↓
MODEL REGISTRY
  provider
  model
  endpoint
  capabilities
  context
  modalities
  quality tier
  cost tier
  latency tier
  region / policy
  health
  capacity
        ↓
ELIGIBILITY FILTER
  capability
  policy
  data residency
  context size
  structured output
  tool support
  breaker state
  rate / quota / budget
        ↓
ROUTING
  static task map
  OR
  bounded score among eligible targets
        ↓
ROUTE DECISION
  selected
  excluded + reasons
  fallback order
  policy version
        ↓
PROVIDER / LOCAL ADAPTER
        ↓
MODEL ENDPOINT
        ↓
NORMALIZE
  output
  tool proposal
  usage
  finish reason
  provider flags
        ↓
VALIDATE CONTRACT
        ↓
RETURN TO CALLER

CROSS-CUTTING:

№34
  decides when stronger model is worth/needed

№63
  retry / breaker / availability fallback

№64
  rate / quota / budget / reservation

№51
  provider credentials and secret handling

№46
  traces / latency / tokens / errors

№61
  exact model/version lineage

№70
  serving capacity and inference runtime

KEY DISTINCTIONS:

GATEWAY
  = HOW THE SYSTEM TALKS TO MODELS

MODEL ROUTING
  = WHICH ELIGIBLE TARGET GETS THIS CALL

MODEL ESCALATION
  = WHETHER THE TASK NEEDS A STRONGER TIER

FALLBACK
  = WHAT TO DO WHEN THE CHOSEN TARGET IS UNAVAILABLE

CORE PRINCIPLE:

THE APPLICATION SHOULD NOT SAY:

"CALL PROVIDER X MODEL Y
WITH SDK Z."

IT SHOULD SAY:

"I NEED THIS MODEL CAPABILITY,
UNDER THESE QUALITY,
LATENCY, COST, POLICY
AND DATA CONSTRAINTS."

THE GATEWAY THEN CHOOSES
AN ELIGIBLE TARGET,
ENFORCES THE RULES,
RECORDS THE DECISION,
AND HIDES PROVIDER-SPECIFIC
MECHANICS FROM THE REST
OF THE SYSTEM.

ECC RETROFIT / PRACTICAL HARNESS INTEGRATION

A. Related ECC ideas. Context-as-cache, scoped memory, lifecycle hooks, selective capabilities, feature flags, deterministic enforcement, provider-neutral adapters and eval-gated learning are applied only where relevant to №65 Model Gateway & Model Routing.

B–E. Existing boundary and placement. The existing conceptual boundary, class PRODUCTION, default ON and owner Model Router remain authoritative. Runtime/control/data/offline placement is unchanged; durable state stays outside model context.

F–H. Hooks and contracts. Use bounded PRE_MODEL/POST_MODEL, PRE_TOOL/POST_TOOL, CHECKPOINT and TASK_COMPLETED events as applicable. Illustrative fields and canonical contracts are defined in NEW_CONTRACTS_SPEC.md; no universal schema is implied.

I–J. Security and evaluation. Host-side schema, permission, secret, budget, idempotency and audit checks take precedence over LLM output. Optional mechanisms require a feature flag and WITH/WITHOUT ablation; measure quality, acceptance, correction, latency, cost, escalations and severe errors.

K–L. Task profiles and cross-references. A TaskProfile selects the relevant skill, tool/context slice, memory scope and enforcement profile independently from FAST/STANDARD/DEEP. See cross-reference map, hook spec and ablation plan. Provider adapters remain outside the core.