AiCredits
Cost Control

How to Budget for AI API Costs as a Solo Founder (Without Guesswork)

A practical system for budgeting AI API costs as a solo founder: a token ledger, hard daily caps, two-tier model routing, and the metrics that predict your bill.

Published 2026-10-10 Updated 2026-10-10 9 min

Why Solo Founders Blow Their AI Budget

The bill rarely explodes because you picked an expensive model. It explodes because nothing in your code notices what you're spending. A retry loop, an unbounded output, a nightly job that reprocesses the same documents — any of those can quietly become your biggest line item while model choice accounts for pocket change.

You have no finance team and no platform engineer, so the budget has to live in the code. Here's a working system: a token ledger, a hard daily cap, two-tier routing, and the metrics that tell you whether next month gets better or worse.

Step 1: Instrument Every Call Before You Optimize Anything

You can't budget what you don't count. Wrap the client once, and every call writes a row to a local ledger. Note that cached prompt tokens are recorded separately — cache hits are cheaper, so you want to see how much of your prompt volume is actually being served from cache. The weight values are yours to set from the current rates; the bookkeeping works with any numbers.

import json
import os
import time
from datetime import date
from pathlib import Path

from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AICREDITS_API_KEY"],
    base_url="https://api.aicreditsapi.com/v1",
)

LEDGER = Path("usage_ledger.jsonl")

# Relative cost weights: set these yourself from the current rates page.
# The bookkeeping code works with any values here.
MODEL_WEIGHT = {"deepseek-v4-flash": 1.0, "deepseek-v4-pro": 3.0}

SYSTEM_PROMPT = (
    "You are a concise assistant for a small SaaS product. "
    "Answer in plain text with no preamble."
)


def call_model(messages, tier="flash", max_tokens=400, temperature=0.2):
    model = "deepseek-v4-flash" if tier == "flash" else "deepseek-v4-pro"
    resp = client.chat.completions.create(
        model=model,
        messages=messages,
        max_tokens=max_tokens,
        temperature=temperature,
    )
    usage = resp.usage
    details = getattr(usage, "prompt_tokens_details", None)
    cached = getattr(details, "cached_tokens", 0) if details else 0
    billable_prompt = usage.prompt_tokens - cached
    row = {
        "ts": time.time(),
        "model": model,
        "prompt_tokens": usage.prompt_tokens,
        "cached_prompt_tokens": cached,
        "completion_tokens": usage.completion_tokens,
        "weighted_units": MODEL_WEIGHT[model] * (billable_prompt + usage.completion_tokens),
    }
    with LEDGER.open("a") as fh:
        fh.write(json.dumps(row) + "\n")
    return resp.choices[0].message.content

Two details matter. One wrapper means one place to change, so you never chase call sites. And JSONL is cheap storage — you can grep it, load it in a notebook, or ship it to analytics later without a warehouse.

Step 2: Put a Hard Cap in the Request Path

A budget you review weekly is a post-mortem, not a budget. Put the cap in the request path so the worst case is a degraded feature instead of a surprise invoice.

# Pick a daily cap you could lose without wrecking your week.
DAILY_UNIT_CAP = 1500000


def units_spent_today():
    if not LEDGER.exists():
        return 0.0
    today = date.today()
    total = 0.0
    for line in LEDGER.read_text().splitlines():
        row = json.loads(line)
        if date.fromtimestamp(row["ts"]) == today:
            total += row["weighted_units"]
    return total


def guarded_call(messages, tier="flash", max_tokens=400):
    if units_spent_today() >= DAILY_UNIT_CAP:
        raise RuntimeError("Daily AI budget spent - serve fallback instead")
    return call_model(messages, tier=tier, max_tokens=max_tokens)

Decide deliberately what happens at the cap. For user-facing requests, a cached or templated answer keeps the product alive. For background work, queue it for tomorrow. Either way, log the refusal — a cap that fires every day at 2pm is telling you something about volume or routing that needs fixing, not a number to raise.

Step 3: Route by Difficulty, Not by Habit

Most traffic doesn't need your strongest model. deepseek-v4-flash handles the bulk of it, while deepseek-v4-pro costs more and earns its place on hard multi-step reasoning, long-document synthesis, and questions where a wrong answer is expensive. The trick is to ask flash whether it's confident and escalate only when it says no.

# Uses client, guarded_call and SYSTEM_PROMPT from the blocks above.

TRIAGE = (
    "Triage this support question. Reply with JSON only: "
    '{"confident": true, "answer": "<short answer>"} if you are certain, '
    'or {"confident": false, "answer": ""} if a stronger model should handle it.'
)


def answer_question(question):
    first = guarded_call(
        [
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": TRIAGE + "\n\nQuestion: " + question},
        ],
        tier="flash",
        max_tokens=400,
    )
    try:
        parsed = json.loads(first)
    except json.JSONDecodeError:
        return first
    if parsed.get("confident") is True and parsed.get("answer"):
        return parsed["answer"]
    return guarded_call(
        [
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": question},
        ],
        tier="pro",
        max_tokens=800,
    )

