跳到正文
DEV Community· tanmay kumar chaurasia·· 2 小時前AI 評分52

模型路由:避免為簡單任務使用前沿 AI 模型而浪費預算

Model Routing: Stop Wasting Budget on Frontier AI Models for Easy Tasks

AI 導讀

文章介紹模型路由,按任務複雜度將請求交給合適的模型,對難度不確定的任務則先用低成本模型,並在驗證失敗時升級。文中稱這種做法可減少 50% 至 70% token 開支,並以 Python 範例示範靜態任務路由和動態升級。

正文

When building AI agents or integrating LLMs into backend services, a common mistake is sending every incoming request to the strongest model available.

Need to extract a date from a paragraph? Call GPT-4o or Claude 3.5 Sonnet. Need to classify a incoming support ticket into one of three categories? Call the frontier model again.

Running basic classification, extraction, or formatting tasks through an expensive reasoning model is the equivalent of hiring a principal architect just to reply to routine emails. It inflates your API bills, introduces unnecessary latency, and wastes compute budget that should be reserved for actual, complex logic.

The solution to this problem is model routing.

What is Model Routing?

Model routing is an architectural pattern where an application evaluates incoming requests and dynamically directs them to the most cost-effective model capable of handling the task.

Instead of treating your LLM provider as a single endpoint, you break your application tasks down into difficulty tiers:

  1. Tier 1 (Deterministic / Simple): JSON extraction, sentiment analysis, text classification, simple reformatting. Handled by fast, lightweight models like gpt-4o-mini, claude-3-haiku, or small open-source models.
  2. Tier 2 (Reasoning / High Stakes): Architecture design, complex code synthesis, multi-step planning, nuanced legal or financial analysis. Handled by frontier models.
  3. Dynamic / Escalation Tier: Tasks with uncertain difficulty. You run the query through a cheap model first, validate the response against predefined criteria, and escalate to a higher-tier model only if the initial output fails validation.

By routing traffic based on task complexity, teams routinely reduce token spend by 50% to 70% without sacrificing output quality.

Step 1: Static Task-Based Routing

The simplest way to implement model routing is at the workflow level. If your backend architecture relies on chain-of-thought workflows or discrete agent steps, assign specific models to specific functions.

Here is a practical Python example demonstrating task-based routing:

import os
from openai import OpenAI

client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

def classify_ticket(user_message: str) -> str:
    """Uses a cheap model for deterministic text classification."""
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {
                "role": "system",
                "content": "Classify the message into one category: BUG, BILLING, FEATURE, OTHER."
            },
            {"role": "user", "content": user_message}
        ],
        temperature=0.0
    )
    return response.choices[0].message.content.strip()

def generate_resolution_plan(user_message: str, category: str) -> str:
    """Uses a frontier model for complex problem solving."""
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[
            {
                "role": "system",content": "You are a senior technical support specialist. Draft a detailed resolution plan."
            },
            {"role": "user", "content": f"Category: {category}\nIssue: {user_message}"}
        ],
        temperature=0.2
    )
    return response.choices[0].message.content

Step 2: Dynamic Escalation Logic

Sometimes you cannot determine the difficulty of a user's prompt in advance. In these scenarios, implement an escalation pattern.

Run the request through your fast model first. Parse and validate the output programmatically (e.g., verifying structured JSON outputs, checking confidence scores, or running a secondary validation check). If validation fails, catch the error and route the prompt to the frontier model.

import json
from pydantic import BaseModel, ValidationError
from openai import OpenAI

client = OpenAI()

class ExtractedPayload(BaseModel):
    user_id: int
    action: str
    urgency: int

def extract_structured_data(raw_text: str) -> dict:
    """Tries a fast model first; falls back to a strong model if validation fails."""
    prompt = f"Extract payload from text as JSON: {raw_text}"

    # Attempt with cheap tier
    try:
        res = client.chat.completions.create(
            model="gpt-4o-mini",
            response_format={"type": "json_object"},
            messages=[{"role": "user", "content": prompt}],
            timeout=4.0
        )
        parsed = json.loads(res.choices[0].message.content)
        validated = ExtractedPayload(**parsed)
        return {"tier": "cheap", "data": validated.model_dump()}
    except (ValidationError, Exception):
        # Fallback to high-tier model upon failure or bad schema
        pass

    # Escalation to frontier tier
    res = client.chat.completions.create(
        model="gpt-4o",
        response_format={"type": "json_object"},
        messages=[{"role": "user", "content": prompt}]
    )
    parsed = json.loads(res.choices[0].message.content)
    validated = ExtractedPayload(**parsed)
    return {"tier": "frontier", "data": validated.model_dump()}

Best Practices for Routing Architecture

  • Set Strict Timeouts: When running dynamic escalation, configure low timeout thresholds for the fast model so a failure doesn't add high latency to the end user's experience.
  • Log Routing Decisions: Track how often your fallback logic triggers. If 95% of cheap-model attempts succeed, your threshold is well-tuned. If cheap models fail consistently on a specific prompt type, update your routing logic to bypass the cheap tier for that route.
  • Decouple Provider Code: Wrap model calls inside an abstraction layer or API gateway (like LiteLLM or custom backend services) so you can swap models without changing your application business logic.

Optimizing AI systems is rarely about waiting for cheaper foundation models to launch—it is about designing backend systems that use the right tool for each step of the pipeline.


About me: Tanmay builds AI agents and automation for businesses and is open to freelance projects. Feel free to connect with me on LinkedIn.

來源:DEV Community · dev.to