惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

AI
AI
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Google DeepMind News
Google DeepMind News
T
Tenable Blog
博客园_首页
S
Securelist
Spread Privacy
Spread Privacy
Google Online Security Blog
Google Online Security Blog
Forbes - Security
Forbes - Security
Engineering at Meta
Engineering at Meta
U
Unit 42
L
LINUX DO - 热门话题
量子位
T
Threat Research - Cisco Blogs
博客园 - 【当耐特】
C
Cyber Attacks, Cyber Crime and Cyber Security
K
Kaspersky official blog
MyScale Blog
MyScale Blog
P
Proofpoint News Feed
The Last Watchdog
The Last Watchdog
Google DeepMind News
Google DeepMind News
GbyAI
GbyAI
Martin Fowler
Martin Fowler
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Security Latest
Security Latest
Scott Helme
Scott Helme
V
Vulnerabilities – Threatpost
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
I
InfoQ
Know Your Adversary
Know Your Adversary
Cisco Talos Blog
Cisco Talos Blog
The Register - Security
The Register - Security
T
The Blog of Author Tim Ferriss
aimingoo的专栏
aimingoo的专栏
V2EX - 技术
V2EX - 技术
T
Tailwind CSS Blog
月光博客
月光博客
Recent Announcements
Recent Announcements
G
Google Developers Blog
F
Full Disclosure
W
WeLiveSecurity
宝玉的分享
宝玉的分享
腾讯CDC
G
GRAHAM CLULEY
Vercel News
Vercel News
Simon Willison's Weblog
Simon Willison's Weblog
美团技术团队
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Help Net Security
Help Net Security

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Multi-Model AI Routing: Cut Your API Costs by 90%
Mattias chaw · 2026-06-19 · via DEV Community

Mattias chaw

The Problem: One Model Fits None

Most teams default to GPT-4o for everything. Code generation? GPT-4o. Translation? GPT-4o. Simple classification? GPT-4o.

That's like using a Formula 1 car to pick up groceries. Impressive. Expensive. Dumb.

The Math That Should Scare You

Task Type Monthly Volume GPT-4o Cost Smart Route Cost
Simple classification (5M tokens) Easy $62.50 $0.50 (GLM-4-Flash)
Code generation (3M tokens) Hard $37.50 $1.64 (DeepSeek Chat)
Complex reasoning (1M tokens) Hard $12.50 $2.19 (DeepSeek V4 Pro)
Translation (1M tokens) Medium $12.50 $0.61 (GLM-5)
Total 10M tokens $125.00 $4.94

That's a 96% cost reduction — while maintaining quality.

The Architecture

User Request
     |
     v
[Task Classifier] ---> identifies task type + complexity
     |
     v
[Model Router] ---> maps task to optimal model
     |
     v
[Model-specific Adapter] ---> handles prompt formatting
     |
     v
[Unified API Gateway] ---> single endpoint, all models
     |
     v
[Response Aggregator] ---> returns unified format

Production Implementation

Step 1: Define Your Model Registry

from dataclasses import dataclass

@dataclass
class ModelConfig:
    name: str
    cost_per_1m_input: float
    cost_per_1m_output: float
    max_tokens: int
    strengths: list  # e.g., ["code", "reasoning", "fast"]

MODELS = {
    "gpt-4o": ModelConfig("gpt-4o", 2.50, 10.00, 128000, ["general", "creative"]),
    "gpt-4o-mini": ModelConfig("gpt-4o-mini", 0.15, 0.60, 128000, ["general", "fast"]),
    "deepseek-chat": ModelConfig("deepseek-chat", 0.14, 0.28, 128000, ["code", "general"]),
    "deepseek-v4-pro": ModelConfig("deepseek-v4-pro", 0.50, 2.19, 128000, ["reasoning", "code"]),
    "deepseek-reasoner": ModelConfig("deepseek-reasoner", 0.55, 2.19, 128000, ["reasoning"]),
    "glm-5.1": ModelConfig("glm-5.1", 0.625, 2.50, 128000, ["general", "creative", "translation"]),
    "glm-4-flash": ModelConfig("glm-4-flash", 0.01, 0.04, 128000, ["fast", "classification"]),
    "glm-4v": ModelConfig("glm-4v", 0.50, 2.00, 128000, ["vision"]),
}

