Risk control rejected is one of the least helpful errors the DeepSeek API can return. There is no missing parameter to fix, no stack trace pointing at your code, and the exact request that worked an hour ago now fails. Teams usually respond by retrying harder or rotating keys — both of which tend to make it worse.
This guide explains what the error actually is, the six triggers behind most incidents, and five fixes you can ship today. Every snippet runs against the OpenAI SDK with the AiCredits base URL, so you can drop it into an existing integration.
What "Risk control rejected" actually means
The rejection happens before your prompt ever reaches the model. It comes from an abuse-prevention layer that inspects the shape of the request and the caller behind it: the network the call arrived from, the state of the account, how much traffic is arriving and how fast, and whether the payload looks like something a real application would send. When that layer is unhappy, you get a short rejection and no completion.
That distinction matters, because the errors people confuse most behave very differently:
429 rate limit — you are over quota for the window. The model never sees the request either, but the cause is arithmetic, not suspicion.
Risk control — the request or the caller was flagged. Replaying the identical call from the identical IP is the worst possible response.
Model-side refusal — the model ran and declined, or returned an empty completion. That is a prompt problem, not an infrastructure problem.
401 / 403 auth — the key is wrong, expired, or not permitted on that route.
Because status codes overlap (a rejection may arrive as 400 or 403), treat the message body as the source of truth and classify once, in one place:
import openai
from openai import OpenAI
client = OpenAI(
api_key="YOUR_AICREDITS_KEY",
base_url="https://api.aicreditsapi.com/v1",
)
def classify(exc: Exception) -> str:
"""Map an SDK exception to a bucket you can act on."""
if isinstance(exc, openai.APIStatusError):
text = str(getattr(exc, "message", exc)).lower()
if "risk control" in text or "risk_control" in text:
return "risk_control"
if exc.status_code == 429:
return "rate_limit"
if exc.status_code in (401, 403):
return "auth"
return f"http_{exc.status_code}"
if isinstance(exc, openai.APIConnectionError):
return "network"
return "unknown"
try:
resp = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[{"role": "user", "content": "Say hello in five words."}],
)
print(resp.choices[0].message.content)
except Exception as exc:
print("bucket:", classify(exc))
print("raw:", exc)
Why it happens: six real triggers
Egress IP reputation. Calls from datacenter ranges, rotating proxy pools, or a VPN that hops countries mid-job look like evasive traffic.
Region whiplash. The same key used from Frankfurt in the morning and Singapore in the afternoon, on identical workloads, is a pattern that attracts attention.
Burst shape. Dozens of parallel requests from one key, or a retry loop firing every few hundred milliseconds, reads as scraping rather than product usage.
Payload shape. Multi-megabyte scraped HTML, binary noise, odd encodings, or the same giant string pasted many times.
Account and billing state. Unverified payment methods, or a billing country that does not match where the traffic originates.
Shared, leaked, or hoarded keys. One key pasted into five services, committed to a public repo, or sitting in a frontend bundle.
Fix 1 — Pin your egress IP and region
Most risk-control incidents are network incidents in disguise. If you sit behind a cloud NAT gateway that changes, a consumer VPN, or a proxy pool that rotates per request, your traffic arrives from a dozen IPs nobody has seen before. That is indistinguishable from abuse.
Pick a stable egress — a single NAT gateway, a fixed floating IP, or a dedicated worker host — and keep it stable for the lifetime of the key. If you genuinely need multiple regions, give each region its own key rather than sharing one. And when a call fails, do not switch proxies and immediately replay it; you have just demonstrated that your traffic is chameleonic. Back off, then retry from the same origin.
Fix 2 — Shape your traffic instead of hammering it
Bursty traffic is the second most common cause. Batch jobs and fan-out workers have a habit of launching everything at once, producing a spike that looks nothing like organic usage. Two things fix it: a concurrency ceiling per key, and backoff that degrades politely.
Retry only what is worth retrying, and add jitter so your workers do not march in lockstep:
import random
import time
from openai import OpenAI
client = OpenAI(api_key="YOUR_AICREDITS_KEY", base_url="https://api.aicreditsapi.com/v1")
RETRYABLE = {"risk_control", "rate_limit", "http_500", "http_502", "http_503", "network"}
def chat(messages, max_attempts=5, base_delay=1.5):
for attempt in range(1, max_attempts + 1):
try:
resp = client.chat.completions.create(
model="deepseek-v4-flash",
messages=messages,
timeout=60,
)
return resp.choices[0].message.content
except Exception as exc:
bucket = classify(exc) # function from the previous snippet
if bucket not in RETRYABLE or attempt == max_attempts:
raise
# full jitter: never retry in lockstep with your other workers
delay = base_delay * (2 ** (attempt - 1)) * (0.5 + random.random())
print(f"{bucket} (attempt {attempt}) - backing off {delay:.1f}s")
time.sleep(delay)
raise RuntimeError("unreachable")
print(chat([{"role": "user", "content": "Summarise the CAP theorem in two sentences."}]))
Note the cap on attempts. Five tries with jittered exponential delays spread the retries over tens of seconds — long enough for a transient flag to clear, short enough that your job does not hang. If a key fails every attempt, stop; a tight loop of identical rejected bodies only deepens the signal.
Fix 3 — Shrink and normalise the payload
Payload-driven rejections are the easiest to miss, because the content is usually perfectly valid for you. Pasting raw HTML with inline scripts, base64 blobs, or a several-hundred-kilobyte log file into messages creates a request no legitimate chat product would send. Strip before you send: drop script and style blocks, collapse padding, normalise encoding, and chunk anything long.
Put hygiene and throttling in one place so no caller can bypass them:
import asyncio
import hashlib
import re
from openai import AsyncOpenAI
client = AsyncOpenAI(api_key="YOUR_AICREDITS_KEY", base_url="https://api.aicreditsapi.com/v1")
LIMITER = asyncio.Semaphore(4) # a small in-flight ceiling per key
_cache = {}
def scrub(text: str, limit: int = 6000) -> str:
text = text.replace("\x00", " ")
text = re.sub(r"<script.*?</script>", " ", text, flags=re.S | re.I)
text = re.sub(r"[ \t]{3,}", " ", text)
return text.strip()[:limit]
async def ask(prompt: str) -> str:
prompt = scrub(prompt)
key = hashlib.sha256(prompt.encode("utf-8")).hexdigest()
if key in _cache:
return _cache[key] # identical repeats look like an attack
async with LIMITER:
resp = await client.chat.completions.create(
model="deepseek-v4-flash",
messages=[{"role": "user", "content": prompt}],
)
answer = resp.choices[0].message.content
_cache[key] = answer
return answer
async def main():
jobs = [ask("Explain Python decorators in three lines.") for _ in range(10)]
for out in await asyncio.gather(*jobs):
print(out)
asyncio.run(main())
The prompt-hash cache does double duty: it saves tokens, and it stops a retry storm from re-submitting an identical body that was already rejected.
Fix 4 — One key per service, rotated on a schedule
A key is an identity. When three services share one, all of their traffic patterns merge into a single profile — and a noisy cron job in staging can get your production key flagged. Issue separate keys per service and per environment, keep them in a secrets manager rather than a .env someone commits, and rotate on a calendar rather than only after an incident. When a key does start failing, you want the blast radius to be one job, not your whole platform.
Fix 5 — Fix the account layer, not just the client
Sometimes nothing in your code is wrong. The account itself — payment method, verification state, billing country — is what is under review, and every client-side workaround is wasted effort until that resolves.
This is where the billing channel matters. AiCredits sells DeepSeek API credits to international developers with a card or PayPal, no Chinese phone number or bank account required, and the same key works with the OpenAI SDK by pointing base_url at https://api.aicreditsapi.com/v1. That removes the verification layer that is a frequent source of rejections for teams outside mainland China. It does not remove prompt-level rules — those still apply to your content, and they should.
Diagnostic table: match the symptom
| Symptom | Likely cause | Action |
|---|---|---|
| Every call fails from one machine, others fine | Egress IP flagged | Pin a static IP; stop proxy rotation |
| Failures cluster right after a deploy | Parallel workers burst | Cap concurrency; add jittered backoff |
| Fails only on large documents | Payload size or shape | Chunk input; strip HTML; normalise encoding |
| Intermittent, no obvious pattern | Shared or leaked key | Rotate key; one key per service and env |
| Worked yesterday, fails today | Account or billing review | Resolve billing channel first (Fix 5) |
| You get 429 instead of a rejection | Rate limit, not risk control | Back off; request more headroom |
FAQ
No. A content filter runs after the model and shows up as a refusal or an empty completion. Risk control rejects the request before inference — the model never sees your prompt, so rewriting the prompt will not help.
A tight immediate retry loop can, because repeated identical rejected bodies from the same IP look like an attack. Exponential backoff with jitter and a hard attempt cap is safe; hammering is not.
No. Risk control sits upstream of model selection, so changing models does nothing. Keep deepseek-v4-flash for volume and retries, and reserve deepseek-v4-pro for work that genuinely needs the stronger model.
Not through AiCredits. Credits are payable by card or PayPal with no Chinese phone or bank account required. Prompt-level content rules still apply regardless of billing route.
The five-minute checklist
Classify the error once, in one function. Never let raw exceptions drive retry logic.
Freeze one egress IP per key, and stop switching proxies after a failure.
Cap concurrency and add jittered exponential backoff.
Strip and chunk payloads before they reach
messages.Separate keys per service and environment; rotate on a schedule.
Check the account and billing layer before you refactor anything.
Start with the cheap fixes — classification and backoff — before assuming the worst. Most teams find the rejection disappears once their traffic starts looking boring. If you want credits without the verification detour, current rates are at aicreditsapi.com/pricing.
Still stuck at DeepSeek's checkout?
This article explains why the payment fails. If what you actually need is a working key today, there is a shorter path: prepaid DeepSeek credits, no subscription, key issued to your account right after checkout.
- $9 / $19 / $29 USD one-time credit packs — 1 USD = 500K credits (so $9 = 4.5M); billed by actual usage, never expires, tax excluded
- Card, Apple Pay, Google Pay or Alipay via Creem — no PayPal account needed
- Email signup only — no Chinese phone number, no Chinese bank account
- Same DeepSeek models and the same OpenAI-compatible API — change one base_url
Get a DeepSeek key → Or try it free first
Not sure how prepaid billing works? See the full DeepSeek API credits guide → — packs, usage-based billing, supported models and payment methods.