AiCredits
API Testing

How to Test Your DeepSeek API Integration Before Going Live: 7 Checks That Catch Real Bugs

A pre-launch test suite for your DeepSeek API integration: contract checks, streaming parity, retries, JSON validation, golden sets and load smoke tests.

Published 2026-09-28 Updated 2026-09-28 9 min

Why a Passing Demo Is Not a Passing Integration

Almost nobody goes live with an integration that returns 500s. They go live with an integration that returns 200s and is still wrong. The response looks fine in a notebook, then in production you discover that finish_reason was length on your longest answers, that the stream dropped its final chunk behind a proxy, that your retry layer turned a rate limit into a user-facing error, or that one prompt in twenty returns JSON wrapped in markdown fences.

This is a pre-launch suite you can run in a single test file before you point real traffic at the API. It uses deepseek-v4-flash for almost everything because it is the fast default and cheap to run repeatedly, and deepseek-v4-pro only on the paths where you genuinely need the stronger model. Everything below runs as written against AiCredits.

Set Up One Client for Every Test

import os
from openai import OpenAI

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

resp = client.chat.completions.create(
    model='deepseek-v4-flash',
    messages=[
        {'role': 'system', 'content': 'You reply with exactly one word.'},
        {'role': 'user', 'content': 'Say READY'},
    ],
    temperature=0,
    max_tokens=8,
)

print(repr(resp.choices[0].message.content))
print('model:', resp.model, '| finish:', resp.choices[0].finish_reason)
print('usage:', resp.usage)

If that prints a word, a model name and a usage object, your key, base URL and model routing are all correct. Keep max_tokens tiny on smoke tests: you are testing plumbing, not quality, and short completions are the cheapest kind of call. Cache-friendly, low-output requests are the least expensive ones you can make, which matters when this runs on every pull request.

Check 2: Assert the Response Contract, Not Just the Text

def assert_contract(resp):
    assert resp.choices, 'API returned no choices'
    choice = resp.choices[0]
    assert choice.message is not None, 'message missing'
    assert choice.finish_reason in {'stop', 'length', 'tool_calls', 'content_filter'}, choice.finish_reason
    assert resp.model, 'model field missing: do not assume which model answered'

    usage = resp.usage
    assert usage is not None, 'usage missing: you cannot budget or alert without it'
    assert usage.total_tokens == usage.prompt_tokens + usage.completion_tokens
    return choice.finish_reason

assert_contract(resp)

Text assertions ('READY' in content) break whenever the model paraphrases. Contract assertions do not. The one that saves you in production is the total_tokens identity check: if your metrics pipeline is built on a usage field that is occasionally absent, you will not notice until your cost dashboard goes blank.

Check 3: Streaming Parity and Dropped-Chunk Detection

def collect_stream(client, messages, model='deepseek-v4-flash', max_tokens=64):
    stream = client.chat.completions.create(
        model=model, messages=messages, temperature=0,
        max_tokens=max_tokens, stream=True,
    )
    parts, finish = [], None
    for chunk in stream:
        if not chunk.choices:
            continue
        delta = chunk.choices[0].delta
        if delta and delta.content:
            parts.append(delta.content)
        if chunk.choices[0].finish_reason:
            finish = chunk.choices[0].finish_reason
    assert finish is not None, 'stream ended without finish_reason -> truncated stream'
    return ''.join(parts), finish

msg = [{'role': 'user', 'content': 'List three uses of a Python set, one per line.'}]
streamed, finish = collect_stream(client, msg)
buffered = client.chat.completions.create(
    model='deepseek-v4-flash', messages=msg, temperature=0, max_tokens=64,
).choices[0].message.content

print('stream finish:', finish)
print('streamed chars:', len(streamed), '| buffered chars:', len(buffered))

Do not assert the two strings are identical; generated text is not guaranteed to be byte-for-byte repeatable across two separate calls. Do assert that the stream terminates with a finish_reason at all. A stream that simply ends without one is the signature of a proxy buffering or cutting long-lived connections, and it is far easier to catch here than in a support ticket.

