AiCredits
Migration Guide

Use DeepSeek API with the OpenAI SDK: Three-Line Migration Guide

Swap three lines and your existing OpenAI SDK code runs on DeepSeek. Migration guide with runnable streaming, JSON mode, tool-calling, and retry examples.

Published 2026-09-21 Updated 2026-09-21 6 min

If your codebase already talks to the OpenAI SDK, you do not need a DeepSeek-specific client, a new HTTP layer, or a rewrite of your response parsing. DeepSeek's API speaks the same chat-completions wire format the SDK already knows how to serialize and deserialize. The migration is genuinely three lines.

This guide shows the swap, then covers the four things that actually trip people up mid-migration: streaming, JSON output, tool calls, and retries. Every snippet below is runnable as written against AiCredits' OpenAI-compatible endpoint.

The Three Lines That Change

Assuming you have a working script today, the diff is: the API key, the base URL, and the model string. Nothing else moves. Point the client at AiCredits, pass your AiCredits key, and name the model you want.

from openai import OpenAI

client = OpenAI(
    api_key="YOUR_AICREDITS_KEY",
    base_url="https://api.aicreditsapi.com/v1",
)

resp = client.chat.completions.create(
    model="deepseek-v4-flash",
    messages=[
        {"role": "system", "content": "You are a terse senior engineer."},
        {"role": "user", "content": "Explain idempotency keys in two sentences."},
    ],
)

print(resp.choices[0].message.content)
print(resp.usage)

That is the whole migration for a basic completion. resp is the same ChatCompletion object type you already handle, resp.usage is populated with prompt and completion token counts, and resp.choices[0].message.content is a plain string.

Why a Base-URL Swap Is Enough

The SDK is mostly a typed wrapper around JSON over HTTPS. When you override base_url, every request the library builds — headers, body shape, retry behavior, streaming decoder — goes to the new host unchanged. That makes the compatibility surface wider than a single endpoint.

  • Message roles, system prompts, and multi-turn history arrays carry over as-is.

  • Streaming: the SDK's SSE parser reads DeepSeek chunks with no modification.

  • Tool calling: tools request schemas and tool_calls responses use the same shape.

  • JSON mode: response_format={"type": "json_object"} is honored.

  • Usage accounting: prompt and completion token counts arrive on the response object.

  • Client-level settings you already configured — timeouts, retry counts, proxies — keep applying.

Streaming Works With the Same Loop

stream = client.chat.completions.create(
    model="deepseek-v4-flash",
    messages=[{"role": "user", "content": "Write a haiku about cache invalidation."}],
    stream=True,
)

for chunk in stream:
    delta = chunk.choices[0].delta.content
    if delta:
        print(delta, end="", flush=True)
print()

One habit worth keeping from day one: guard on delta being None. The final chunks carry a finish_reason and no content, so a naive print(chunk.choices[0].delta.content) throws a TypeError at exactly the wrong moment — after a long generation, in front of a user.

Structured Output Without a New Parser

If you already use JSON mode, keep using it. Put the schema in the prompt, set response_format, and parse with json.loads as usual. Do not let the model invent field names; spell out the exact keys you expect.

import json

instructions = (
    "Review the code below. Reply with JSON only, using exactly these keys: "
    '{"severity": "info"|"warn"|"error", "line": <int>, "message": <string>}'
)

resp = client.chat.completions.create(
    model="deepseek-v4-flash",
    messages=[
        {"role": "system", "content": "You are a code linter. Output JSON only."},
        {"role": "user", "content": instructions + "\n\nx = 1\nprint(x)"},
    ],
    response_format={"type": "json_object"},
)

finding = json.loads(resp.choices[0].message.content)
print(finding["severity"], finding["line"], finding["message"])

A caveat that bites people during migration: JSON mode guarantees syntactically valid JSON, not a valid schema. Validate the parsed dict against a Pydantic model or JSON Schema before the value reaches your database. A short validation step saves hours of downstream debugging, and it doubles as the trigger for escalating a call to the stronger model — more on that below.

Tool Calling Uses the Same Shapes

tools = [
    {
        "type": "function",
        "function": {
            "name": "lookup_order",
            "description": "Look up an order by ID and return its status.",
            "parameters": {
                "type": "object",
                "properties": {"order_id": {"type": "string"}},
                "required": ["order_id"],
            },
        },
    }
]

messages = [{"role": "user", "content": "Where is order A-1042?"}]

resp = client.chat.completions.create(
    model="deepseek-v4-flash",
    messages=messages,
    tools=tools,
)

call = resp.choices[0].message.tool_calls[0]
print(call.function.name)       # lookup_order
print(call.function.arguments)  # {"order_id": "A-1042"}

