AiCredits
Side Project Ops

DeepSeek API for Side Projects: Low-Cost Setup Under a Dollar

How to run the DeepSeek API on a side project without a surprise bill: output caps, local caching, trimmed history, and a hard token ceiling.

Published 2026-09-21 Updated 2026-09-21 7 min

Most hobby projects don't die at the idea stage. They die the week a prototype that felt free starts sending more tokens per request than the feature it powers is worth. The bill isn't outrageous — it's just unexplained, and unexplained costs kill momentum faster than bugs do.

If your personal rule is that a side project stays under a dollar, the levers below are the ones that actually get you there. None of them are clever. All of them are decisions about how you shape a request, made once, and enforced automatically afterward.

This guide assumes you're using the DeepSeek models through the OpenAI-compatible endpoint, so every snippet runs as written with the standard openai SDK.

Why hobby-project LLM spend creeps up

The four causes are almost always the same, and none of them are about picking the wrong model.

  • The full conversation is resent every turn. Turn twenty costs roughly twenty times what turn one cost, for the same assistant reply.

  • max_tokens is left at its default. A chat endpoint asked to be chatty will be chatty, and output tokens are the expensive half of a request.

  • A stronger model is used everywhere. Escalation should be an exception path, not the default path.

  • Nothing is cached locally. The same classification or summary gets computed twice because nothing remembers the first answer.

Step 1: Default to deepseek-v4-flash and meter every call

deepseek-v4-flash handles the vast majority of side-project work — classification, extraction, short summaries, small chat features — and it's the right default because it's the cheaper tier. Reach for deepseek-v4-pro only when flash's output fails a check you wrote yourself.

Before you optimize anything, print the usage object on every call. You cannot tune what you can't see, and resp.usage is free.

import os
from openai import OpenAI

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


def ask(prompt, model="deepseek-v4-flash", max_tokens=300, temperature=0.3):
    resp = client.chat.completions.create(
        model=model,
        messages=[{"role": "user", "content": prompt}],
        max_tokens=max_tokens,
        temperature=temperature,
    )
    usage = resp.usage
    print(f"in={usage.prompt_tokens} out={usage.completion_tokens} model={model}")
    return resp.choices[0].message.content


if __name__ == "__main__":
    print(ask("Give me three name ideas for a habit-tracking CLI."))

Step 2: Cap output, and put the static part of the prompt first

Two habits do most of the work here. First, set max_tokens per call site instead of per project — a label classifier needs a handful of tokens, not a paragraph. Second, keep the prompt's stable prefix identical across calls so provider-side caching has something to reuse; only the variable part should sit in the user message.

Prompt caching rewards stability. If your system message changes on every request because you interpolate a timestamp or a user id into it, you've paid for a long prompt that can never be reused. Cache hits are billed more cheaply, so an unstable prefix is pure waste.

For anything that can only return one of a few labels, use temperature 0 and an output cap in the single digits.

SYSTEM = """You tag support tickets.
Return exactly one label: billing, bug, feature, or other.
Return the label only. No punctuation, no explanation.
"""


def classify(text):
    resp = client.chat.completions.create(
        model="deepseek-v4-flash",
        messages=[
            {"role": "system", "content": SYSTEM},  # identical on every call
            {"role": "user", "content": text},      # only this part changes
        ],
        max_tokens=4,
        temperature=0,
    )
    return resp.choices[0].message.content.strip().lower()

Step 3: Put a local cache in front of the API

Side projects are full of repeated requests: the same page re-rendered, the same webhook retried, the same test fixture summarized a dozen times during development. A twenty-line SQLite cache removes all of it, and it also makes your retry logic safe — a retry that hits the cache costs nothing and can't produce a duplicate answer.

Keep the cache keyed on everything that affects the result: model, messages, max_tokens, and temperature.

import hashlib
import json
import sqlite3

db = sqlite3.connect("llm_cache.db")
db.execute("CREATE TABLE IF NOT EXISTS cache (key TEXT PRIMARY KEY, value TEXT NOT NULL)")


def cached_chat(messages, model="deepseek-v4-flash", max_tokens=300, temperature=0.0):
    blob = json.dumps([model, messages, max_tokens, temperature], sort_keys=True)
    key = hashlib.sha256(blob.encode()).hexdigest()

    row = db.execute("SELECT value FROM cache WHERE key = ?", (key,)).fetchone()
    if row is not None:
        return json.loads(row[0])

    resp = client.chat.completions.create(
        model=model,
        messages=messages,
        max_tokens=max_tokens,
        temperature=temperature,
    )
    text = resp.choices[0].message.content
    db.execute(
        "INSERT OR REPLACE INTO cache (key, value) VALUES (?, ?)",
        (key, json.dumps(text)),
    )
    db.commit()
    return text

Step 4: Stop resending the entire conversation