Check 4: Retries That Survive 429s and 5xxs

import time, random
from openai import APIConnectionError, APIStatusError, RateLimitError

RETRYABLE_STATUS = {408, 409, 429, 500, 502, 503, 504}

def chat_with_retry(client, messages, model='deepseek-v4-flash', max_attempts=5, **kwargs):
    for attempt in range(1, max_attempts + 1):
        try:
            return client.chat.completions.create(model=model, messages=messages, **kwargs)
        except RateLimitError:
            pass  # 429: back off and try again
        except APIStatusError as err:
            if err.status_code not in RETRYABLE_STATUS:
                raise  # 400/401/403/404 are your bug, not a transient blip
        except APIConnectionError:
            pass

        if attempt == max_attempts:
            raise RuntimeError('retries exhausted')
        time.sleep(min(2 ** attempt + random.random(), 30.0))

Two rules make this safe. First, only retry idempotent work: a chat completion you will discard is fine, a tool call that charged a card is not, unless you pass your own idempotency key through the request. Second, jitter matters more than the base delay. Without it, eight worker threads retry in lockstep and you recreate the rate limit you are backing off from. Test this path deliberately by setting max_attempts=1 and confirming a non-retryable 401 raises immediately rather than looping.

Check 5: Prove Your JSON Output Parses Every Time

import json

def extract_json(client, prompt, model='deepseek-v4-flash', model_retries=1):
    messages = [
        {'role': 'system', 'content': 'Return only a JSON object. No prose, no code fences.'},
        {'role': 'user', 'content': prompt},
    ]
    for _ in range(model_retries + 1):
        resp = client.chat.completions.create(
            model=model, messages=messages, temperature=0,
            response_format={'type': 'json_object'},
        )
        raw = resp.choices[0].message.content
        try:
            return json.loads(raw)
        except json.JSONDecodeError:
            messages.append({'role': 'assistant', 'content': raw})
            messages.append({'role': 'user', 'content': 'Invalid JSON. Return the same data as one JSON object.'})
    raise ValueError('model never returned parseable JSON')

print(extract_json(client, 'Extract the city from this text as a JSON object: Flight to Lisbon on May 3'))

The repair loop is the point. Even with JSON mode on, a defensive one-shot correction turns a small class of failures into a slightly slower success instead of a 500 for your user. Log how often the second attempt fires; if it is frequent, your system prompt is the problem, not the model.

Check 6: A Golden Set That Catches Silent Quality Drops

GOLDEN = [
    ('Extract the city as JSON: Flight to Lisbon on May 3', 'Lisbon'),
    ('Extract the city as JSON: Meeting in Osaka next week', 'Osaka'),
    ('Extract the city as JSON: Train to Turin tomorrow', 'Turin'),
]

def run_golden(client, model='deepseek-v4-flash'):
    failures = []
    for prompt, expected in GOLDEN:
        got = extract_json(client, prompt, model=model)
        value = str(got.get('city', '')).strip().lower()
        if value != expected.lower():
            failures.append((prompt, expected, got))
    return failures

print('flash failures:', run_golden(client))
print('pro failures:', run_golden(client, model='deepseek-v4-pro'))

Thirty real prompts beats three hundred synthetic ones. Pull them from your actual logs, pin temperature=0, and store the expected output so a prompt edit or a model change shows up as a diff in CI instead of as a complaint.

Running the set on both models is how you decide routing honestly. If deepseek-v4-flash clears most of the set, send everything there by default and escalate only the failing categories to deepseek-v4-pro. Pro costs more per call than flash, so escalate by task type rather than by sending every request to the stronger model and hoping.

Check 7: Concurrency, Truncation, and Load Smoke

from concurrent.futures import ThreadPoolExecutor