# Round-trip: hand the tool result back and let the model answer.
messages.append(resp.choices[0].message)
messages.append(
    {
        "role": "tool",
        "tool_call_id": call.id,
        "content": '{"order_id": "A-1042", "status": "in transit"}',
    }
)

final = client.chat.completions.create(
    model="deepseek-v4-flash",
    messages=messages,
)
print(final.choices[0].message.content)

Note that call.function.arguments is a JSON string, not a dict — you json.loads it before use. That behaviour is identical on both backends, but it is the detail people forget when they copy a migration snippet out of a blog post.

flash or pro: Choose Per Call Site

Signaldeepseek-v4-flashdeepseek-v4-pro
Typical jobChat, extraction, classification, linting at volumeMulti-step reasoning, tricky refactors, long-horizon planning
Relative pricingThe cheaper default per callCosts more than flash, so spend it deliberately
Latency feelSnappier first tokenThinks longer before answering
Where it belongsThe default for every new call siteEscalation only, behind validation

The pragmatic pattern is routing, not a single global model constant. Define both IDs in one config module, default everything to flash, and add a narrow escalation path: when a flash answer fails your own validation — a schema check, a unit test, a regex assertion — retry once with pro and log which call sites escalated. Within a day you will know the shape of your own workload instead of guessing.

Two things move the pricing needle in your favor without any code change. Prompt caching means repeated system prompts and shared context cost less on cache hits, so keep system prompts stable and put variable content in the user turn. Off-peak scheduling means the same request costs less outside peak hours, which makes non-interactive batch jobs worth moving to a queue. Current rates for both models are on the pricing page at aicreditsapi.com/pricing.

Make the Migration Production-Safe

The SDK retries some failures for you, but a migration is a good moment to own the policy explicitly — especially since you want 4xx errors to fail fast rather than repeat.

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

client = OpenAI(
    api_key="YOUR_AICREDITS_KEY",
    base_url="https://api.aicreditsapi.com/v1",
    timeout=30.0,
    max_retries=0,  # retries handled below so the policy is visible
)

def complete(prompt, model="deepseek-v4-flash", tries=4):
    delay = 1.0
    for attempt in range(1, tries + 1):
        try:
            resp = client.chat.completions.create(
                model=model,
                messages=[{"role": "user", "content": prompt}],
            )
            return resp.choices[0].message.content
        except (RateLimitError, APIConnectionError):
            if attempt == tries:
                raise
        except APIStatusError as err:
            if err.status_code < 500 or attempt == tries:
                raise
        time.sleep(delay)
        delay *= 2

print(complete("Summarize what a connection pool does in one sentence."))
  • Keep model IDs in one place. A single MODEL = "deepseek-v4-flash" constant beats a find-and-replace later when you start routing to pro.

  • Leave your prompts unchanged for the first deploy. Change transport, measure, then tune prompts — otherwise you cannot tell which change moved the needle.

  • Log resp.usage per call site so you can see which feature actually drives spend.

  • Never retry 4xx. A malformed request or bad key fails identically every time and just burns your rate limit.

  • Set an explicit client timeout. A stuck request is worse than a failed one you can handle.

  • Run your existing test suite before touching anything else — it is a free compatibility check.

Getting a Key Without the Usual Friction

For developers outside China, the practical blocker is rarely the SDK — it is payment. AiCredits sells DeepSeek API credits to international developers by card or PayPal, with no Chinese phone number or bank account required, and the endpoint used throughout this article is the OpenAI-compatible one. If you also want to catch the small stuff while you migrate — unused imports, dead retry branches, the None delta bug above — the code linting tools on the same account will flag them before they reach production.

FAQ

Do I need to install a DeepSeek-specific SDK?

No. The openai package for Python or Node is all you need. Change base_url, change api_key, change model, and your existing code runs.

Will my streaming code break?

No. The SDK's SSE parser handles the chunks unchanged. Just guard against None deltas, since the final chunk carries a finish reason and no content.

Does function calling work the same way?

Yes — same tools schema, same tool_calls response, and the same round-trip where you append the assistant message and a tool role message before asking for the final answer.

What if I am still pointing at a retired model ID?

Those requests will fail. Move to deepseek-v4-flash as your default and reserve deepseek-v4-pro for calls that genuinely need deeper reasoning.

How do I decide between flash and pro?

Default to flash everywhere, then escalate specific call sites to pro only when your own validation rejects a flash answer. Log the escalations so the decision stays data-driven.

Where do I see current pricing?

Rates for both models are listed at aicreditsapi.com/pricing.

The migration is three lines. The actual work is deciding which call sites deserve the pro model — start with flash everywhere, measure, and escalate deliberately.

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 ×