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-proonly 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.
| Habit | What it does to spend | Cheaper alternative |
|---|---|---|
| Resending full chat history | Prompt tokens grow with every turn | Rolling window plus a short summary |
| Default max_tokens | One chatty answer can dwarf a day of use | Explicit cap per call site |
| deepseek-v4-pro everywhere | You pay more for reasoning you don't need | Flash first, escalate on failed validation |
| No local cache | Repeat requests cost repeat tokens | Hash the prompt, store the answer in SQLite |
| Peak-hour batch jobs | Full-rate processing for offline work | Schedule the job off-peak |
| LLM for deterministic tasks | Trivial spend you can delete entirely | Regex, 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
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.
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.
No. AiCredits accepts international cards and PayPal, so you can fund a hobby project without a Chinese bank account or phone number.
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.
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.
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.