How to Choose Between Direct Model APIs, Cloud Providers, and Aggregation Platforms

    The same foundation model can have significantly different pricing depending on whether it is accessed through the official API, a cloud provider, or a third-party aggregation platform. This guide explains how to calculate real costs, compare availability, rate limits, compliance, and pricing, and implement multi-channel routing with retries and graceful degradation. It also covers caching, usage reconciliation, and practical rollout steps.

    1. Start by Understanding Your Token Usage

    Channel pricing is meaningful only when you know how many input and output tokens your application uses. For tasks such as text classification and information extraction, input tokens usually account for most of the usage. Agent applications, however, may repeatedly reason, reflect, and generate code, causing output tokens to significantly exceed input tokens.

    A 30% input and 70% output split is a common reference point, but it does not apply to every workload. Teams should calculate the ratio from their own request logs:

    1. Collect request logs from the past 7 to 30 days, aggregating input_tokens and output_tokens for each request.
    2. Calculate the output share as total output tokens divided by total input and output tokens.
    3. Calculate the ratio for each functional module, then combine the results using each module’s request volume as the weighting factor.

    Failed requests and automatic retries must be included in the calculation. Their tokens may also be billed.

    2. Cost Formulas: Include Caching and Exchange Rates

    First, standardize the billing unit. Some providers charge per thousand tokens, others per million tokens, and some charge per request. Convert all prices to RMB per million tokens. For request-based pricing, use the average number of tokens per request to calculate an equivalent rate.

    For overseas providers that charge in U.S. dollars, convert prices using a consistent exchange rate:

    1. RMB_Rate = USD_Rate × FX

    Use the exchange rate specified by your finance team and record the date on which it was applied in the cost report.

    For a rough comparison between two channels, you can use a blended rate:

    1. Blended_Rate = 0.3 × InRate + 0.7 × OutRate

    To estimate the actual bill, include input-token caching:

    1. Total_Cost = [InTok × (1 − h) × InRate + InTok × h × CacheRate + OutTok × OutRate] / 1,000,000

    Here, InTok and OutTok are the total input and output tokens, and h is the input-token cache hit rate. Caching applies only to input tokens. Output tokens do not receive a cache discount.

    Measure the cache hit rate as cached input tokens divided by total input tokens. Because usage field names differ across providers, verify the meaning of each field in the relevant API documentation.

    3. Example: Comparing Two Channels for the Same Workload

    The following figures are hypothetical and are used only to demonstrate the calculation method. They do not represent the actual prices of any provider.

    Suppose an Agent application processes 10 million tokens per day: 3 million input tokens and 7 million output tokens.

    • Channel A charges RMB 2 per million input tokens and RMB 8 per million output tokens. It does not offer a cache discount.
    • Channel B charges RMB 1.5 per million input tokens and RMB 6 per million output tokens. Cached input tokens cost RMB 0.3 per million, and the input cache hit rate is 40%.

    Channel A

    • Input: 3 million × RMB 2 per million = RMB 6
    • Output: 7 million × RMB 8 per million = RMB 56
    • Total: RMB 62 per day
    • Blended rate: approximately RMB 6.2 per million tokens

    Channel B

    • Uncached input: 3 million × 0.6 × RMB 1.5 per million = RMB 2.7
    • Cached input: 3 million × 0.4 × RMB 0.3 per million = RMB 0.36
    • Output: 7 million × RMB 6 per million = RMB 42
    • Total: RMB 45.06 per day
    • Blended rate: approximately RMB 4.51 per million tokens

    Channel B is RMB 16.94 cheaper per day, or approximately 27% cheaper.

    Two points are important here.

    First, output tokens account for most of the cost in this example. If Channel B did not provide caching, its daily cost would be RMB 4.5 plus RMB 42, or RMB 46.5. Caching saves only RMB 1.44, approximately 3%. The value of caching depends both on the hit rate and on whether most of the cost comes from input or output tokens.

    Second, retries and failures increase actual usage. If rate limiting on Channel B causes retries that increase token consumption by 10%, the daily cost rises to approximately RMB 49.57. It remains cheaper than Channel A, but the difference is much smaller. Channel selection should therefore be based on actual post-retry usage rather than ideal usage.

    4. Comparing the Three Channel Types

    Comparison area Direct official API Cloud provider hosting Third-party aggregation platform
    Pricing characteristics Often used as the baseline; promotional pricing may occasionally be very low Per-token pricing usually includes infrastructure costs Bulk purchasing may enable substantial discounts, but quotas and validity conditions may apply
    Rate limits and concurrency Depend on account tier; higher quotas may require an application Concurrency quotas can usually be configured, with monitoring and alerts Affected by upstream limits; request failures may be more likely during peak periods
    Availability guarantees Governed by the provider’s official service terms Usually offers clearer SLAs and multi-availability-zone deployment Enterprise-grade SLAs are less common and must be confirmed separately
    Network access Public network access by default; private connectivity requires separate evaluation Can often be accessed through a private network and integrated with storage, message queues, and other services Primarily accessed over the public network
    Data compliance Review data usage and retention terms Enterprise contracts and data processing agreements are generally available Requires careful review; terms may be less comprehensive
    Version availability New versions are generally released first Popular versions are usually made available relatively quickly Versions may lag behind or only lightweight versions may be offered
    API compatibility Many providers offer OpenAI-compatible or native APIs Most offer compatible APIs Most support the OpenAI request format

    These are common characteristics of each channel type. Actual terms and prices vary by provider and must be verified individually before production deployment.

    5. Acceptance Metrics and Weights

    Price is only one selection criterion. The following table lists common acceptance metrics. Adjust the weights according to business priorities. The thresholds shown are examples and should be defined for each workload.

    Dimension Acceptance metric Data source Example weight Action if the target is not met
    Unit cost Cost per million effective tokens recalculated from logs Billing records and request logs 30% Reduce the channel’s routing weight or stop sending requests to it
    Version availability The required model version can be called successfully through the channel Channel model list and test calls 20% Exclude the channel from routing if the version has no acceptable substitute
    Reliability Success rate of at least 99% and timeout rate no higher than 1% Gateway monitoring data 20% Switch to a backup channel
    Concurrency quota Peak QPS and token quotas meet load-testing targets Load-test report 15% Request a quota increase or add queuing at the gateway
    Compliance Data processing agreements, retention periods, and regional requirements meet policy Contracts and legal review 15% Prohibit the channel for workloads containing sensitive data

    Before selecting a channel, perform load tests and small-volume trial calls. Use a traffic distribution that reflects real requests to measure latency, success rate, and cost instead of evaluating providers only by their listed prices.

    6. Dynamic Routing: Code Example

    Multi-channel access is usually implemented in a unified LLM gateway. The following example demonstrates how to:

    • Rank channels by workload type
    • Filter channels by a per-request budget
    • Retry or degrade when rate limits or timeouts occur

    The send function is omitted. It is responsible for calling the actual API and returning usage information.

    1. import random
    2. import time
    3. from dataclasses import dataclass
    4. class RateLimitError(Exception):
    5. """The upstream provider returned a 429 or quota error."""
    6. @dataclass
    7. class Channel:
    8. name: str
    9. in_rate: float # RMB per million input tokens
    10. out_rate: float # RMB per million output tokens
    11. cache_rate: float # RMB per million cached input tokens
    12. p95_ms: float # P95 latency over the past 7 days
    13. compliant: bool # Whether the channel meets this workload's requirements
    14. @dataclass
    15. class Task:
    16. realtime: bool # Whether this is an interactive request
    17. sensitive: bool # Whether the request contains sensitive data
    18. in_tok: int
    19. out_tok: int
    20. hit_ratio: float # Cache hit rate for input tokens
    21. def estimate_cost(ch: Channel, t: Task) -> float:
    22. cached = t.in_tok * t.hit_ratio
    23. fresh = t.in_tok - cached
    24. return (fresh * ch.in_rate + cached * ch.cache_rate + t.out_tok * ch.out_rate) / 1_000_000
    25. class LLMRouter:
    26. def __init__(self, channels: list[Channel], max_retry: int = 2, budget: float | None = None):
    27. self.channels = channels
    28. self.max_retry = max_retry
    29. self.budget = budget # Per-request cost limit in RMB; None means unlimited
    30. def candidates(self, task: Task) -> list[Channel]:
    31. pool = [c for c in self.channels if c.compliant or not task.sensitive]
    32. if task.realtime:
    33. pool.sort(key=lambda c: c.p95_ms) # Prioritize latency for real-time traffic
    34. else:
    35. pool.sort(key=lambda c: estimate_cost(c, task)) # Prioritize cost for offline traffic
    36. if self.budget is not None:
    37. pool = [c for c in pool if estimate_cost(c, task) <= self.budget]
    38. return pool
    39. def call(self, task: Task, send):
    40. last_err = None
    41. for ch in self.candidates(task):
    42. for attempt in range(self.max_retry + 1):
    43. try:
    44. return send(ch.name, task) # send should return actual usage for billing reconciliation
    45. except RateLimitError as e:
    46. last_err = e
    47. time.sleep(min(8, 2 ** attempt) + random.random()) # Exponential backoff with jitter
    48. except TimeoutError as e:
    49. last_err = e
    50. break # Switch to the next channel on timeout
    51. return self.degrade(task, last_err)
    52. def degrade(self, task: Task, err):
    53. # Degradation: return a cached result for real-time traffic,
    54. # or queue offline traffic for a later retry.
    55. action = "fallback_cache" if task.realtime else "queue"
    56. return {"status": "degraded", "action": action, "reason": str(err)}

    The caller must inspect the return value. Under normal conditions, the result is the response from a channel. During degradation, the method returns a dictionary containing a status: degraded field.

    After the gateway goes live, the monitoring dashboard should record at least:

    • Channel name
    • Model version
    • Input tokens
    • Output tokens
    • Cached input tokens
    • Retry count
    • Error code
    • Cost per request

    These fields can be inserted into the formulas in Section 2 to automate daily billing reconciliation.

    7. Caching and Compliance Considerations

    Semantic caching can reduce the cost of repeated queries. The savings depend on the repetition rate. Before production deployment, replay approximately one week of real logs offline to measure the actual cache hit rate and answer quality. Do not simply reuse assumptions from another application.

    When using caching:

    • Include the tenant identifier in the cache key to prevent data from being shared between customers.
    • Before storing questions and answers that contain personal information or other sensitive content, anonymize them, or do not cache them.
    • Set the cache TTL to match the data-retention period specified in the applicable agreement.
    • Store the cache in storage controlled by the business so that it remains useful when the model channel changes.
    • Clear the cache associated with a model version when switching versions; otherwise, the system may return answers generated by the previous version.
    • When using an overseas channel, assess whether cross-border data transfers comply with applicable regulations and internal policies.
    1. Use logs to calculate the input/output token ratio, separately for each module.
    2. Build a daily cost report using the formulas in Section 2 and reconcile it against actual billing records.
    3. Load-test candidate channels and run small-volume trials, scoring them against the metrics in Section 5.
    4. Implement scenario- and weight-based routing at the gateway, with timeout, retry, and degradation policies.