[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AVR7P45JRE4VC8W51GG82F":3,"skill-same:01M7AVR7P45JRE4VC8W51GG82F":61},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":14,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":6,"ownerDescription":29,"updatedAt":30,"install":31,"resources":44},"01M7AVR7P45JRE4VC8W51GG82F","dynamic-model-router",null,"Architect, configure, and operate multi-provider dynamic LLM routing pipelines with sub-5ms heuristic complexity classification, declarative model matrices, and automated failover. Do not use for static single-model prompts or offline batch dataset labeling.","SpectreDeath\u002FBrain-Harness","SpectreDeath","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F207463416?v=4","01M7AVGR1D4X8ADT47APKGVH2Z","JL","01M7AVGR2HSGD23BA5DBTJJTVN",0,"MIT","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fdynamic-model-router\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: dynamic-model-router\ndescription: Architect, configure, and operate multi-provider dynamic LLM routing pipelines with sub-5ms heuristic complexity classification, declarative model matrices, and automated failover. Do not use for static single-model prompts or offline batch dataset labeling.\n---\n\n# Dynamic Model Router: Multi-Provider Switching & Resilient Failover Engine\n\n`dynamic-model-router` is the cognitive and architectural engine for designing, deploying, and operating multi-provider AI model routing systems. Synthesized from Chidiebere Njoku's foundational literature (*How to Build AI Applications That Switch Models Automatically*, freeCodeCamp, 2026) and grounded in the Knowledge Vault ([ki_njoku_dynamic_model_routing](..\u002F..\u002F..\u002F.harness\u002Fknowledge\u002Fki_njoku_dynamic_model_routing\u002Fsummary.md)), this skill operationalizes dynamic model switching to eliminate single-point-of-failure API outages, curb token cost inflation, and enforce strict execution SLAs.\n\nRelying on a single monolithic frontier model for every incoming request introduces severe production risks: upstream API downtime freezes end-user workflows, expensive reasoning models are wasted on trivial formatting tasks, and lightweight models fail on complex multi-step reasoning. `dynamic-model-router` enforces a decoupled 3-tier lifecycle: deterministic offline complexity profiling, declarative model matrix resolution, and resilient multi-provider failover.\n\nEvery dynamic model routing workflow executes this 5-stage progression:\n\n```\n[1. Offline Complexity Profiling] → [2. Declarative Matrix Resolution] → [3. Strict-Timeout Encasement] → [4. Automated Failover Execution] → [5. Schema Normalization & Telemetry]\n```\n\nSee [CARD.md](CARD.md) for the companion summary card, stage reference matrix, and verification checklist.\nConsult [..\u002Fcompute-model-assessor\u002FSKILL.md](..\u002Fcompute-model-assessor\u002FSKILL.md) for 5D compute assessment calibrations, [..\u002Fagent-harness-architect\u002FSKILL.md](..\u002Fagent-harness-architect\u002FSKILL.md) for harness reliability mechanisms, and [..\u002Fself-evaluating-ai-pipeline\u002FSKILL.md](..\u002Fself-evaluating-ai-pipeline\u002FSKILL.md) for model evaluation gates.\nAuthoritative domain engine is co-located in [scripts\u002Fdynamic_model_router_engine.py](scripts\u002Fdynamic_model_router_engine.py) and elevated into the micro-kernel IoC service seam via [..\u002F..\u002F..\u002Fplugins\u002Fagent_orchestration\u002Fdynamic_model_router\u002Fmain.py](..\u002F..\u002F..\u002Fplugins\u002Fagent_orchestration\u002Fdynamic_model_router\u002Fmain.py).\n\n---\n\n## 1. Offline Complexity & Intent Profiling\n\nClassify incoming prompts into discrete complexity tiers using deterministic, zero-LLM heuristics that execute in under 5 milliseconds:\n\n1. **Deterministic Syntax & Length Heuristics**:\n   - Never dispatch an LLM call to classify prompts; spending $0.005 and 500ms of network latency to route a prompt defeats the cost and throughput benefits of dynamic routing.\n   - Profile incoming text strings using three fast syntactic checks:\n     * *Code Block Fences*: Detect markdown code markers (` ``` `) signaling code generation, debugging, or syntax refactoring.\n     * *Reasoning Regex Keywords*: Match high-cognitive intent tokens (`refactor`, `debug`, `algorithm`, `architecture`, `optimize`, `kernel`, `proof`, `analyze`).\n     * *Word \u002F Token Boundaries*: Split on whitespace to calculate raw length boundaries.\n2. **Assign Task Complexity Tier**:\n   - `TaskComplexity.SIMPLE`: Short factual prompts (\u003C 80 words) containing zero code blocks and no reasoning keywords (e.g., FAQ lookups, classification, tone adjustment, one-sentence summaries).\n   - `TaskComplexity.MEDIUM`: Moderate conversational prompts (80–300 words) requiring coherent structuring, entity extraction, or standard tool invocation.\n   - `TaskComplexity.COMPLEX`: Heavy reasoning tasks containing code blocks, matching complex keywords, or exceeding 300 words in length.\n3. **Complexity Engine Implementation**:\n\n```python\nfrom enum import Enum\nimport re\n\nclass TaskComplexity(str, Enum):\n    SIMPLE = \"simple\"\n    MEDIUM = \"medium\"\n    COMPLEX = \"complex\"\n\nclass PromptAnalyzer:\n    def __init__(self) -> None:\n        self.complex_keywords = [\n            r\"\\brefactor\\b\",\n            r\"\\bdebug\\b\",\n            r\"\\boptimize\\b\",\n            r\"\\balgorithm\\b\",\n            r\"\\barchitecture\\b\",\n            r\"\\bconcurrency\\b\",\n            r\"\\bkernel\\b\",\n        ]\n\n    def analyze_complexity(self, prompt: str) -> TaskComplexity:\n        normalized = prompt.lower().strip()\n        word_count = len(normalized.split())\n\n        contains_code = \"```\" in prompt\n        has_complex_keyword = any(\n            re.search(pattern, normalized) for pattern in self.complex_keywords\n        )\n\n        if contains_code or has_complex_keyword or word_count > 300:\n            return TaskComplexity.COMPLEX\n        elif word_count > 80:\n            return TaskComplexity.MEDIUM\n        return TaskComplexity.SIMPLE\n```\n\n> **Completion criterion**: Prompt evaluated deterministically in $\u003C 5\\text{ ms}$ with zero network requests and categorized into `SIMPLE`, `MEDIUM`, or `COMPLEX`.\n\n---\n\n## 2. Declarative Model Routing Resolution\n\nMap evaluated complexity tiers to primary and secondary fallback model configurations through a centralized, declarative routing table:\n\n1. **Define Model Configuration Schema**:\n   - Model configurations must declare both provider domain (e.g., `\"openai\"`, `\"anthropic\"`, `\"gemini\"`) and the specific versioned model identifier (e.g., `\"gpt-4o-mini\"`, `\"claude-3-5-sonnet-20241022\"`).\n2. **Enforce the Provider Diversity Invariant**:\n   - A primary model and its fallback must **never** share the same cloud provider infrastructure (`primary.provider != fallback.provider`).\n   - Coupling a primary model (`gpt-4o`) to a same-vendor fallback (`gpt-4o-mini`) guarantees total outage during provider-wide API incidents, DNS outages, or auth service downtime.\n3. **Route Against the 3-Tier Allocation Matrix**:\n   - *Simple Tier*: Primary budget model (e.g., `openai \u002F gpt-4o-mini`), backed by an alternative provider flash model (e.g., `anthropic \u002F claude-3-5-haiku-20241022` or `gemini \u002F gemini-2.5-flash`).\n   - *Medium Tier*: Primary high-throughput model (e.g., `openai \u002F gpt-4o-mini`), backed by balanced secondary (e.g., `anthropic \u002F claude-3-5-haiku-20241022`).\n   - *Complex Tier*: Primary frontier reasoning model (e.g., `anthropic \u002F claude-3-5-sonnet-20241022`), backed by an alternative frontier reasoning model (e.g., `openai \u002F gpt-4o` or `gemini \u002F gemini-2.5-pro`).\n4. **Router Implementation**:\n\n```python\nfrom pydantic import BaseModel\n\nclass ModelConfig(BaseModel):\n    provider: str\n    model_name: str\n\nclass ModelRouter:\n    def __init__(self) -> None:\n        self.routing_table: dict[TaskComplexity, dict[str, ModelConfig]] = {\n            TaskComplexity.SIMPLE: {\n                \"primary\": ModelConfig(provider=\"openai\", model_name=\"gpt-4o-mini\"),\n                \"fallback\": ModelConfig(provider=\"anthropic\", model_name=\"claude-3-5-haiku-20241022\"),\n            },\n            TaskComplexity.MEDIUM: {\n                \"primary\": ModelConfig(provider=\"openai\", model_name=\"gpt-4o-mini\"),\n                \"fallback\": ModelConfig(provider=\"anthropic\", model_name=\"claude-3-5-haiku-20241022\"),\n            },\n            TaskComplexity.COMPLEX: {\n                \"primary\": ModelConfig(provider=\"anthropic\", model_name=\"claude-3-5-sonnet-20241022\"),\n                \"fallback\": ModelConfig(provider=\"openai\", model_name=\"gpt-4o\"),\n            },\n        }\n\n    def get_models_for_tier(self, complexity: TaskComplexity) -> tuple[ModelConfig, ModelConfig]:\n        config = self.routing_table[complexity]\n        return config[\"primary\"], config[\"fallback\"]\n```\n\n> **Completion criterion**: Discrete `(primary, fallback)` tuple resolved from the routing table with strictly verified provider diversity.\n\n---\n\n## 3. Resilient Strict-Timeout Encasement\n\nEncapsulate model provider calls behind unified abstraction bridges with aggressive, client-enforced socket timeouts:\n\n1. **Tight Timeout Budgeting (5.0s – 10.0s)**:\n   - Upstream model APIs frequently experience TCP hangs, threadpool stalls, or silent queuing during degradation rather than throwing clean immediate errors.\n   - Relying on default SDK socket timeouts (30 to 120 seconds) leaves users waiting at frozen interfaces.\n   - Enforce an explicit timeout bound of $\\le 10.0\\text{ s}$ on primary provider invocations to trigger failover before end-user abandonment.\n2. **Decoupled Provider Bridge Dispatchers**:\n   - Isolate vendor SDK specifics inside private adapter methods (`_call_openai`, `_call_anthropic`, `_call_gemini`).\n   - Normalize API arguments (system prompts, user messages, max tokens, temperature) across client implementations.\n3. **Execution Engine Skeleton**:\n\n```python\nimport os\nfrom openai import OpenAI, APIError as OpenAIAPIError\nfrom anthropic import Anthropic, APIError as AnthropicAPIError\n\nclass ResilientModelEngine:\n    def __init__(self, timeout_seconds: float = 10.0) -> None:\n        self.timeout = timeout_seconds\n        self.openai_client = OpenAI(api_key=os.getenv(\"OPENAI_API_KEY\", \"dummy\"))\n        self.anthropic_client = Anthropic(api_key=os.getenv(\"ANTHROPIC_API_KEY\", \"dummy\"))\n\n    def _call_openai(self, model: str, prompt: str) -> str:\n        response = self.openai_client.chat.completions.create(\n            model=model,\n            messages=[{\"role\": \"user\", \"content\": prompt}],\n            timeout=self.timeout,\n        )\n        return response.choices[0].message.content or \"\"\n\n    def _call_anthropic(self, model: str, prompt: str) -> str:\n        response = self.anthropic_client.messages.create(\n            model=model,\n            max_tokens=2048,\n            messages=[{\"role\": \"user\", \"content\": prompt}],\n            timeout=self.timeout,\n        )\n        return response.content[0].text\n```\n\n> **Completion criterion**: Provider clients instantiated with unified $\\le 10.0\\text{ s}$ timeout guards and decoupled adapter bridges.\n\n---\n\n## 4. Automated Failover & Fallback Invocation\n\nExecute primary model calls inside resilient exception-trapping blocks and trigger instant fallback upon transient degradation:\n\n1. **Trap Provider-Specific Exceptions**:\n   - Catch rate-limiting errors (`HTTP 429 Too Many Requests`), gateway timeouts (`HTTP 504`), service downtime (`HTTP 503`), socket timeouts, and provider SDK API errors.\n2. **Log Structured Recovery Warning**:\n   - Log explicit telemetry containing the failing provider, model name, exception message, and the designated fallback target.\n   - Never silently swallow errors; silent failover masks upstream infrastructure degradations and creates unexpected billing shifts.\n3. **Invoke Secondary Fallback Seamlessly**:\n   - Instantly route the identical prompt payload to the secondary fallback model without breaking the calling application's execution chain.\n   - Escalate to an unrecoverable `RuntimeError` only if both primary and secondary fallback calls fail.\n4. **Resilient Failover Logic**:\n\n```python\nimport structlog\n\nlogger = structlog.get_logger()\n\nclass ResilientModelEngine(ResilientModelEngine):\n    def execute_provider_call(self, config: ModelConfig, prompt: str) -> str:\n        if config.provider == \"openai\":\n            return self._call_openai(config.model_name, prompt)\n        elif config.provider == \"anthropic\":\n            return self._call_anthropic(config.model_name, prompt)\n        raise ValueError(f\"Unsupported model provider: {config.provider}\")\n\n    def execute_with_fallback(\n        self, primary: ModelConfig, fallback: ModelConfig, prompt: str\n    ) -> tuple[str, str, bool]:\n        # Attempt Primary Provider\n        try:\n            logger.info(\"calling_primary_provider\", provider=primary.provider, model=primary.model_name)\n            response = self.execute_provider_call(primary, prompt)\n            return response, primary.model_name, False\n        except (OpenAIAPIError, AnthropicAPIError, TimeoutError, Exception) as primary_error:\n            logger.warning(\n                \"primary_model_failed_activating_fallback\",\n                primary_provider=primary.provider,\n                primary_model=primary.model_name,\n                fallback_provider=fallback.provider,\n                fallback_model=fallback.model_name,\n                error=str(primary_error),\n            )\n\n        # Attempt Secondary Fallback Provider\n        try:\n            logger.info(\"calling_fallback_provider\", provider=fallback.provider, model=fallback.model_name)\n            response = self.execute_provider_call(fallback, prompt)\n            return response, fallback.model_name, True\n        except Exception as fallback_error:\n            logger.error(\"all_model_providers_failed\", error=str(fallback_error))\n            raise RuntimeError(\n                f\"Critical: Both primary ({primary.model_name}) and fallback ({fallback.model_name}) failed. \"\n                f\"Root cause: {fallback_error}\"\n            ) from fallback_error\n```\n\n> **Completion criterion**: Primary failures caught within timeout bounds and execution smoothly recovered via secondary fallback with audit logging.\n\n---\n\n## 5. Output Schema Normalization & Telemetry Audit\n\nPackage all execution returns into a canonical, provider-agnostic data schema and emit telemetry for routing calibration:\n\n1. **Normalize Output Schema**:\n   - Prevent vendor-specific response objects (`openai.types.chat.ChatCompletion`, `anthropic.types.Message`) from leaking into application layers.\n   - Standardize outputs into a typed response schema declaring execution status, resolved complexity tier, executed model, fallback flag, and clean text response.\n2. **Emit Operational Observability & Cost Deltas**:\n   - Record token counts, round-trip latency, model provider, and whether fallback occurred.\n   - Track the volume ratio: verify that fast\u002Fbudget models handle $\\ge 60\\%$ of total request traffic, validating that the complexity classifier's thresholds are properly tuned.\n3. **Unified Orchestration Engine**:\n\n```python\nfrom pydantic import BaseModel\n\nclass NormalizedResponse(BaseModel):\n    status: str\n    complexity_tier: TaskComplexity\n    model_used: str\n    fallback_used: bool\n    response: str\n\nclass SmartAIEngine:\n    def __init__(self) -> None:\n        self.analyzer = PromptAnalyzer()\n        self.router = ModelRouter()\n        self.executor = ResilientModelEngine(timeout_seconds=10.0)\n\n    def process_request(self, user_prompt: str) -> NormalizedResponse:\n        # Step 1: Deterministic offline analysis\n        complexity = self.analyzer.analyze_complexity(user_prompt)\n\n        # Step 2: Declarative routing resolution\n        primary, fallback = self.router.get_models_for_tier(complexity)\n\n        # Step 3 & 4: Resilient execution with fallback\n        response_text, executed_model, fallback_used = self.executor.execute_with_fallback(\n            primary=primary, fallback=fallback, prompt=user_prompt\n        )\n\n        # Step 5: Normalized schema packaging\n        return NormalizedResponse(\n            status=\"success\",\n            complexity_tier=complexity,\n            model_used=executed_model,\n            fallback_used=fallback_used,\n            response=response_text,\n        )\n```\n\n> **Completion criterion**: Downstream clients receive uniform `NormalizedResponse` schemas with verified telemetry logging and fallback tracking.\n\n### The Visual Brief\n\nGenerate a standalone interactive HTML visual brief in `%TEMP%\u002Fdynamic-model-router-\u003Ctimestamp>.html` summarizing routing metrics:\n1. **Visual Telemetry**:\n   - Render a dark-themed (`#0d1117`) dashboard loading Tailwind CSS and Mermaid.js via CDN.\n   - Embed a **Routing Distribution Flowchart** illustrating query classification breakdown across simple, medium, and complex tiers.\n   - Render a **Fallback Event Audit Table** detailing primary provider errors, failover frequencies, and latency deltas.\n2. **Delivery**:\n   - Deliver the clickable absolute file path to the operator for real-time routing inspection.\n\n### Mandatory Checkpoint Gate\n\nEnforce an operational review checkpoint (`RequestFeedback: true`) prior to committing routing table modifications or provider migrations:\n1. **Provider Availability & Parity Audit**:\n   - Verify that fallback models maintain functional parity with primary models before deployment.\n   - Assert `primary.provider != fallback.provider` across all tiers to preserve infrastructure diversity.\n2. **Operational Budget Sign-off**:\n   - Validate that default timeouts ($\\le 10.0\\text{ s}$) and retry budgets are declared in `config.default.yaml`.\n\n---\n\n## Diagnostic Evaluation Scorecard Table\n\n| Dimension | Evaluation Criterion | Target Threshold | Verification Mechanism | Passing Gate |\n|---|---|---|---|---|\n| **Classifier Latency** | Deterministic pre-routing classification speed | $\\le 5.0\\text{ ms}$ | Benchmark 1,000 synthetic prompts against regex & length scanner | P99 latency $\u003C 5\\text{ ms}$ with zero network calls |\n| **Cost Distribution** | Ratio of routine traffic handled by low-cost models | $\\ge 60\\%$ of queries | Inspect routing decision logs across production traffic sample | $\\ge 60\\%$ routed to budget flash tier |\n| **Failover SLA** | Timeout latency ceiling before initiating secondary failover | $\\le 10.0\\text{ s}$ | Simulate primary provider socket hang in automated mock harness | Secondary model invoked within $10.0\\text{ s}$ |\n| **Provider Diversity** | Primary and fallback reside on decoupled cloud infrastructures | $100\\%$ decoupled | Audit routing matrix: assert `primary.provider != fallback.provider` | Zero shared infrastructure dependencies |\n| **Schema Normalization**| Provider-specific SDK objects isolated from consumers | $100\\%$ compliance | Typecheck downstream consumers against `NormalizedResponse` | Zero vendor SDK object leakage |\n\n---\n\n## Anti-Patterns\n\n- **LLM-for-Routing** — Invoking an auxiliary language model to determine prompt complexity before routing; introduces 300–800ms of latency and doubles query token expenditure.\n- **Lax Provider Timeout** — Relying on default SDK socket timeouts (30 to 120 seconds); freezes user interfaces and degrades end-user experience during upstream API degradations.\n- **Vendor Monoculture Fallback** — Assigning primary and fallback models to the same cloud provider; causes concurrent double-failure during vendor-wide outages or authentication failures.\n- **Silent Failover Drift** — Catching primary provider errors and executing fallbacks without logging warnings or failure telemetry; obscures chronic outages and causes unmonitored billing spikes.\n- **Hardcoded Fallback-Free Invocation** — Invoking single proprietary models directly from business logic without fallback routing tables; creates fragile, single-point-of-failure applications.\n","# Dynamic Model Router: Multi-Provider Switching & Resilient Failover Engine\n\n`dynamic-model-router` is the cognitive and architectural engine for designing, deploying, and operating multi-provider AI model routing systems. Synthesized from Chidiebere Njoku's foundational literature (*How to Build AI Applications That Switch Models Automatically*, freeCodeCamp, 2026) and grounded in the Knowledge Vault ([ki_njoku_dynamic_model_routing](..\u002F..\u002F..\u002F.harness\u002Fknowledge\u002Fki_njoku_dynamic_model_routing\u002Fsummary.md)), this skill operationalizes dynamic model switching to eliminate single-point-of-failure API outages, curb token cost inflation, and enforce strict execution SLAs.\n\nRelying on a single monolithic frontier model for every incoming request introduces severe production risks: upstream API downtime freezes end-user workflows, expensive reasoning models are wasted on trivial formatting tasks, and lightweight models fail on complex multi-step reasoning. `dynamic-model-router` enforces a decoupled 3-tier lifecycle: deterministic offline complexity profiling, declarative model matrix resolution, and resilient multi-provider failover.\n\nEvery dynamic model routing workflow executes this 5-stage progression:\n\n```\n[1. Offline Complexity Profiling] → [2. Declarative Matrix Resolution] → [3. Strict-Timeout Encasement] → [4. Automated Failover Execution] → [5. Schema Normalization & Telemetry]\n```\n\nSee [CARD.md](CARD.md) for the companion summary card, stage reference matrix, and verification checklist.\nConsult [..\u002Fcompute-model-assessor\u002FSKILL.md](..\u002Fcompute-model-assessor\u002FSKILL.md) for 5D compute assessment calibrations, [..\u002Fagent-harness-architect\u002FSKILL.md](..\u002Fagent-harness-architect\u002FSKILL.md) for harness reliability mechanisms, and [..\u002Fself-evaluating-ai-pipeline\u002FSKILL.md](..\u002Fself-evaluating-ai-pipeline\u002FSKILL.md) for model evaluation gates.\nAuthoritative domain engine is co-located in [scripts\u002Fdynamic_model_router_engine.py](scripts\u002Fdynamic_model_router_engine.py) and elevated into the micro-kernel IoC service seam via [..\u002F..\u002F..\u002Fplugins\u002Fagent_orchestration\u002Fdynamic_model_router\u002Fmain.py](..\u002F..\u002F..\u002Fplugins\u002Fagent_orchestration\u002Fdynamic_model_router\u002Fmain.py).\n\n---\n\n## 1. Offline Complexity & Intent Profiling\n\nClassify incoming prompts into discrete complexity tiers using deterministic, zero-LLM heuristics that execute in under 5 milliseconds:\n\n1. **Deterministic Syntax & Length Heuristics**:\n   - Never dispatch an LLM call to classify prompts; spending $0.005 and 500ms of network latency to route a prompt defeats the cost and throughput benefits of dynamic routing.\n   - Profile incoming text strings using three fast syntactic checks:\n     * *Code Block Fences*: Detect markdown code markers (` ``` `) signaling code generation, debugging, or syntax refactoring.\n     * *Reasoning Regex Keywords*: Match high-cognitive intent tokens (`refactor`, `debug`, `algorithm`, `architecture`, `optimize`, `kernel`, `proof`, `analyze`).\n     * *Word \u002F Token Boundaries*: Split on whitespace to calculate raw length boundaries.\n2. **Assign Task Complexity Tier**:\n   - `TaskComplexity.SIMPLE`: Short factual prompts (\u003C 80 words) containing zero code blocks and no reasoning keywords (e.g., FAQ lookups, classification, tone adjustment, one-sentence summaries).\n   - `TaskComplexity.MEDIUM`: Moderate conversational prompts (80–300 words) requiring coherent structuring, entity extraction, or standard tool invocation.\n   - `TaskComplexity.COMPLEX`: Heavy reasoning tasks containing code blocks, matching complex keywords, or exceeding 300 words in length.\n3. **Complexity Engine Implementation**:\n\n```python\nfrom enum import Enum\nimport re\n\nclass TaskComplexity(str, Enum):\n    SIMPLE = \"simple\"\n    MEDIUM = \"medium\"\n    COMPLEX = \"complex\"\n\nclass PromptAnalyzer:\n    def __init__(self) -> None:\n        self.complex_keywords = [\n            r\"\\brefactor\\b\",\n            r\"\\bdebug\\b\",\n            r\"\\boptimize\\b\",\n            r\"\\balgorithm\\b\",\n            r\"\\barchitecture\\b\",\n            r\"\\bconcurrency\\b\",\n            r\"\\bkernel\\b\",\n        ]\n\n    def analyze_complexity(self, prompt: str) -> TaskComplexity:\n        normalized = prompt.lower().strip()\n        word_count = len(normalized.split())\n\n        contains_code = \"```\" in prompt\n        has_complex_keyword = any(\n            re.search(pattern, normalized) for pattern in self.complex_keywords\n        )\n\n        if contains_code or has_complex_keyword or word_count > 300:\n            return TaskComplexity.COMPLEX\n        elif word_count > 80:\n            return TaskComplexity.MEDIUM\n        return TaskComplexity.SIMPLE\n```\n\n> **Completion criterion**: Prompt evaluated deterministically in $\u003C 5\\text{ ms}$ with zero network requests and categorized into `SIMPLE`, `MEDIUM`, or `COMPLEX`.\n\n---\n\n## 2. Declarative Model Routing Resolution\n\nMap evaluated complexity tiers to primary and secondary fallback model configurations through a centralized, declarative routing table:\n\n1. **Define Model Configuration Schema**:\n   - Model configurations must declare both provider domain (e.g., `\"openai\"`, `\"anthropic\"`, `\"gemini\"`) and the specific versioned model identifier (e.g., `\"gpt-4o-mini\"`, `\"claude-3-5-sonnet-20241022\"`).\n2. **Enforce the Provider Diversity Invariant**:\n   - A primary model and its fallback must **never** share the same cloud provider infrastructure (`primary.provider != fallback.provider`).\n   - Coupling a primary model (`gpt-4o`) to a same-vendor fallback (`gpt-4o-mini`) guarantees total outage during provider-wide API incidents, DNS outages, or auth service downtime.\n3. **Route Against the 3-Tier Allocation Matrix**:\n   - *Simple Tier*: Primary budget model (e.g., `openai \u002F gpt-4o-mini`), backed by an alternative provider flash model (e.g., `anthropic \u002F claude-3-5-haiku-20241022` or `gemini \u002F gemini-2.5-flash`).\n   - *Medium Tier*: Primary high-throughput model (e.g., `openai \u002F gpt-4o-mini`), backed by balanced secondary (e.g., `anthropic \u002F claude-3-5-haiku-20241022`).\n   - *Complex Tier*: Primary frontier reasoning model (e.g., `anthropic \u002F claude-3-5-sonnet-20241022`), backed by an alternative frontier reasoning model (e.g., `openai \u002F gpt-4o` or `gemini \u002F gemini-2.5-pro`).\n4. **Router Implementation**:\n\n```python\nfrom pydantic import BaseModel\n\nclass ModelConfig(BaseModel):\n    provider: str\n    model_name: str\n\nclass ModelRouter:\n    def __init__(self) -> None:\n        self.routing_table: dict[TaskComplexity, dict[str, ModelConfig]] = {\n            TaskComplexity.SIMPLE: {\n                \"primary\": ModelConfig(provider=\"openai\", model_name=\"gpt-4o-mini\"),\n                \"fallback\": ModelConfig(provider=\"anthropic\", model_name=\"claude-3-5-haiku-20241022\"),\n            },\n            TaskComplexity.MEDIUM: {\n                \"primary\": ModelConfig(provider=\"openai\", model_name=\"gpt-4o-mini\"),\n                \"fallback\": ModelConfig(provider=\"anthropic\", model_name=\"claude-3-5-haiku-20241022\"),\n            },\n            TaskComplexity.COMPLEX: {\n                \"primary\": ModelConfig(provider=\"anthropic\", model_name=\"claude-3-5-sonnet-20241022\"),\n                \"fallback\": ModelConfig(provider=\"openai\", model_name=\"gpt-4o\"),\n            },\n        }\n\n    def get_models_for_tier(self, complexity: TaskComplexity) -> tuple[ModelConfig, ModelConfig]:\n        config = self.routing_table[complexity]\n        return config[\"primary\"], config[\"fallback\"]\n```\n\n> **Completion criterion**: Discrete `(primary, fallback)` tuple resolved from the routing table with strictly verified provider diversity.\n\n---\n\n## 3. Resilient Strict-Timeout Encasement\n\nEncapsulate model provider calls behind unified abstraction bridges with aggressive, client-enforced socket timeouts:\n\n1. **Tight Timeout Budgeting (5.0s – 10.0s)**:\n   - Upstream model APIs frequently experience TCP hangs, threadpool stalls, or silent queuing during degradation rather than throwing clean immediate errors.\n   - Relying on default SDK socket timeouts (30 to 120 seconds) leaves users waiting at frozen interfaces.\n   - Enforce an explicit timeout bound of $\\le 10.0\\text{ s}$ on primary provider invocations to trigger failover before end-user abandonment.\n2. **Decoupled Provider Bridge Dispatchers**:\n   - Isolate vendor SDK specifics inside private adapter methods (`_call_openai`, `_call_anthropic`, `_call_gemini`).\n   - Normalize API arguments (system prompts, user messages, max tokens, temperature) across client implementations.\n3. **Execution Engine Skeleton**:\n\n```python\nimport os\nfrom openai import OpenAI, APIError as OpenAIAPIError\nfrom anthropic import Anthropic, APIError as AnthropicAPIError\n\nclass ResilientModelEngine:\n    def __init__(self, timeout_seconds: float = 10.0) -> None:\n        self.timeout = timeout_seconds\n        self.openai_client = OpenAI(api_key=os.getenv(\"OPENAI_API_KEY\", \"dummy\"))\n        self.anthropic_client = Anthropic(api_key=os.getenv(\"ANTHROPIC_API_KEY\", \"dummy\"))\n\n    def _call_openai(self, model: str, prompt: str) -> str:\n        response = self.openai_client.chat.completions.create(\n            model=model,\n            messages=[{\"role\": \"user\", \"content\": prompt}],\n            timeout=self.timeout,\n        )\n        return response.choices[0].message.content or \"\"\n\n    def _call_anthropic(self, model: str, prompt: str) -> str:\n        response = self.anthropic_client.messages.create(\n            model=model,\n            max_tokens=2048,\n            messages=[{\"role\": \"user\", \"content\": prompt}],\n            timeout=self.timeout,\n        )\n        return response.content[0].text\n```\n\n> **Completion criterion**: Provider clients instantiated with unified $\\le 10.0\\text{ s}$ timeout guards and decoupled adapter bridges.\n\n---\n\n## 4. Automated Failover & Fallback Invocation\n\nExecute primary model calls inside resilient exception-trapping blocks and trigger instant fallback upon transient degradation:\n\n1. **Trap Provider-Specific Exceptions**:\n   - Catch rate-limiting errors (`HTTP 429 Too Many Requests`), gateway timeouts (`HTTP 504`), service downtime (`HTTP 503`), socket timeouts, and provider SDK API errors.\n2. **Log Structured Recovery Warning**:\n   - Log explicit telemetry containing the failing provider, model name, exception message, and the designated fallback target.\n   - Never silently swallow errors; silent failover masks upstream infrastructure degradations and creates unexpected billing shifts.\n3. **Invoke Secondary Fallback Seamlessly**:\n   - Instantly route the identical prompt payload to the secondary fallback model without breaking the calling application's execution chain.\n   - Escalate to an unrecoverable `RuntimeError` only if both primary and secondary fallback calls fail.\n4. **Resilient Failover Logic**:\n\n```python\nimport structlog\n\nlogger = structlog.get_logger()\n\nclass ResilientModelEngine(ResilientModelEngine):\n    def execute_provider_call(self, config: ModelConfig, prompt: str) -> str:\n        if config.provider == \"openai\":\n            return self._call_openai(config.model_name, prompt)\n        elif config.provider == \"anthropic\":\n            return self._call_anthropic(config.model_name, prompt)\n        raise ValueError(f\"Unsupported model provider: {config.provider}\")\n\n    def execute_with_fallback(\n        self, primary: ModelConfig, fallback: ModelConfig, prompt: str\n    ) -> tuple[str, str, bool]:\n        # Attempt Primary Provider\n        try:\n            logger.info(\"calling_primary_provider\", provider=primary.provider, model=primary.model_name)\n            response = self.execute_provider_call(primary, prompt)\n            return response, primary.model_name, False\n        except (OpenAIAPIError, AnthropicAPIError, TimeoutError, Exception) as primary_error:\n            logger.warning(\n                \"primary_model_failed_activating_fallback\",\n                primary_provider=primary.provider,\n                primary_model=primary.model_name,\n                fallback_provider=fallback.provider,\n                fallback_model=fallback.model_name,\n                error=str(primary_error),\n            )\n\n        # Attempt Secondary Fallback Provider\n        try:\n            logger.info(\"calling_fallback_provider\", provider=fallback.provider, model=fallback.model_name)\n            response = self.execute_provider_call(fallback, prompt)\n            return response, fallback.model_name, True\n        except Exception as fallback_error:\n            logger.error(\"all_model_providers_failed\", error=str(fallback_error))\n            raise RuntimeError(\n                f\"Critical: Both primary ({primary.model_name}) and fallback ({fallback.model_name}) failed. \"\n                f\"Root cause: {fallback_error}\"\n            ) from fallback_error\n```\n\n> **Completion criterion**: Primary failures caught within timeout bounds and execution smoothly recovered via secondary fallback with audit logging.\n\n---\n\n## 5. Output Schema Normalization & Telemetry Audit\n\nPackage all execution returns into a canonical, provider-agnostic data schema and emit telemetry for routing calibration:\n\n1. **Normalize Output Schema**:\n   - Prevent vendor-specific response objects (`openai.types.chat.ChatCompletion`, `anthropic.types.Message`) from leaking into application layers.\n   - Standardize outputs into a typed response schema declaring execution status, resolved complexity tier, executed model, fallback flag, and clean text response.\n2. **Emit Operational Observability & Cost Deltas**:\n   - Record token counts, round-trip latency, model provider, and whether fallback occurred.\n   - Track the volume ratio: verify that fast\u002Fbudget models handle $\\ge 60\\%$ of total request traffic, validating that the complexity classifier's thresholds are properly tuned.\n3. **Unified Orchestration Engine**:\n\n```python\nfrom pydantic import BaseModel\n\nclass NormalizedResponse(BaseModel):\n    status: str\n    complexity_tier: TaskComplexity\n    model_used: str\n    fallback_used: bool\n    response: str\n\nclass SmartAIEngine:\n    def __init__(self) -> None:\n        self.analyzer = PromptAnalyzer()\n        self.router = ModelRouter()\n        self.executor = ResilientModelEngine(timeout_seconds=10.0)\n\n    def process_request(self, user_prompt: str) -> NormalizedResponse:\n        # Step 1: Deterministic offline analysis\n        complexity = self.analyzer.analyze_complexity(user_prompt)\n\n        # Step 2: Declarative routing resolution\n        primary, fallback = self.router.get_models_for_tier(complexity)\n\n        # Step 3 & 4: Resilient execution with fallback\n        response_text, executed_model, fallback_used = self.executor.execute_with_fallback(\n            primary=primary, fallback=fallback, prompt=user_prompt\n        )\n\n        # Step 5: Normalized schema packaging\n        return NormalizedResponse(\n            status=\"success\",\n            complexity_tier=complexity,\n            model_used=executed_model,\n            fallback_used=fallback_used,\n            response=response_text,\n        )\n```\n\n> **Completion criterion**: Downstream clients receive uniform `NormalizedResponse` schemas with verified telemetry logging and fallback tracking.\n\n### The Visual Brief\n\nGenerate a standalone interactive HTML visual brief in `%TEMP%\u002Fdynamic-model-router-\u003Ctimestamp>.html` summarizing routing metrics:\n1. **Visual Telemetry**:\n   - Render a dark-themed (`#0d1117`) dashboard loading Tailwind CSS and Mermaid.js via CDN.\n   - Embed a **Routing Distribution Flowchart** illustrating query classification breakdown across simple, medium, and complex tiers.\n   - Render a **Fallback Event Audit Table** detailing primary provider errors, failover frequencies, and latency deltas.\n2. **Delivery**:\n   - Deliver the clickable absolute file path to the operator for real-time routing inspection.\n\n### Mandatory Checkpoint Gate\n\nEnforce an operational review checkpoint (`RequestFeedback: true`) prior to committing routing table modifications or provider migrations:\n1. **Provider Availability & Parity Audit**:\n   - Verify that fallback models maintain functional parity with primary models before deployment.\n   - Assert `primary.provider != fallback.provider` across all tiers to preserve infrastructure diversity.\n2. **Operational Budget Sign-off**:\n   - Validate that default timeouts ($\\le 10.0\\text{ s}$) and retry budgets are declared in `config.default.yaml`.\n\n---\n\n## Diagnostic Evaluation Scorecard Table\n\n| Dimension | Evaluation Criterion | Target Threshold | Verification Mechanism | Passing Gate |\n|---|---|---|---|---|\n| **Classifier Latency** | Deterministic pre-routing classification speed | $\\le 5.0\\text{ ms}$ | Benchmark 1,000 synthetic prompts against regex & length scanner | P99 latency $\u003C 5\\text{ ms}$ with zero network calls |\n| **Cost Distribution** | Ratio of routine traffic handled by low-cost models | $\\ge 60\\%$ of queries | Inspect routing decision logs across production traffic sample | $\\ge 60\\%$ routed to budget flash tier |\n| **Failover SLA** | Timeout latency ceiling before initiating secondary failover | $\\le 10.0\\text{ s}$ | Simulate primary provider socket hang in automated mock harness | Secondary model invoked within $10.0\\text{ s}$ |\n| **Provider Diversity** | Primary and fallback reside on decoupled cloud infrastructures | $100\\%$ decoupled | Audit routing matrix: assert `primary.provider != fallback.provider` | Zero shared infrastructure dependencies |\n| **Schema Normalization**| Provider-specific SDK objects isolated from consumers | $100\\%$ compliance | Typecheck downstream consumers against `NormalizedResponse` | Zero vendor SDK object leakage |\n\n---\n\n## Anti-Patterns\n\n- **LLM-for-Routing** — Invoking an auxiliary language model to determine prompt complexity before routing; introduces 300–800ms of latency and doubles query token expenditure.\n- **Lax Provider Timeout** — Relying on default SDK socket timeouts (30 to 120 seconds); freezes user interfaces and degrades end-user experience during upstream API degradations.\n- **Vendor Monoculture Fallback** — Assigning primary and fallback models to the same cloud provider; causes concurrent double-failure during vendor-wide outages or authentication failures.\n- **Silent Failover Drift** — Catching primary provider errors and executing fallbacks without logging warnings or failure telemetry; obscures chronic outages and causes unmonitored billing spikes.\n- **Hardcoded Fallback-Free Invocation** — Invoking single proprietary models directly from business logic without fallback routing tables; creates fragile, single-point-of-failure applications.\n",{"name":5,"description":7},"main","eff3b00e36d1d233ad4a4389605c82fbfa0326d3",".agents\u002Fskills\u002Fdynamic-model-router","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness","https:\u002F\u002Fgithub.com\u002FSpectreDeath","I'm here to manage stress so I wouldn't expect earth shattering break throughs I'm just an enthusiast that likes making stuff. ","2026-11-15 05:32:58",{"source":8,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add SpectreDeath\u002FBrain-Harness --skill dynamic-model-router",{"tool":37,"command":38},"bunx","bunx skills add SpectreDeath\u002FBrain-Harness --skill dynamic-model-router",{"tool":40,"command":41},"pnpm","pnpm dlx skills add SpectreDeath\u002FBrain-Harness --skill dynamic-model-router","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fdynamic-model-router\u002FSKILL.md",true,[45,51,55],{"path":46,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":49,"sourceHtmlUrl":50},"CARD.md","REFERENCE","参考文档",4757,"https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fdynamic-model-router\u002FCARD.md",{"path":52,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":53,"sourceHtmlUrl":54},"config.default.yaml",892,"https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fdynamic-model-router\u002Fconfig.default.yaml",{"path":56,"resourceType":57,"resourceTypeDesc":58,"sizeBytes":59,"sourceHtmlUrl":60},"scripts\u002Fdynamic_model_router_engine.py","SCRIPT","脚本",26232,"https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fdynamic-model-router\u002Fscripts\u002Fdynamic_model_router_engine.py",[62,69,76,83,90,97],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":19},"01M7E0W6FR68J2N9CXCZTAQJFX","ui-behavior-primitive-architect","Architect, audit, and verify zero-dependency headless UI behavior primitives, WebMCP agent bridges, WAI-ARIA\u002FSSR\u002FRTL tri-modal checks, and framework expert routing. Do not use for static CSS theme styling or backend database migrations.","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fui-behavior-primitive-architect\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M7E0VZ7JQNW34G271DENFGYP","trustgraph-ontology-governor","Govern knowledge graphs, SHACL-AF triple policies, OntologyRAG subclass validation, PROV-O dual named graphs, and Laya entropy decision scoring. Do not use for relational SQL queries or generic web scraping.","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Ftrustgraph-ontology-governor\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M7E0VQ6Z7R45Q8QAZ4MT39EK","shim-harness-governor","Govern universal CLI agent loops, 4-tier tool permissions, ancestor-symlink workspace sandboxes, deterministic-first command routing, collision-safe MCP namespacing, and layered skill loading. Do not use for static UI styling or external SQL analytics.","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fshim-harness-governor\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M7E0VC18NMP1QBSRJ3TPQ7MB","graphiti-zep-memory-governor","Govern bi-temporal knowledge graphs with Graphiti future-edge clamping, MinHash\u002FLSH entity dedup, RRF\u002FMMR reranking, and Zep typed ontologies. Do not use for static SQL joins or generic web crawling.","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgraphiti-zep-memory-governor\u002FSKILL.md",[],[],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":19},"01M7E0V12ABE1RW3ZRCST8VH5Z","agora-mcp-workbench-architect","Architect, audit, and orchestrate Agora Workbench MCP servers, loopback sidecars, unified state graphs, gateway\u002Fdispatcher connectors, and policy-enforced data lakes. Do not use for static frontend CSS styling or non-MCP desktop GUI automation.","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fagora-mcp-workbench-architect\u002FSKILL.md",[],[],{"skillNo":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":19},"01M7BFYG6QT3484VC57TZ19V7P","skill-eval-assurance-runner","Evaluate and assure agent skills using small-N Wilson confidence intervals, unbiased pass^k reliability, deterministic trajectory graders, preflight boundary honesty, and sealed digest verification. Do not use for subjective prose review or unconstrained production deployment.","https:\u002F\u002Fgithub.com\u002FSpectreDeath\u002FBrain-Harness\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fskill-eval-assurance-runner\u002FSKILL.md",[],[]]