Multi-Model AI Office Cost Control: Tiered Routing and Budget Alerts
This article describes a practical cost-control design for multi-model AI office platforms. It covers sensitivity-first task tiering, a unified quota formula based on token usage, model multipliers, output weight, and discount-window factors; schedulable discount-hour execution; budget alerts with throttling and circuit breaking; and Python routing and fallback code, monitoring metrics, troubleshooting, and rollback procedures. Example multipliers, factors, and budgets must be replaced with platform-published data and team-approved limits before production.
1. Conclusions and Scope
Cost control for multi-model access can be split into three parts: tiered routing by task complexity, a unified formula for calculating quota consumption, and constraints on spending through discount-window scheduling and budget alerts. The multipliers, time-window factors, and budget limits in this article are examples. Before launch, replace them with data published by the platform and limits set by the team.
The scope is as follows:
- It applies to text tasks on internal enterprise AI office platforms, such as email, summaries, reports, code, and data analysis.
- Tasks containing personal information or confidential content use only local or approved models and do not participate in external routing or discount-window scheduling.
- The design depends on the token usage fields and model invocation APIs returned by the platform. Without these APIs, quota cannot be calculated accurately.
2. Task Tiers and Model Selection
When selecting a model, check sensitivity tags first, then task type, and finally input length. The order must not be reversed: sensitivity checks take precedence over cost decisions. The table below is a reference framework.
| Task Type | Recommended Tier | Typical Input Length | Example Multiplier | Fallback Strategy |
|---|---|---|---|---|
| Email polishing, short-text summaries | Lightweight model | Under 500 tokens | 0.5 | Upgrade to general model if quality is insufficient |
| Daily Q&A, document summarization, creative writing | General model | 500 to 8,000 tokens | 1.0 | Switch to a same-tier backup model on timeout or error |
| Code generation, complex reasoning, data analysis | Reasoning model | Above 8,000 tokens, or high complexity | 3.0 | Fall back to general model on failure and flag for manual review |
| Tasks containing personal information or confidential content | Local or approved model | Unlimited | Priced by contract | External routing prohibited; fallback remains local or approved model |
The multipliers in the table only illustrate the calculation method and do not represent the real pricing of any platform.
3. How to Calculate Quota Consumption Multipliers
The unified formula is as follows. The result is kept to two decimal places and rounded up:
Quota consumption = ⌈ (input tokens + output tokens × output weight) ÷ 1000 × model multiplier × time-window factor ⌉
Definitions:
- Token basis: use the
prompt_tokensandcompletion_tokensreturned by the platform for accounting. Estimates based on character count are only for pre-call checks and are not included in billing. - Input and output are calculated separately: output weight reflects the amplification of output relative to input. The example uses 1.5; the actual value follows platform rules.
- Model multiplier: use the value published by the platform. The values in this article are examples only.
- Time-window factor: applies only to schedulable tasks within the discount window; otherwise it is 1.0.
- Rounding rule: round up so that budget checks do not underestimate actual consumption.
The following are three calculation examples:
- Lightweight model, input 300 tokens, output 200 tokens, multiplier 0.5, time-window factor 1.0. The result is (300 + 200 × 1.5) ÷ 1000 × 0.5 = 0.6 × 0.5 = 0.30.
- Reasoning model, input 9,000 tokens, output 2,000 tokens, multiplier 3.0, time-window factor 1.0. The result is (9,000 + 2,000 × 1.5) ÷ 1000 × 3.0 = 12 × 3.0 = 36.00.
- Same as example 2, but the task is schedulable and runs within the 00:00 to 08:00 discount window, with a time-window factor of 0.6. The result is 36.00 × 0.6 = 21.60.
These three numbers show that the cost of the same task changes with tier, output length, and time window. If you look only at unit price and ignore multipliers, output weight, and time-window factors, the budget will be systematically underestimated.
4. Routing and Fallback Code
Prerequisites:
- Python 3.9 or later. On Windows, install the
tzdatapackage so thatzoneinfoworks correctly. - The platform SDK provides
call_model(model, payload, timeout)andnotify(channel, text).timeoutis in seconds. A timeout raisesTimeoutError; other errors raiseModelError. - The service account can call only approved model IDs.
- Runtime parameters are loaded from the configuration center. The
RUNTIMEfields below correspond one-to-one with the configuration in section 5.
import loggingimport randomimport timefrom dataclasses import dataclassfrom datetime import datetime, time as dtime, timedeltafrom decimal import Decimal, ROUND_UPfrom zoneinfo import ZoneInfologger = logging.getLogger("ai_route")LITE = "Lite_Model_Fast"GENERAL = "General_Model"GENERAL_BACKUP = "General_Model_Backup"PRO = "Pro_Model_Reasoning"LOCAL = "Local_Model_Secure"LOCAL_BACKUP = "Local_Model_Secure_Backup"APPROVED_LOCAL = frozenset({LOCAL, LOCAL_BACKUP})SENSITIVE_TAGS = frozenset({"personal_info", "confidential"})SCHEDULABLE_TASKS = frozenset({"batch_summary", "weekly_report"})TZ = ZoneInfo("Asia/Shanghai") # Unified business timezone; example valueRUNTIME = {"routing_enabled": True,"discount_enabled": True,"throttle": False,"circuit_open": False,"timeout_seconds": 30,"max_retry": 2,}# Example values. Replace with platform-published data before launch.# LOCAL is priced by contract and is not in this table.MULTIPLIERS = {LITE: Decimal("0.5"), GENERAL: Decimal("1.0"), PRO: Decimal("3.0")}OUTPUT_WEIGHT = Decimal("1.5")DISCOUNT_WINDOW = (dtime(0, 0), dtime(8, 0))DISCOUNT_FACTOR = Decimal("0.6")ALERT_RULES = [(Decimal("0.70"), "notify", "70% used; notify the project owner"),(Decimal("0.90"), "throttle", "90% used; throttle high-complexity tasks"),(Decimal("1.00"), "circuit", "100% used; circuit-break all new tasks"),]ALERT_CHANNEL = "ops-ai-cost"_notified = set()class ModelError(Exception):"""Non-timeout model error, such as rate limiting, service unavailable, or content policy rejection."""class BudgetExceeded(Exception):"""Budget circuit breaker; reject all new tasks."""class ThrottledError(Exception):"""Reject high-complexity tasks during throttling; the caller should queue them."""class RouteFailed(Exception):"""Both primary and fallback models failed; manual handling is required."""@dataclass(frozen=True)class Route:primary: strfallback: strlevel: strsensitive: booldef classify_complexity(task_type, token_length):if token_length > 8000:return "high"if task_type in {"code_generation", "data_analysis", "logic_reasoning"}:return "high"if task_type in {"simple_text_polish", "short_summary"} and token_length < 500:return "low"return "medium"def decide_route(task):tags = task.get("tags", frozenset())# Sensitivity check runs first. The rollback switch must not bypass it.if tags & SENSITIVE_TAGS:return Route(LOCAL, LOCAL_BACKUP, "sensitive", True)if not RUNTIME["routing_enabled"]:return Route(GENERAL, GENERAL_BACKUP, "medium", False)level = classify_complexity(task["type"], task["tokens"])if level == "low":return Route(LITE, GENERAL, level, False)if level == "high":return Route(PRO, GENERAL, level, False)return Route(GENERAL, GENERAL_BACKUP, level, False)def log_route_event(task_id, primary, used, outcome, error_type):# Log only task ID, model name, outcome, and error type; never log input or output content.logger.info("route task_id=%s primary=%s used=%s outcome=%s error=%s",task_id, primary, used, outcome, error_type,)def call_with_retry(model, task):# Retry only timeouts on the same model with backoff. Other errors go directly to the fallback model.for attempt in range(RUNTIME["max_retry"] + 1):try:return call_model(model, task["payload"], timeout=RUNTIME["timeout_seconds"])except TimeoutError:if attempt == RUNTIME["max_retry"]:raisetime.sleep(min(2 ** attempt, 8) + random.uniform(0, 0.2))def call_with_fallback(task):if RUNTIME["circuit_open"]:raise BudgetExceeded("Budget circuit breaker is active; task was not executed")route = decide_route(task)if RUNTIME["throttle"] and route.level == "high":raise ThrottledError("Throttling is active; high-complexity tasks must be queued")last_error = Nonefor model in (route.primary, route.fallback):try:output = call_with_retry(model, task)except (TimeoutError, ModelError) as e:last_error = elog_route_event(task["id"], route.primary, model, "failed", type(e).__name__)continueused_fallback = model != route.primaryoutcome = "fallback" if used_fallback else "ok"log_route_event(task["id"], route.primary, model, outcome, None)return {"output": output,"model": model,"needs_review": used_fallback and route.level == "high",}# For sensitive tasks, the fallback is also limited to approved local models.# After failure, the task can only be routed to manual handling and must not be sent to an external model.raise RouteFailed(f"Task {task['id']} failed on both primary and fallback models") from last_errordef quota_cost(model, input_tokens, output_tokens, factor):units = (Decimal(input_tokens) + Decimal(output_tokens) * OUTPUT_WEIGHT) / Decimal(1000)cost = units * MULTIPLIERS[model] * factorreturn cost.quantize(Decimal("0.01"), rounding=ROUND_UP)def period_factor(now, task_type):if not RUNTIME["discount_enabled"] or task_type not in SCHEDULABLE_TASKS:return Decimal("1.0")start, end = DISCOUNT_WINDOWif start <= now.time() < end:return DISCOUNT_FACTORreturn Decimal("1.0")def next_run_time(task, now):"""If a schedulable task is outside the discount window, wait for the next window start."""if task["type"] not in SCHEDULABLE_TASKS or not RUNTIME["discount_enabled"]:return nowif period_factor(now, task["type"]) < Decimal("1.0"):return nowstart = DISCOUNT_WINDOW[0]candidate = now.replace(hour=start.hour, minute=start.minute, second=0, microsecond=0)if candidate <= now:candidate += timedelta(days=1)deadline = task.get("deadline")if deadline is not None and candidate > deadline:return now # The deadline cannot be met; run immediatelyreturn candidatedef check_budget(scope, used, limit):ratio = used / limithit = Nonefor threshold, action, message in ALERT_RULES:if ratio >= threshold:hit = (threshold, action, message)if hit is None:returnthreshold, action, message = hit# Notify only once per level, but throttling and circuit-breaker states apply every time.if (scope, threshold) not in _notified:notify(ALERT_CHANNEL, f"[{scope}] {message}; used {used}/{limit}")_notified.add((scope, threshold))if action == "throttle":RUNTIME["throttle"] = Trueelif action == "circuit":RUNTIME["circuit_open"] = Truedef reset_period():"""Call at the start of a daily or weekly period. Clear throttling and alert deduplication; keep circuit breaker unchanged, requiring manual release."""RUNTIME["throttle"] = False_notified.clear()if __name__ == "__main__":task = {"id": "t-001","type": "short_summary","tokens": 320,"payload": "sample input","tags": frozenset(),}result = call_with_fallback(task)print(result["model"], result["needs_review"])now = datetime.now(TZ)print(quota_cost(PRO, 9000, 2000, period_factor(now, "batch_summary")))
After running, each call in the log records the task ID, primary model, actual model, outcome, and error type. The log does not contain input or output content.
5. Discount-Window Scheduling and Budget Alerts
5.1 Scheduling Configuration Checklist
The following configuration corresponds to RUNTIME, DISCOUNT_WINDOW, and ALERT_RULES in the code. In production, load it from the configuration center and keep a version history.
routing:enabled: true # When disabled, non-sensitive tasks all use the general modeltimeout_seconds: 30 # Unit: secondsmax_retry: 2 # Retry timeouts onlydiscount:enabled: true # When disabled, no scheduling occurs and all tasks use factor 1.0timezone: Asia/Shanghaiwindow: "00:00-08:00"factor: 0.6 # Example valueschedulable_tasks: # Whitelist of schedulable tasks- batch_summary- weekly_reportbudget:channel: ops-ai-costscopes:day: 500 # Example value; set by finance or the project ownerweek: 3000 # Example valueproject: per-project configurationalerts: [0.7 notify, 0.9 throttle, 1.0 circuit]kill_switch:routing_enabled: truediscount_enabled: truecircuit_open: false # After circuit breaking, only the owner can change this manually
Scheduling rules are as follows:
- Only tasks in the whitelist can be delayed to the discount window.
- Sensitive tasks are not added to the whitelist and do not participate in time-window scheduling.
- Real-time tasks, such as polishing or Q&A that a user is waiting for, run immediately with a time-window factor of 1.0.
- If a schedulable task exceeds its deadline, it runs immediately and no longer waits for the window.
5.2 Budget Alert Rules
Budgets are tracked separately by day, week, and project. If any scope reaches a threshold, the corresponding action is executed.
| Threshold | Level | Action | Notify | Release Method |
|---|---|---|---|---|
| 70% | Reminder | Send notification; routing unchanged | Operations alert group | No release needed |
| 90% | Throttling | High-complexity tasks raise ThrottledError and are queued by the caller |
Alert group and project owner | Automatically released by calling reset_period at the start of the period |
| 100% | Circuit breaking | Reject all new tasks | Alert group, project owner, and finance | After the owner confirms the usage is genuine, manually set circuit_open to false |
The notification channel uses the team’s existing alert bot or ticketing system. Notification content includes only the scope, used quota, and limit; it does not include task content.
5.3 Failure Degradation Strategy
- Timeout: retry the same model with backoff twice. If it still fails, switch to the fallback model.
- Non-timeout errors such as rate limiting or service unavailable: switch directly to the fallback model without retrying.
- Fallback model also fails: raise
RouteFailed, and the task enters the manual queue. Sensitive tasks must not be switched to external models. - During circuit breaking: all tasks raise
BudgetExceeded; the caller records the event and waits for manual release.
6. Routing Monitoring Metrics
After launch, observe at least the following metrics. They can all be calculated from routing logs:
- Hit rate: number of tasks completed at the expected tier divided by total tasks.
- Fallback rate: number of tasks with outcome
fallbackdivided by total tasks. An example alert line is more than 10% for 15 consecutive minutes. - Timeout rate: number of
TimeoutErroroccurrences divided by model invocation count. - Quota per task: calculated separately by tier, equal to total quota consumption in the period divided by task count.
- Manual review volume: number of tasks with
needs_reviewset to True. - Throttling and circuit-breaking counts: used to judge whether budget limits are reasonable.
Metrics should be split by tier. Overall averages may hide degradation problems in the reasoning model.
7. Common Mistakes
- No sensitivity check, or the sensitivity check is placed after cost decisions. In the code, the sensitivity check must run first.
- Retries do not switch to fallback. After a timeout, staying on the same failing model slows down the entire chain.
- Logs record raw content. Routing logs should only record task ID, model name, outcome, and error type.
- Only unit price is considered, while multipliers, output weight, and time-window factors are ignored. The budget will be underestimated.
- There are no budget alerts, or alerts only send notifications without throttling or circuit breaking.
- The rollback switch bypasses the sensitivity check. When
routing.enabledis false, sensitive tasks must still use local or approved models. - Sensitive tags are filled in by users. Tags should come from the data classification service.
- The server timezone differs from the business timezone, causing incorrect discount-window decisions.
- After circuit breaking, no one releases it, or the code is modified to bypass the circuit breaker. Circuit-breaker release must be confirmed by the owner.
8. Troubleshooting Steps
- First distinguish routing issues from model issues. Check the
outcomeanderrorfields in the logs. If errors are mostlyTimeoutError, check model-side latency and whether the unit oftimeout_secondsis seconds. - If all tasks fall to the general model, check whether
routing.enabledis false. If so, confirm whether someone is performing a rollback. - If quota numbers are abnormal, verify that token fields come from the platform-returned
usage, not local estimates. Then verify whetherOUTPUT_WEIGHTmatches platform rules. - If the discount is not applied, check in order: whether the task type is in the whitelist, whether
discount.enabledis true, and whether the server timezone matchesTZ. - If an alert is received but no overage is visible, verify whether the period start of the scope matches the platform billing cycle.
- If the circuit breaker cannot recover, first confirm whether the used quota is genuine. After confirmation, the owner modifies
circuit_open; do not hard-code a bypass in the code. - If
RouteFailedpersists, check whether the fallback model is in the approved list and whether the service account has invocation permission.
9. Rollback Steps
Prefer switches over direct code changes for rollback. Perform the operations in the following order:
- First disable discount-window scheduling: set
discount.enabledto false. This takes effect immediately and does not affect routing. - If routing results are abnormal, set
routing.enabledto false. Non-sensitive tasks all use the general model, while sensitive tasks still use local or approved models. - If costs need to be paused, after owner confirmation set
circuit_opento true and notify relevant people. - If the configuration itself has a problem, roll back to the previous version in the configuration center and keep the change record.
- After rollback, sample 20 tasks to confirm that the
modelfield, quota field, and logs are normal. Then observe the fallback rate and quota consumption for 30 minutes.
Do not delete logs or quota records during rollback. These data are the basis for troubleshooting and reconciliation. After each rollback, confirm that sensitive tasks still use only local or approved models.
