889. Self-host or pay per token?
Why it matters Build versus buy is the most common cost question for an AI product. Utilisation, not the GPU price, usually decides it.
Compare running your own GPU with paying an API per token.
Write selfhost_vs_api(gpu_hourly_usd, tokens_per_s, utilization, api_usd_per_m).
- self-host cost per 1M tokens: gpu_hourly_usd / (tokens_per_s * 3600 * utilization) * 1e6
- break-even utilisation: the utilisation at which both cost the same, gpu_hourly_usd * 1e6 / (tokens_per_s * 3600 * api_usd_per_m). It can be above 1, which means self-hosting never wins.
- choice: "self-host" if the self-host cost is strictly lower than api_usd_per_m, else "api"
Inputs: positive floats; utilization is in (0, 1].
Return a dict {"selfhost_per_m": rounded to 4 decimals, "breakeven_utilization": rounded to 4 decimals, "choice": str}.
def selfhost_vs_api(gpu_hourly_usd, tokens_per_s, utilization, api_usd_per_m)Example 1
Input: selfhost_vs_api(2.0, 1500, 0.5, 0.6)
Output: {'selfhost_per_m': 0.7407, 'breakeven_utilization': 0.6173, 'choice': 'api'}
Example 2
Input: gpu_hourly_usd = 4.0, tokens_per_s = 2000, utilization = 0.2, api_usd_per_m = 1.0
Output: {'selfhost_per_m': 2.7778, 'breakeven_utilization': 0.5556, 'choice': 'api'}
Example 3
Input: gpu_hourly_usd = 1.0, tokens_per_s = 100, utilization = 1.0, api_usd_per_m = 1.0
Output: {'selfhost_per_m': 2.7778, 'breakeven_utilization': 2.7778, 'choice': 'api'}
Constraints
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
Tokens per hour = tokens_per_s * 3600 * utilization.
Hint 2
Break-even: set the self-host cost equal to the API price and solve for utilization.
Hint 3
Use a strict < for the choice.
Common mistakes
- Ignoring utilisation.
- Mixing per-1K and per-1M prices.
- Capping break-even at 1.
Understand the idea
A GPU costs the same per hour whether it is busy or idle, so the cost per token is the hourly price divided by the tokens it actually serves. At $2 an hour, 1500 tokens per second and 50 percent utilisation, you serve 2.7M tokens an hour, which is about $0.74 per million. If the API charges $0.60, you need about 62 percent utilisation to break even.
Shapes and data flow
Scalars in, dict out.