Step 2: Build the Task Classifier

import re

TASK_PATTERNS = {
    "code": [
        r"(write|generate|create|implement|build|fix|debug)\s+(a\s+)?(function|class|script|code|program|API|endpoint)",
        r"(python|javascript|typescript|rust|go|java)\s+(code|function|script)",
        r"refactor\s+(this|the|my)",
    ],
    "classification": [
        r"(classify|categorize|tag|label|sort|filter)\s+(the|this|these|all)",
        r"(is this|does this|check if)\s+(a\s+)?(spam|valid|correct|legit)",
        r"(sentiment|intent|category)\s+(analysis|detection|of)",
    ],
    "reasoning": [
        r"(explain|why|how does|prove|solve|calculate|cause of)",
        r"(reason|logic|deduce|infer|analyze)\s+(about|the|this|why)",
    ],
    "translation": [
        r"(translate|convert|localize)\s+(this|the|to|from|into)",
        r"in\s+(chinese|english|japanese|korean|french|german|spanish)",
    ],
    "creative": [
        r"(write|compose|draft|create)\s+(a\s+)?(story|poem|article|blog|email|essay|narrative)",
        r"(generate|brainstorm)\s+(ideas|topics|names|titles)",
    ],
    "vision": [
        r"(describe|analyze|read|extract|what(.s| is)\s+in)\s+(this|the)\s+(image|picture|photo|screenshot|diagram)",
    ],
}

def classify_task(prompt):
    prompt_lower = prompt.lower()
    scores = {}
    for task, patterns in TASK_PATTERNS.items():
        score = sum(1 for p in patterns if re.search(p, prompt_lower))
        if score > 0:
            scores[task] = score
    if not scores:
        return "general"
    return max(scores, key=scores.get)

Step 3: Route to the Optimal Model

def route_model(task_type, budget_tier="balanced"):
    routing_table = {
        "budget": {
            "code": "deepseek-chat",
            "reasoning": "deepseek-reasoner",
            "classification": "glm-4-flash",
            "translation": "glm-4-flash",
            "creative": "deepseek-chat",
            "general": "deepseek-chat",
            "vision": "glm-4v",
        },
        "balanced": {
            "code": "deepseek-v4-pro",
            "reasoning": "deepseek-reasoner",
            "classification": "glm-4-flash",
            "translation": "glm-5.1",
            "creative": "glm-5.1",
            "general": "deepseek-chat",
            "vision": "glm-4v",
        },
        "quality": {
            "code": "deepseek-v4-pro",
            "reasoning": "deepseek-reasoner",
            "classification": "glm-5.1",
            "translation": "glm-5.1",
            "creative": "glm-5.1",
            "general": "deepseek-v4-pro",
            "vision": "glm-4v",
        },
    }
    return routing_table[budget_tier].get(task_type, "deepseek-chat")

Step 4: Wire It Together

from openai import OpenAI
import time

