# Multi-Model Integration and Credits-Based Billing: Engineering Practices for Office AI Agents
This article examines the engineering practices behind multi-model AI office agents, covering how they integrate multiple models behind a single agent, route tasks intelligently between them, meter usage through a unified credits system, and maintain stability. It walks through a five-layer decoupled architecture, a unified call contract, quality-versus-cost routing with retry and failover, a standardized credits billing formula, a rule-engine approach to time-windowed pricing, offline and online evaluation, observability, and security and compliance considerations. Readers will find concrete design references, configuration examples, and a practical implementation checklist for building enterprise-grade agent platforms.
AI office products are increasingly moving beyond a single in-house model to integrate several third-party models alongside their own, sometimes paired with temporary pricing incentives: users who call participating models during designated windows on workdays and holidays can enjoy reduced credits consumption, with a couple of models receiving time-limited reductions. From a product operations standpoint, this is a combined move of “expanding the model lineup plus a phased price cut.” From an engineering standpoint, it rests on a typical multi-model architecture:
- A single agent runs at the business layer, backed by multiple models with different capability profiles;
- Users are metered by credits, with models normalized against each other through per-model “weights”;
- Promotional activities require billing rules to be adjusted dynamically within designated time windows.
Using this as an entry point, this article discusses the general engineering practices that office agents rely on for multi-model integration, intelligent routing, credits metering, and reliability, and offers a design reference that can be implemented directly.
1. Background: Why Office Agents Move Toward Multiple Models
From “answering questions” to “delivering outcomes”
Traditional chat products center on single-turn Q&A, whereas office agents break down tasks around a user’s goal, invoke tools, execute across multiple steps, and ultimately deliver documents, spreadsheets, and presentations. A single “generate a weekly report” request may involve information retrieval, data aggregation, content drafting, and layout export. The number of calls is multiplied, the execution chain grows longer, and each step places different demands on capability, latency, and cost.
The core drivers for multi-model integration
- Heterogeneous capabilities: Different models have different strengths in long-context handling, complex reasoning, code generation, structured output, and tool-call adherence. A single model rarely performs optimally across every task.
- Clear task tiering: By frequency, most requests are “small, low-cost tasks” like rewriting, polishing, and summarization, while a minority are “high-value tasks” such as deep analysis and complex proposal writing. Paying for a top-tier model on every request is not economical.
- The need for supply redundancy: If a single model service is rate-limited, times out, or suffers a regional outage, the entire product is affected. Multiple models leave room for failover and canary switching.
- Users need choice: Giving users partial control over model selection lets people with different preferences and budgets find a configuration that suits them.
It is worth emphasizing that multi-model does not mean “more models is better.” Each new model adds adaptation, evaluation, metering, and operations costs. The prerequisite for integration is that the access layer is standardized enough.
2. Overall Architecture: Five-Layer Decoupling
A sustainable, evolvable multi-model agent architecture can be divided into five layers:
- Unified access layer (API gateway): Handles authentication, tenant identification, rate limiting, and an audited entry point. It exposes one internal interface to the layers above so that business code never depends directly on any specific model.
- Protocol adapter layer (Adapter): Normalizes differences across models—message structure, tool calling, generation parameters, streaming chunks, and error codes—into a single internal model.
- Routing layer (Router): Selects an executor from the candidate models based on task profile, quality requirements, and budget constraints, and handles retries and failover.
- Credits and metering layer: Records the model, input/output usage, applied weight, and credits deducted for each call, providing a unified basis for quota limits and promotions.
- Observability layer: Collects metrics such as latency, success rate, and per-task credits consumption, and connects full-chain tracing.
User request│▼[Access layer] Auth / rate limit / tenant & plan identification│▼[Agent orchestration layer] Task planning / tool calling / context management│ Unified call contract AgentCall / AgentResponse▼[Routing layer] Task tiering → candidate filtering → quality × cost scoring → retry & failover│ ▲▼ │ Health status / eval scores / weights[Adapter layer] Model A Model B Model C … (vendor SDKs)│▼[Credits & metering layer] Usage capture → weight calculation → promo evaluation → quota deduction → billing│▼[Observability layer] Metrics / logs / tracing / alerts
3. Unified Access Layer: Hiding Model Differences
The key to a multi-model architecture is whether business code can be “written once.” For that, you need a stable internal call contract:
- Input normalization: Unify message roles, the reference format for multimodal fragments (images, files, etc.), and where the system prompt is injected.
- Output normalization: Unify the representation of plain text, tool calls (function name + JSON arguments), and structured output (e.g., generation constrained by a JSON Schema).
- Parameter normalization: Whitelist-map generation parameters such as temperature, maximum output length, and stop conditions. Parameters a model does not support should be safely ignored rather than raising an error.
- Streaming normalization: Unify the types of incremental events (text delta, tool-call delta, end event) so the upper layers do not have to handle each model separately.
- Error semantics: Map rate limiting, timeouts, context overflow, content-safety blocks, and server errors into a finite set of internal error codes, so the routing layer can decide whether to retry or fail over.
- Usage standardization: Uniformly capture input tokens, output tokens, cache-hit input tokens, as well as the number of tool calls and retrievals.
from dataclasses import dataclass, field@dataclassclass AgentCall:messages: list[dict] # Normalized context messagestask_type: str # Task type, e.g. chat / write / code / summarizequality_tier: str = "standard" # standard / high, decided by user plan and tasktools: list[dict] = field(default_factory=list)max_output_tokens: int = 2048budget_weight: float = 1.0 # Highest allowed consumption weightstream: bool = Truetrace_id: str = "" # Full-chain tracing identifier@dataclassclass AgentResponse:text: strtool_calls: list[dict] # Unified format: {"name": ..., "arguments": {...}}usage: dict # {"input_tokens": ..., "output_tokens": ..., "cached_input_tokens": ...}model_id: str # Model actually used, for metering and attributionadapter: str # Adapter version usedfinish_reason: str # stop / length / tool_calls / content_filtered
Tool calling is where differences concentrate most. Some models natively support function calling, while others can only parse a text convention. The adapter layer needs to establish clear conventions:
- After a call fails, pass the error information back as the tool result so the model can correct itself;
- Cap the number of tool calls in a single round;
- Require user confirmation for side-effecting operations like writing files or sending emails, to prevent runaway loops.
def run_tool_loop(task: AgentCall, max_rounds: int = 6) -> AgentResponse:messages = task.messagesfor _ in range(max_rounds):resp = dispatch(task, messages) # dispatch internally handles routing, calling and meteringmessages.append({"role": "assistant", "content": resp.text, "tool_calls": resp.tool_calls})if not resp.tool_calls:return respfor call in resp.tool_calls:try:result = TOOL_REGISTRY[call["name"]](**call["arguments"])except Exception as exc: # Feed tool errors back to the model so it can retry or change pathresult = {"error": str(exc)}messages.append({"role": "tool", "name": call["name"], "content": str(result)})raise RuntimeError("Tool call rounds exceeded the limit")
4. Task Routing: Balancing Quality and Cost
1. Four bases for routing
- Task type and complexity: Can be estimated using rules (text length, whether code is involved, number of tools), heuristic features, or a lightweight classifier, without an extra call to a large model.
- Quality tier: Free or basic plans default to a cost-effective tier; paid or high-stakes tasks can use a more capable tier.
- Real-time status: Each model’s current health, rate-limit state, time-to-first-token, and historical error rate.
- Budget constraints: The user’s remaining credits, the per-task budget cap, and the model’s current consumption weight.
2. Scoring and selection
You can rank candidate models with a weighted “quality score × cost coefficient” approach that balances effectiveness and spend:
score(m) = quality(m, task_type, quality_tier) × (base_weight / weight(m))
Here, weight(m) is model m’s current consumption weight, and base_weight is the baseline weight. When quality is comparable, a model with a lower weight (cheaper) scores higher; on hard tasks, the quality term dominates and a more capable model tends to win. quality can come from offline evaluation results, or from online human ratings and user feedback sampled per task tier.
3. Retry and failover
RETRYABLE = {"rate_limited", "timeout", "server_error"}def dispatch(task: AgentCall, messages: list[dict]) -> AgentResponse:candidates = rank_candidates(task) # Sorted by score, filtering out models over budgetlast_error = Nonefor model in candidates:for attempt in range(2): # At most two tries per candidatetry:resp = ADAPTERS[model.adapter].invoke(model, task, messages)METRICS.record_success(model, task.task_type)return respexcept AdapterError as exc:if exc.code in {"context_length_exceeded"}:messages = trim_context(messages) # Compress context and retry on the same modelcontinueif exc.code not in RETRYABLE:raise # e.g. content-safety blocks; failing over is pointlesslast_error = exctime.sleep(backoff(attempt)) # Exponential backoff to ease rate limitingREGISTRY.mark_unhealthy(model) # Temporarily remove after consecutive failuresraise AllModelsFailed(last_error)
A few engineering notes:
- Switching models should not lose the session context. Prefer candidates with a compatible context window, and summarize or compress history when necessary.
- Output already produced should be metered separately to avoid double deduction.
- Every failure should leave a structured record for attribution.
4. Configuration example
Model capability profiles, plan mappings, and budget caps are best managed as configuration files or via a configuration center, so they can be adjusted without a redeploy:
models:lite:adapter: adapter_v2weight: 0.5 # Base consumption weight; lower means more tasks per creditmax_context: 128000supports_tools: truetiers: [standard]pro:adapter: adapter_v2weight: 1.0max_context: 256000supports_tools: truetiers: [standard, high]tiers:standard:budget_weight: 1.0 # Standard tier only allows models with weight <= 1.0high:budget_weight: 2.0 # High-value tasks may call higher-weight modelstask_routing:chat: { prefer: [lite, pro] }summarize: { prefer: [lite, pro] }write: { prefer: [lite, pro] }code: { prefer: [pro, lite] }
5. Credits Metering: Making Cost Quantifiable and Explainable
1. A unified billing formula
Credits are a unified unit of measure from the user’s perspective, and different models are normalized onto the same scale through consumption weights. A reference formula:
tokens_billed = input_tokens + output_weight × output_tokens − cached_discount × cached_input_tokenscost = ceil(tokens_billed × model_weight × promo_weight / billing_unit)
- output_weight: Reflects that output tokens typically consume more compute than input tokens;
- cached_discount: A discount on cache-hit inputs, encouraging the upper layers to reuse system prompts and document content;
- billing_unit: The billing granularity, such as one billing unit per 1,000 tokens or per 10,000 tokens;
- promo_weight: The promotion coefficient, normally 1.0 and less than 1.0 during promotional windows or limited-time activities.
The responsibilities across the pipeline:
- Metering events are reported by the execution side, buffered through a message queue to absorb spikes, and settled asynchronously;
- Estimated credits are used for pre-request budget checks;
- Actual credits are settled after the call finishes;
- The whole flow is correlated by trace_id to guarantee idempotency and reconcilability.
2. Clear boundaries for free usage
“Simple, low-cost tasks are free” needs to translate into executable rules, for example:
- The task type belongs to lightweight interaction (such as single-turn Q&A or short-text polishing);
- The estimated consumption of a single call does not exceed a set threshold;
- The number of free calls per calendar day is capped.
A free policy with fuzzy boundaries is easy to abuse and tends to create a gap with user expectations.
3. Quotas and abuse prevention
- Pre-request estimation: Estimate consumption from context length and expected output length. When it exceeds the limit, return a clear message directly without issuing a model call, saving cost and improving experience.
- Multi-window limits: Set credit caps at three granularities simultaneously—“per request,” “per hour,” and “per day”—to handle both burst demand and long-term abuse protection.
- Anomaly detection: Detect and throttle behaviors such as high-frequency calls in a short window and abnormal single-call context inflation.
- Reserve and settle: Under high concurrency, reserve credits before execution and release the reservation on failure, avoiding credits being “double-spent.”
6. Promotional Windows: Driving Dynamic Billing with a Rule Engine
A limited-time promotion is essentially a set of billing rules that take effect “by date, by model, by time window.” If these are hard-coded into business logic, every adjustment requires a redeploy and is error-prone. A better approach is to extract a rule engine and evaluate it uniformly during credit calculation.
{"version": 3,"effective_from": "2026-01-01T00:00:00+08:00","effective_to": "2026-03-31T23:59:59+08:00","timezone": "Asia/Shanghai","calendar": {"workdays": [1, 2, 3, 4, 5],"holidays": ["2026-02-17", "2026-02-18", "2026-02-19"]},"windows": [{"name": "workday_offpeak", "days": "workdays", "start": "20:00", "end": "23:59", "promo_weight": 0.5, "models": ["lite", "pro"]},{"name": "holiday_offpeak", "days": "holidays", "start": "10:00", "end": "23:59", "promo_weight": 0.5, "models": ["lite", "pro"]}],"limited_discount": {"models": {"lite": {"weight": 0.25},"pro": {"weight": 1.0}},"effective_to": "2026-03-31T23:59:59+08:00"}}
def resolve_weight(model: str, ts: datetime, cfg: dict) -> float:rules = cfg["limited_discount"]["models"]weight = rules.get(model, {}).get("weight", REGISTRY.base_weight(model)) # Limited-time weight takes precedencelocal = ts.astimezone(ZoneInfo(cfg["timezone"]))key = local.strftime("%Y-%m-%d")if key in cfg["calendar"]["holidays"]:day_type = "holidays"else:day_type = "workdays" if local.weekday() < 5 else "weekends"if cfg["effective_from"] <= local.isoformat() <= cfg["effective_to"]:for w in cfg["windows"]:if w["days"] == day_type and w["start"] <= local.strftime("%H:%M") <= w["end"] \and model in w["models"]:weight *= w["promo_weight"]breakreturn weight
A few design points are worth noting:
- Maintain the holiday calendar separately: Cases like rescheduled working days on weekends need a manually maintained calendar and cannot be judged simply as “Monday to Friday.”
- Use server time as authoritative: Client clocks can be tampered with, so all window judgments should happen on the server.
- Stack rules rather than overwrite them: If both a “limited-time weight reduction” and a “time-window discount” exist, they should generally multiply. For example, a model with a base weight of 1.0 reduced to 0.5 for a limited time, then combined with a 0.5 window discount, ends at a final weight of 0.25—which can be written directly as 0.25 in the configuration so users can understand it easily.
- Effective boundaries: Use the actual execution time of the request. A long task spanning windows can be calculated by its start time, but this must be stated clearly in the rule documentation to avoid billing disputes.
- Version traceability: Every metering record should store the rule version and calculation process used, for reconciliation and appeal review.
- Configuration first: Promotional rules should be configured, reviewed, and canaried in advance, with an effective time set, and preloaded by a scheduled task, so that a config-fetch failure at the moment of activation does not fall back to old rules.
7. Continuous Evaluation of Quality and Cost
One risk of a multi-model architecture is that the routing strategy silently “degrades”: after a new model is integrated or a weight is adjusted, routing sacrifices effectiveness to save money. You therefore need an evaluation system that combines offline and online methods.
1. Offline evaluation
Build evaluation sets per task type, maintaining a reference answer or scoring rubric for each sample. Metrics include:
- Answer correctness rate and format compliance rate;
- Tool-call success rate;
- Average latency and P95 latency;
- Average credits consumed per task.
def evaluate(case, model):resp = dispatch(build_call(case), case.messages)return {"task_type": case.task_type,"model": resp.model_id,"score": score_answer(case, resp.text), # Rule matching or model review"format_ok": validate_schema(case, resp),"cost": resp.usage["input_tokens"] + resp.usage["output_tokens"],}# Before a new model or routing strategy goes live, it must reach the baseline on the eval set before scaling up
2. Online evaluation
- Champion/challenger canary: Roll out a new routing strategy to a small share of traffic first, comparing adoption rate, retry rate, and user feedback against the current strategy.
- Stratified sampling with human review: Sample by task type, plan, and model to avoid averages masking regressions in specific scenarios.
- An explainable cost dashboard: Break down credits consumption by user, department, model, and task type to help teams locate the biggest cost drivers.
8. Observability and Reliability
- Full-chain tracing: Use trace_id to link “user request → task orchestration → model call → credit settlement,” so the full path can be reconstructed even when a single task crosses multiple models.
- Core metrics: Success rate, time-to-first-token, end-to-end latency, per-task credits consumption, cache-hit rate, and failover rate for each model.
- Tiered alerts: Automatically alert when error rate or latency exceeds a threshold for a sustained period; automatically reduce weight or temporarily remove a model when it becomes unavailable; trigger manual review on abnormal credit consumption.
- Rate limiting and circuit breaking: Rate limit by tenant and model at the access layer so that a single user’s burst traffic does not affect the overall service.
- Cost budgets: Set budget caps per business line and per plan, with multi-level warnings.
9. Security, Privacy, and Compliance
- Data minimization: Send only the context necessary for the current task to the model service, and desensitize sensitive information such as ID and bank card numbers before transmission.
- Data boundaries across providers: Integrating third-party models means data flows to multiple providers. Their respective data usage and retention policies must be clarified during architecture design and clearly communicated to users at the product level.
- Prompt injection defense: Office agents need to read external documents and web pages, and this untrusted content may carry malicious instructions. System prompts should be clearly isolated from external content, and highly sensitive operations must be confirmed by the user.
- Content safety: Bidirectional review of inputs and outputs, used together with tool-call permission controls.
- Audit trails: Keep auditable logs for critical operations; the logs themselves must also be desensitized and given a retention period.
10. Implementation Checklist
- Define the contract first: Unify the call interface and error codes so the business layer never depends directly on any specific model.
- Then build routing: Keep rules simple before complex, starting from “task type + plan” and gradually adding health and quality scores.
- Instrument metering early: Place metering points when integrating the first model, to avoid backfilling data later.
- Externalize configuration: Move the model list, plan mappings, weights, and promotion rules entirely into configuration, with support for version rollback.
- Back it with evaluation: New models and strategies must pass offline evaluation before launch and be continuously sampled and monitored afterward.
- Balance stability and compliance: Design failover, rate limiting and circuit breaking, desensitization, and prompt injection defense in tandem.
Conclusion
When an AI office product integrates multiple models and launches a limited-time promotion, it looks on the surface like “more model choices and lower usage cost,” but what it really tests is the platform’s multi-model engineering capability:
- Use a unified access layer to smooth over model differences;
- Use intelligent routing to balance quality and cost;
- Use credits metering to make consumption transparent and auditable;
- Use a rule engine to make promotions flexible and controllable;
- Use evaluation and observability systems to ensure long-term stability.
For teams building enterprise-grade agent platforms, what is truly worth borrowing is not how many models are integrated, but this “replaceable, meterable, and controllable” architectural approach. Models will keep iterating, and prices and promotions will keep changing; only when the architecture stays stable can the product continuously find the optimal balance among effectiveness, cost, and experience.