def load_smoke(client, calls=8, workers=4, model='deepseek-v4-flash'):
    def one(i):
        resp = client.chat.completions.create(
            model=model,
            messages=[{'role': 'user', 'content': f'Reply with the number {i}.'}],
            temperature=0, max_tokens=16,
        )
        return resp.choices[0].finish_reason

    with ThreadPoolExecutor(max_workers=workers) as pool:
        return list(pool.map(one, range(calls)))

print(load_smoke(client))
  • This is a small smoke test, not a load test. It answers one question: does your HTTP client share connections safely when four requests overlap, or does it silently serialize or error?

  • Add a truncation test: pass a deliberately small max_tokens with a long prompt and assert that finish_reason == 'length'. Your application should detect that and either continue the answer or surface a clear message. Shipping half an answer is worse than shipping an error.

  • Run the concurrency check with your real client configuration, including proxies and timeouts. A 30-second default timeout that never fires in development will fire constantly in production.

The Pre-Launch Test Matrix

CheckFailure it catchesPass signal
Smoke + contractWrong model name, missing usage, empty choices`finish_reason` and usage both present
Streaming parityProxy buffering, dropped terminal chunk`finish_reason` received; output length close to buffered run
Retry logicA 429 or 503 leaking through as a user-facing errorRetries succeed; 4xx raised immediately
JSON modeMarkdown fences, trailing prose, partial JSON`json.loads` succeeds on the first attempt
Golden setSilent quality regression after a prompt editAll expected values returned at temperature 0
Concurrency smokeConnection pool starvation under parallel callsEvery future returns without raising
TruncationCut-off answers shipped to users`finish_reason == 'length'` handled explicitly

What to Run Where

  • Every pull request: smoke test, contract assertions, and the JSON parse check. They are short-output calls, so they are the cheapest tier of test to run frequently.

  • Nightly: the full golden set on both deepseek-v4-flash and deepseek-v4-pro, plus the truncation check.

  • Weekly or before a launch: the concurrency smoke test against your real client config, with logging enabled so you can confirm usage metrics land where you expect.

  • Never: retry storms in tests. Cap max_attempts in CI so a failing key does not turn into a loop.

The most expensive integration bug is not the one that breaks the build. It is the one that returns a plausible-looking answer with the wrong shape.

Running This Suite Against AiCredits

AiCredits exposes both deepseek-v4-flash and deepseek-v4-pro behind a single OpenAI-compatible base URL, so the client setup above is the only configuration you need. Accounts are funded with a card or PayPal, and you do not need a Chinese phone number or bank account to get started, which keeps the testing environment simple to provision in CI.

Pricing is usage-based: off-peak requests cost less than peak, cache hits are cheaper than fresh input tokens, and deepseek-v4-pro costs more per call than deepseek-v4-flash. Current rates live at aicreditsapi.com/pricing. Budget the suite accordingly: keep smoke tests on flash with small max_tokens, and reserve pro for the escalation paths your golden set actually justifies.

If you want a second pair of eyes on the test code itself, AiCredits also ships linting tools that flag the usual suspects in API client code, including unretried client instantiation, missing timeouts, and swallowed exceptions.

FAQ

How do I test a DeepSeek API integration without spending much?

Use deepseek-v4-flash for nearly all tests, keep max_tokens small, and pin temperature=0. Contract and JSON checks need a handful of output tokens each, and cached or off-peak requests cost less than peak ones, so a full CI run stays cheap.

Should I test deepseek-v4-pro before launch too?

Yes, but only on the paths that actually use it. Run the same golden set on both models, keep the requests where flash succeeds on flash, and escalate only the categories where pro is genuinely better. That keeps the routing decision evidence-based.

What is the most common pre-launch failure you see?

Ignoring finish_reason. Teams check the content string and never notice that responses are being cut off by max_tokens, or that a stream ends without a terminal chunk.

How many examples should the golden set have?

Start with 20 to 30 prompts taken from real usage rather than invented ones. A small set drawn from production traffic catches more regressions than a large synthetic one that never occurs in your app.

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 ×