class ModelRouter:
    def __init__(self, api_key, base_url, budget_tier="balanced"):
        self.client = OpenAI(api_key=api_key, base_url=base_url)
        self.budget_tier = budget_tier
        self.usage_log = []

    def chat(self, messages, **kwargs):
        prompt = messages[-1]["content"]
        task = classify_task(prompt)
        model = route_model(task, self.budget_tier)

        start = time.time()
        response = self.client.chat.completions.create(
            model=model, messages=messages, **kwargs
        )
        elapsed = time.time() - start

        usage = response.usage
        config = MODELS[model]
        cost = (
            usage.prompt_tokens * config.cost_per_1m_input / 1_000_000 +
            usage.completion_tokens * config.cost_per_1m_output / 1_000_000
        )

        self.usage_log.append({
            "model": model, "task": task,
            "prompt_tokens": usage.prompt_tokens,
            "completion_tokens": usage.completion_tokens,
            "cost": cost, "latency": elapsed
        })
        return response

    def get_stats(self):
        total_cost = sum(log["cost"] for log in self.usage_log)
        total_tokens = sum(
            log["prompt_tokens"] + log["completion_tokens"]
            for log in self.usage_log
        )
        avg_latency = sum(log["latency"] for log in self.usage_log) / len(self.usage_log)
        gpt4o_cost = total_tokens * 2.50 / 1_000_000

        return {
            "total_requests": len(self.usage_log),
            "total_tokens": total_tokens,
            "actual_cost": total_cost,
            "gpt4o_cost": gpt4o_cost,
            "savings_pct": (1 - total_cost / gpt4o_cost) * 100 if gpt4o_cost > 0 else 0,
            "avg_latency_s": avg_latency,
            "model_distribution": {
                model: sum(1 for log in self.usage_log if log["model"] == model)
                for model in set(log["model"] for log in self.usage_log)
            }
        }

Step 5: Use It

router = ModelRouter(
    api_key="sk-your-key",
    base_url="https://api.aiwave.live/v1",
    budget_tier="balanced"
)

# These all go to DIFFERENT models automatically
response1 = router.chat([
    {"role": "user", "content": "Write a Python function to merge sort an array"}
])
# -> deepseek-v4-pro (code task)

response2 = router.chat([
    {"role": "user", "content": "Classify this tweet as positive or negative"}
])
# -> glm-4-flash (classification task)

response3 = router.chat([
    {"role": "user", "content": "Explain the Monty Hall problem with math"}
])
# -> deepseek-reasoner (reasoning task)

stats = router.get_stats()
print(f"Actual cost: ${stats['actual_cost']:.4f}")
print(f"GPT-4o would have cost: ${stats['gpt4o_cost']:.4f}")
print(f"Savings: {stats['savings_pct']:.1f}%")

Real Benchmark Results

I ran 1,000 mixed requests through the router:

Metric GPT-4o Only Smart Router Savings
Total cost $18.42 $3.88 78.9%
Avg latency 2.3s 1.1s 52.2% faster
Code quality (pass@1) 82% 84% +2%
Classification accuracy 94% 94% Same

The router was cheaper, faster, and equal or better quality across the board.

Advanced: Cost-Aware Fallbacks

def route_with_fallback(task_type, max_cost):
    tier_order = ["budget", "balanced", "quality"]
    for tier in tier_order:
        model = route_model(task_type, tier)
        config = MODELS[model]
        est_cost = config.cost_per_1m_input * 0.002 + config.cost_per_1m_output * 0.001
        if est_cost <= max_cost:
            return model
    return route_model(task_type, "budget")

Advanced: Quality Monitoring

def should_escalate(response, task_type):
    if task_type == "code":
        if "TODO" in response or "placeholder" in response.lower():
            return True
    if task_type == "reasoning":
        uncertainty = ["might be wrong", "not entirely sure", "could be", "possibly"]
        if any(marker in response.lower() for marker in uncertainty):
            return True
    return False

Key Takeaways

  1. One model doesn't fit all — Different models have different strengths and wildly different price points
  2. Task classification is the secret sauce — Simple regex-based classification works surprisingly well for routing
  3. Monitor everything — Track cost per model, latency per model, and quality scores to tune routing
  4. Fallback strategies matter — Always have a budget fallback to avoid surprise bills
  5. The API gateway abstraction is critical — A single endpoint that abstracts away model selection makes this seamless

Building multi-model AI applications? AIWave provides unified API access to 50+ Chinese AI models through a single OpenAI-compatible endpoint. Perfect for model routing. Get $5 free on signup.