If your app keeps a growing messages list and sends all of it, prompt tokens grow linearly with conversation length. Keep a rolling window of the last few turns and fold everything older into a short summary you maintain yourself. This is the single biggest saving in most chat-shaped side projects.

def trim_history(messages, keep_last=6, running_summary=None):
    system = [m for m in messages if m["role"] == "system"]
    turns = [m for m in messages if m["role"] != "system"]
    tail = turns[-keep_last:]
    if running_summary:
        tail = [{"role": "system", "content": f"Earlier summary: {running_summary}"}] + tail
    return system + tail

Step 5: Give yourself a hard ceiling

A budget you only check monthly isn't a budget. Log usage after every call and raise an error once a token ceiling you chose in advance is crossed. If a loop bug starts firing requests, you find out on call forty instead of on the invoice.

import json
import pathlib

LEDGER = pathlib.Path("usage_ledger.json")
CEILING = 250_000  # your own monthly token cap, not a vendor limit


def log_usage(prompt_tokens, completion_tokens):
    data = json.loads(LEDGER.read_text()) if LEDGER.exists() else {"calls": 0, "tokens": 0}
    data["calls"] += 1
    data["tokens"] += prompt_tokens + completion_tokens
    LEDGER.write_text(json.dumps(data))
    if data["tokens"] > CEILING:
        raise RuntimeError(
            f"ceiling hit: {data['tokens']} tokens across {data['calls']} calls"
        )
    return data

Where the extra spend is worth it

  • Escalation, not defaults. Run flash first, validate the output, and call deepseek-v4-pro only when validation fails. You pay the higher tier for the hard percentage of requests, not all of them.

  • Off-peak batch jobs. Off-peak windows cost less, so nightly summaries, embeddings backfills, and test-fixture generation belong on a schedule, not in the request path.

  • Real output caps on chat. Streaming makes a long answer feel good but doesn't make it cheaper; a tighter cap plus a "continue" button is friendlier to your budget.

  • Deterministic work off the model. Slug generation, date parsing, and enum mapping don't need an LLM, and every call you don't make is a call you don't pay for.

HabitWhat it does to spendCheaper alternative
Resending full chat historyPrompt tokens grow with every turnRolling window plus a short summary
Default max_tokensOne chatty answer can dwarf a day of useExplicit cap per call site
deepseek-v4-pro everywhereYou pay more for reasoning you don't needFlash first, escalate on failed validation
No local cacheRepeat requests cost repeat tokensHash the prompt, store the answer in SQLite
Peak-hour batch jobsFull-rate processing for offline workSchedule the job off-peak
LLM for deterministic tasksTrivial spend you can delete entirelyRegex, a lookup table, or a schema check

Getting credits when you're outside China

One practical wrinkle for international developers: paying DeepSeek directly can be awkward without a Chinese phone number or bank account. AiCredits sells DeepSeek API credits that you can buy with an international card or PayPal, and serves the models through an OpenAI-compatible endpoint at https://api.aicreditsapi.com/v1, so the code in this post works unchanged.

That setup fits side projects well, because you can top up a small amount for a hobby app rather than committing to a plan sized for production. For current rates, see aicreditsapi.com/pricing — and remember that caching and off-peak scheduling move your effective cost more than any single model choice. If you're shipping code alongside the API calls, our linting tools are there too.

FAQ

Is the DeepSeek API compatible with the OpenAI Python SDK?

Yes. Point the SDK at base_url="https://api.aicreditsapi.com/v1", pass your AiCredits key, and use model="deepseek-v4-flash" or "deepseek-v4-pro" exactly as shown above.

Which model should a side project default to?

deepseek-v4-flash. It's the faster, lower-cost tier and covers classification, extraction, summaries, and short chat replies. Reserve deepseek-v4-pro for requests where flash's output fails a validation check you wrote.

Do I need a Chinese phone number or bank account?

No. AiCredits accepts international cards and PayPal, so you can fund a hobby project without a Chinese bank account or phone number.

How do I estimate what my side project will cost?

Track tokens rather than guessing: log resp.usage.prompt_tokens and resp.usage.completion_tokens on every call, then compare your monthly totals against current rates at aicreditsapi.com/pricing. Caching and off-peak jobs lower the effective number.

Does prompt caching work automatically?

Caching rewards stable prefixes, so keep the static part of your system message byte-identical across calls and put only the changing text in the user message. If you interpolate a timestamp or user id into the system prompt, you lose the benefit on every request.

What happens if my side project suddenly gets traffic?

The token ceiling in Step 5 raises an error before spend runs away, and the local cache absorbs repeated identical requests. Add per-user rate limiting on top before you share the link anywhere public.

The cheapest DeepSeek request is the one you never send: cache it, trim it, cap it, and put a ceiling above all of it.

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 ×