You pay one extra flash call per escalated request and skip pro entirely on everything flash can handle. Watch your escalation rate: if pro is answering most traffic, the fix is better flash prompts, not a bigger budget line.

Step 4: Order Your Prompts So Caching Can Actually Help

Prompt caching matches from the start of the prompt. The moment something changes early in your system message, everything after it is reprocessed. Stable content goes first; the variable user turn goes last.

  • Static system instructions first, then durable reference material such as product docs, policies, and few-shot examples, then the user's input.

  • Never interpolate a timestamp, request ID, or user name into the system message — it invalidates the prefix on every call.

  • Keep a small number of long-lived prompt variants instead of assembling prompts from concatenated flags.

  • Track cached prompt tokens per route. A route that never reports cache hits has an unstable prefix.

  • Re-run your eval suite after any prefix change, because caching changes cost, not correctness.

The Five Buckets That Make Up a Solo Budget

Solo budgets go wrong when everything is a single number, because a spike in one area hides inside the total. Split it up.

BucketWhat lives thereHow to keep it honest
Build & explorationPrompt experiments, throwaway scripts, manual testingSend your own dev calls through the same guard; run experiments on flash
Eval & regressionRe-running a fixed test set after every prompt or model changeFreeze the test set, run it as a batch, compare token counts between runs
Production interactiveUser-facing requests in your appFlash by default, tight max_tokens, stream and abort when the user leaves
Batch & backgroundSummaries, classification, nightly enrichmentSchedule off-peak when it's cheaper, and reuse stable prefixes for cache hits
Spikes & abuseOne account hammering a free endpointPer-user rate limits plus the global daily cap

The Five Numbers That Predict Next Month's Bill

  • Cost per active user. If it climbs while usage habits stay flat, a route drifted to pro or outputs grew.

  • Pro escalation rate. Rising escalation means your flash prompts are losing context they need.

  • Cache-hit share of prompt tokens. A low share usually means an ID or timestamp snuck into a prefix.

  • Completion tokens per request. Uncapped outputs are the most common silent leak — set max_tokens and enforce it.

  • Retry rate. Every retry you bill twice, so use exponential backoff and idempotency keys.

When Another Provider or Gateway Is the Better Fit

Aggregators like OpenRouter are genuinely useful when you need to compare many models behind one key or fail over between vendors — if model choice is part of your product, that flexibility is worth paying for. OpenAI's direct platform makes sense when you're already standardized on its tooling and ecosystem.

If what you actually want is DeepSeek at a predictable direct rate and you're outside China without a Chinese phone number or bank account, that's the gap AiCredits fills: buy DeepSeek credits with a card or PayPal, then point the OpenAI SDK at the same base_url. Off-peak windows cost less and cache hits are cheaper, while pro costs more than flash — which is exactly why the routing and prefix discipline above is what keeps your budget flat. Current rates are at aicreditsapi.com/pricing.

A budget isn't a number you pick once. It's a cap in the request path, a ledger you can read, and a routing decision you make on purpose.

Frequently Asked Questions

How do I estimate a budget before I have any usage history?

Build a 50–100 question eval set from realistic user requests, run it through your wrapper, and read the ledger. Total weighted units divided by the number of cases gives you a per-request figure you can multiply by expected daily volume. Add headroom for retries and spikes, then set the daily cap below what you could afford to lose in a day.

Is deepseek-v4-pro ever worth the extra cost for a solo product?

Yes, in narrow places: multi-step reasoning, long-document synthesis, and outputs where an error costs more than the call. Gate every pro request behind a triage check so it stays a deliberate spend rather than a default.

Do failed requests still count against my budget?

Requests that fail before generating tokens generally don't bill, but a retry that succeeds does — and retry storms are the classic way a small project sees a surprising total. Cap retries, back off exponentially, and log failures in the same ledger as successful calls.

Can I just use my own DeepSeek account instead of a reseller?

If you have a Chinese phone number and bank account, the direct platform is fine. Many international founders don't, which is where AiCredits comes in: card or PayPal checkout, no Chinese phone or bank required, and the same OpenAI-compatible endpoint so the code above works unchanged.

Does AiCredits offer anything for catching cost bugs in code?

Alongside credits, AiCredits offers code linting tools you can run over your integration to catch sloppy patterns before they reach production — useful when your API wrapper is one file away from a runaway loop.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

💻Code Explainer

Was this article helpful?

| Share on X Reddit Copy link

服务器宕机了?别等用户告诉你

Wakeless 梦哨 帮你 30 秒监控网站 / API / SSL 证书,宕机秒级告警到邮箱、飞书、Slack。免费档 30 个监控,永久免费,无需信用卡。

免费开始监控 →
💬
反馈意见 / Feedback ×