Why prototypes hide production surprises
Prototypes usually test one prompt, one user, and one happy path. Production adds concurrency, retries, long-tail inputs, and a finance team asking why usage doubled. The surprise is rarely the model's quality; it is uncontrolled variance in request size, model choice, and failure handling.
Treat the model as one dependency in a larger system. You need explicit routing, hard limits, caching, observability, and a fallback plan before traffic scales. The goal is not to eliminate every failure; it is to make failures visible, bounded, and cheap to recover from.
Default to deepseek-v4-flash, escalate deliberately
Most production work—classification, extraction, summarization, drafting, routine code help—does not need the strongest model. Start with deepseek-v4-flash for the default path. Reserve deepseek-v4-pro for tasks where you have measured that extra reasoning changes the outcome: complex debugging, architecture review, multi-step planning, or high-stakes analysis.
Make the routing decision explicit in code and logs. If every request can silently become a pro request, your cost and latency profile will drift. A simple task label plus a hard flag is enough at first.
Use deepseek-v4-flash for high-volume, latency-sensitive, well-specified tasks.
Use deepseek-v4-pro only for a short list of task types or when a user explicitly requests deeper analysis.
Log the chosen model on every request so you can audit the mix later.
Re-evaluate routing with real eval results, not vibes.
If you cannot explain why a request used deepseek-v4-pro, it probably should have used deepseek-v4-flash.
A production wrapper you can actually run
This wrapper adds the guardrails that prototypes usually skip: a per-request timeout, bounded retries with backoff, an in-memory cache for repeated prompts, and usage logging. It uses the OpenAI SDK against AiCredits' OpenAI-compatible endpoint. Set AICREDITS_API_KEY before running it.
import os
import time
import json
import random
import hashlib
import logging
from openai import OpenAI
from openai import APITimeoutError, APIConnectionError, RateLimitError, APIStatusError
logging.basicConfig(level=logging.INFO)
client = OpenAI(
api_key=os.environ['AICREDITS_API_KEY'],
base_url='https://api.aicreditsapi.com/v1',
timeout=30.0,
max_retries=0,
)
def model_for(task: str, hard: bool = False) -> str:
if hard or task in {'architecture_review', 'complex_debug'}:
return 'deepseek-v4-pro'
return 'deepseek-v4-flash'
def complete(prompt: str, *, task: str = 'general', hard: bool = False, max_tokens: int = 512, temperature: float = 0.2, cache=None) -> str:
cache = cache if cache is not None else {}
key = hashlib.sha256(f'{task}|{hard}|{max_tokens}|{temperature}|{prompt}'.encode()).hexdigest()
if key in cache:
return cache[key]
model = model_for(task, hard)
last_err = None
for attempt in range(3):
try:
resp = client.chat.completions.create(
model=model,
messages=[{'role': 'user', 'content': prompt}],
max_tokens=max_tokens,
temperature=temperature,
)
text = resp.choices[0].message.content or ''
usage = resp.usage
logging.info(json.dumps({'model': model, 'usage': usage.model_dump() if usage else None, 'chars': len(prompt)}))
cache[key] = text
return text
except (APITimeoutError, APIConnectionError, RateLimitError) as e:
last_err = e
time.sleep((2 ** attempt) + random.random())
except APIStatusError as e:
if e.status_code >= 500:
last_err = e
time.sleep((2 ** attempt) + random.random())
else:
raise
raise RuntimeError(f'completion failed after retries: {last_err}')
The in-memory cache is fine for a single process; move it to Redis or your existing cache layer before you run multiple workers. Keep cache keys tied to the prompt, model, and generation settings so you never serve a response generated with different constraints.
Control the three variables that surprise teams
Most production surprises come from three variables: request size, model mix, and retry volume. Put a hard ceiling on each.
Request size: cap max_tokens, trim retrieved context, and reject oversized prompts before they hit the API. A prompt that grows from a paragraph to a document changes both latency and cost.
Model mix: enforce routing in one place. If deepseek-v4-pro is available as a free-form option, it will eventually be used everywhere.
Retry volume: retries are necessary, but unbounded retries turn a transient outage into a self-inflicted traffic spike. Use exponential backoff, a retry budget, and a circuit breaker.
Concurrency: limit in-flight requests per worker. Queueing internally is usually cheaper and more predictable than letting the API rate-limit you.
Output length: stop sequences and max_tokens are product decisions. A chatbot that can generate an essay when asked for a label is a cost bug.
Instrument what you can act on
You do not need a full observability platform on day one. You need a small set of signals that tell you when behavior changes.
| Signal | Why it matters | Action |
|---|---|---|
| Tokens per request (prompt + completion) | Detects context bloat and runaway generations | Alert on sustained shifts; trim prompts |
| Model mix | Shows whether pro usage is creeping | Route by task label; review weekly |
| Retry rate and error type | Distinguishes bad requests from outages | Fix 4xx; back off and circuit-break 5xx/429 |
| Cache hit rate | Reveals repeat traffic and wasted spend | Normalize prompts; add TTLs |
| p95 latency by task | Catches slow paths before users do | Stream, lower max_tokens, or split tasks |
Failure handling is a product feature
An LLM call can time out, return a 429, produce truncated output, or return valid JSON with wrong fields. Production code needs a policy for each. Retry only what is safe to retry. For user-facing generation, stream tokens so a timeout does not leave the UI blank. For structured extraction, validate the output and retry with a repair prompt rather than silently passing bad data downstream.
Keep a fallback path that degrades gracefully. For a hard task routed to deepseek-v4-pro, you might fall back to deepseek-v4-flash with a shorter prompt and a clear reduced-analysis state in the UI. For critical workflows, queue the request and retry later instead of blocking a user.
Use idempotency keys for background jobs so retries do not duplicate side effects.
Separate user-facing timeouts from background job timeouts.
Record the request ID and model on every log line.
Test failure paths with mocked 429s and timeouts.
Version prompts and evaluate before you scale
Prompts are code. Store them in version control, name them, and log the version with each response. When you change a prompt, run a small eval set that represents production traffic—edge cases, short inputs, long inputs, and adversarial inputs. Compare deepseek-v4-flash and deepseek-v4-pro only on tasks where the stronger model might matter; otherwise you are buying variance.
Roll out prompt changes gradually. A canary slice of traffic plus a rollback switch is more useful than a perfect offline eval. Track task success, retry rate, and user corrections, not just average latency.
How AiCredits fits without procurement surprises
AiCredits sells DeepSeek API credits to international developers who want to pay by card or PayPal without a Chinese phone number or bank account. The API is OpenAI-compatible, so the code above works with the same SDK you already use. Start on deepseek-v4-flash, route selectively to deepseek-v4-pro, and check aicreditsapi.com/pricing for current rates. Off-peak usage costs less, cache hits are cheaper than fresh calls, and pro costs more than flash, so the routing and caching decisions in this guide directly affect your bill.
Procurement should not be the reason a prototype stalls. A prepaid credit model with card or PayPal keeps the finance path simple while you focus on the engineering controls.
FAQ
No. Use deepseek-v4-flash as the default and reserve deepseek-v4-pro for tasks where evals show a meaningful quality gain. Pro costs more than flash and can add latency, so blanket routing usually creates surprises.
Cap max_tokens, trim context, cache repeated prompts, route by task, and monitor tokens per request and model mix. Also bound retries and concurrency so an outage does not amplify traffic.
No. AiCredits is built for international developers and supports card or PayPal. The endpoint is OpenAI-compatible at https://api.aicreditsapi.com/v1.
Log the model, prompt version, token usage, latency, status code, retry count, and a request ID. Avoid logging sensitive prompt content unless you have a clear retention policy.