Translation APIs are cheap per call and expensive per habit
A translation API looks like the safest possible first LLM side project: the task is well defined, quality is easy to eyeball, and every request is small. Then you ship it, a customer uploads a 40-page product catalogue, your retry logic kicks in on three timeouts, and the month's usage is several times what your napkin math predicted.
Most "cost breakdown" posts hand you a per-word estimate and move on. That number is useless, because a translation endpoint's bill is not driven by words — it is driven by tokens you resend, tokens you resend again after a failure, and content you re-translate that you already translated last week. This breakdown walks through the four quantities that actually determine your invoice, with runnable code for measuring each one.
The four numbers behind every invoice
Input tokens per segment. Source text plus system prompt plus glossary. The system prompt is often the largest single component for short UI strings.
Output tokens per segment. Roughly proportional to input, but some target languages expand noticeably and some scripts cost more tokens per word.
Cache hit rate. In translation, repeats are the norm: navigation labels, error messages, changelog boilerplate. A high hit rate is the single biggest lever you control.
Retry rate. Every failed-then-retried segment is billed twice if the first call actually succeeded server-side. This is the silent multiplier.
Log all four from the first request. You cannot optimise a bill you cannot decompose, and resp.usage gives you the first two for free.
1. The baseline call — and where to read your real cost
Save this as translator.py. It uses the OpenAI SDK pointed at AiCredits and returns token counts alongside the translation so you can price every call yourself.
The system prompt is deliberately short. Long style guides feel rigorous but they are re-sent on every request, so a 600-token instruction block on a 12-word button label is a 50x overhead you pay forever.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["AICREDITS_API_KEY"],
base_url="https://api.aicreditsapi.com/v1",
)
SYSTEM_TEMPLATE = (
"You are a translation engine. Translate the user's text into __TARGET__. "
"Preserve line breaks and placeholders such as {name} or %s. "
"Return only the translation, with no commentary."
)
def translate(text: str, target: str = "French", glossary: dict | None = None) -> dict:
system = SYSTEM_TEMPLATE.replace("__TARGET__", target)
if glossary:
pairs = "\n".join(f"{src} => {dst}" for src, dst in glossary.items())
system = system + "\nUse this glossary exactly:\n" + pairs
resp = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[
{"role": "system", "content": system},
{"role": "user", "content": text},
],
temperature=0,
)
return {
"text": resp.choices[0].message.content.strip(),
"input_tokens": resp.usage.prompt_tokens,
"output_tokens": resp.usage.completion_tokens,
}
if __name__ == "__main__":
out = translate("Ship it before Friday, then we iterate.", "French")
print(out["text"])
print("in:", out["input_tokens"], "out:", out["output_tokens"])
Run it on twenty segments from your real corpus — not lorem ipsum — and you have your per-segment token cost. Multiply by your current rates at aicreditsapi.com/deepseek-prices and the abstract question becomes an actual number.
2. Cache before you scale
Add the following to the same translator.py. The cache key covers model, target language, source text, and glossary, so changing any of them correctly produces a new entry. check_same_thread=False plus a lock lets you reuse the connection from a thread pool later.
import hashlib
import json
import sqlite3
import threading
_db = sqlite3.connect("translation_cache.db", check_same_thread=False)
_db.execute("CREATE TABLE IF NOT EXISTS cache (key TEXT PRIMARY KEY, value TEXT NOT NULL)")
_lock = threading.Lock()
def _key(text: str, target: str, glossary: dict | None) -> str:
payload = json.dumps(
["deepseek-v4-flash", target, text, sorted((glossary or {}).items())],
ensure_ascii=False,
)
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
def translate_cached(text: str, target: str = "French", glossary: dict | None = None) -> dict:
key = _key(text, target, glossary)
with _lock:
row = _db.execute("SELECT value FROM cache WHERE key = ?", (key,)).fetchone()
if row:
return {**json.loads(row[0]), "cached": True}
result = translate(text, target, glossary)
with _lock:
_db.execute(
"INSERT OR REPLACE INTO cache (key, value) VALUES (?, ?)",
(key, json.dumps(result, ensure_ascii=False)),
)
_db.commit()
return {**result, "cached": False}
The cache is also your retry safety net: write the result before you return it, and a client that retries the same request costs nothing.
3. Concurrency, deduplication, and retries
Parallelism is where side projects accidentally spend the most. Two rules: deduplicate the input list before dispatching, and cap concurrent workers well below whatever you think the limit is. A modest worker count with a real backoff beats fifty threads and a wall of 429s you then retry.
import time
from concurrent.futures import ThreadPoolExecutor
def translate_batch(texts, target="French", glossary=None, workers=4, attempts=3):
unique = list(dict.fromkeys(texts))
def run(text):
for attempt in range(attempts):
try:
return text, translate_cached(text, target, glossary)
except Exception:
if attempt == attempts - 1:
raise
time.sleep(2 ** attempt)
out = {}
with ThreadPoolExecutor(max_workers=workers) as pool:
for text, result in pool.map(run, unique):
out[text] = result
return out
if __name__ == "__main__":
segments = ["Add to cart", "Add to cart", "Out of stock"]
for src, res in translate_batch(segments, "German").items():
print(src, "->", res["text"], "cached:", res["cached"])
Where translation bills actually leak
| Leak | How it shows up | Fix |
|---|---|---|
| Glossary sent on every call | Input tokens scale with glossary size, not segment size | Attach a glossary only when the segment contains one of its terms |
| Timeout then retry | The same segment is billed twice | Cache under an idempotency key before retrying |
| Re-translating unchanged strings | Bill scales with traffic instead of with new content | Hash the source and check cache first |
| Pro model on every segment | You pay the premium for strings nobody reads closely | Route by content type, spot-check with pro |
| One call per sentence | System prompt repeated dozens of times per document | Send paragraphs, cap characters per request |
Routing between deepseek-v4-flash and deepseek-v4-pro
deepseek-v4-flash is the right default: fast, cheap, and good enough for the overwhelming majority of strings in a typical product. deepseek-v4-pro costs more and earns that cost on content where tone carries revenue or a mistranslation carries liability. The mistake is picking one model globally — route by content type and review a sample before you promote anything.
| Segment type | Default model | Reasoning |
|---|---|---|
| UI labels, errors, internal tools | deepseek-v4-flash | Short, repetitive, cache-friendly; readers want clarity, not style |
| Marketing and landing pages | deepseek-v4-pro | Tone and nuance affect conversion, and volume is small |
| Legal, medical, contracts | deepseek-v4-pro plus human review | The cost of one bad translation dwarfs any token savings |
| Low-resource languages | Test both, then decide | Flash may need more repair passes, and repairs cost tokens too |
The costs that have nothing to do with tokens
Fixed hosting floor. A small VPS or a serverless function plus a managed database. For an early-stage API this floor, not tokens, is usually the biggest line item.
Storage and egress. Translation memory grows forever and documents move in and out. Cheap, but not zero.
Observability. Logging token counts per request is free; a full APM stack is not. Start with structured logs.
Payment and billing overhead. If you resell translation, per-transaction fees on small invoices hurt more than your inference costs.
Your time. The genuinely expensive input. Every hour spent on a glossary feature nobody asked for is an hour not spent on cache hit rate.
The cheapest token is the one you never send. Cache hit rate is a product decision, not an infrastructure detail.
Build your own cost model in one afternoon
Measure average input and output tokens per segment from 20 real samples.
Estimate segments per month from actual traffic or a plausible launch scenario.
Apply your expected cache hit rate — new content is the only content you pay full price for.
Add a retry allowance, then instrument real retries and replace the estimate.
Re-run the model monthly. Off-peak usage and cache hits cost less, so shifting batch jobs to quiet hours genuinely changes the total.
Why developers run this on AiCredits
AiCredits exists because paying for DeepSeek shouldn't require a Chinese phone number or a Chinese bank account. You top up with a card or PayPal, get an OpenAI-compatible endpoint at https://api.aicreditsapi.com/v1, and keep the same SDK code shown above — nothing to rewrite when you switch. Current rates for deepseek-v4-flash and deepseek-v4-pro live at aicreditsapi.com/deepseek-prices.
If you're also shipping the codebase behind the API, the same account covers linting tools, which is convenient for a one-person side project.
FAQ
There is no single answer, because billing tracks tokens rather than words and your cache hit rate changes the result dramatically. Run 20 representative segments through translator.py, sum input_tokens and output_tokens, then apply the current rates at aicreditsapi.com/deepseek-prices. The second thousand words is usually far cheaper than the first because repeats hit the cache.
For product copy, UI strings, support macros, and internal tooling, yes — that's what it's for. For marketing, legal, or anything a customer will scrutinise, route those segments to deepseek-v4-pro and review a sample. Mixing models is normal and usually cheaper than picking one.
Write the result to your cache before returning it, key it on a hash of model, target, source text, and glossary, and check that cache at the top of your handler. Then a client retry — or your own backoff loop — resolves from SQLite instead of a second inference call.
Not through AiCredits. You sign up, pay by card or PayPal, and use the standard OpenAI SDK with the AiCredits base URL. No Chinese phone number, bank account, or identity verification is involved.