AiCredits
Migration Guide

Migrating from OpenAI to DeepSeek: A Drop-In Replacement Checklist

A practical, runnable checklist for moving from OpenAI to DeepSeek with the same SDK: model mapping, streaming, tool calls, fallbacks, and gotchas that bite.

Published 2026-10-20 Updated 2026-10-20 9 min

The SDK swap is easy. The semantics are not.

OpenAI built the interface that most teams already speak: chat completions, streaming SSE, tool calls, and a Python SDK that is copied across the industry. DeepSeek exposes an OpenAI-compatible API, so the first migration step is genuinely a base_url and model-name change. That is why the phrase drop-in replacement is mostly fair.

Mostly is the operative word. OpenAI still has the broadest ecosystem: mature structured outputs, embeddings, moderation, evals, and enterprise controls. If you rely on those, keep them and migrate the chat path first. DeepSeek's strengths are different: strong reasoning models, open weights, long-context work, and a cost profile that rewards routing easy traffic to a fast model. AiCredits exists to remove the billing friction for international developers: you can buy DeepSeek credits with a card or PayPal, no Chinese phone number or bank account required. The checklist below is about the part that breaks silently after the base_url change.

The drop-in replacement checklist

  • Point the OpenAI SDK at https://api.aicreditsapi.com/v1 and use an AiCredits API key from an environment variable.

  • Replace every model string. Use deepseek-v4-flash as the default; reserve deepseek-v4-pro for hard reasoning, architecture, and debugging tasks.

  • Recompute max_tokens and context budgets. Tokenizers differ, so the same prompt can consume a different amount of budget.

  • Re-test system prompts. Be explicit about format, tone, and refusal behavior; do not rely on provider-specific prompt folklore.

  • Verify streaming. Handle empty content deltas and read finish_reason explicitly.

  • Re-run tool-calling tests. Validate arguments against your JSON schema before executing a function.

  • Replace JSON-mode assumptions with an explicit schema in the prompt and a parser with retries.

  • Check sampling parameters you actually use: temperature, top_p, stop sequences, penalties. Drop the ones you do not need.

  • Keep an embedding provider. DeepSeek chat models are not a drop-in replacement for OpenAI embeddings.

  • Add exponential backoff and a model fallback. Do not hard-code OpenAI rate-limit behavior.

  • Log prompt hash, model, token counts, finish_reason, and errors for the first week.

  • Run your eval set on both providers before moving customer-facing traffic.

Step 1: Point the OpenAI SDK at AiCredits

Install the official OpenAI SDK, set one environment variable, and change two arguments. The rest of your request shape stays the same.

# pip install openai
import os
from openai import OpenAI

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

response = client.chat.completions.create(
    model='deepseek-v4-flash',
    messages=[
        {'role': 'system', 'content': 'You are a terse code reviewer.'},
        {'role': 'user', 'content': 'Find the bug: def avg(xs): return sum(xs) / len(xs)'},
    ],
    temperature=0.2,
    max_tokens=300,
)

print(response.choices[0].message.content)

If this call works, you have cleared the mechanical part of the migration. Keep the API key server-side; never ship it in a browser or mobile bundle.

Step 2: Map model names deliberately

A blind find-and-replace is how teams accidentally send every request to the expensive model. Map by task instead. Fast traffic, classification, extraction, summarization, and lint explanations belong on deepseek-v4-flash. Hard debugging, multi-step planning, and architecture review can justify deepseek-v4-pro. Pro costs more than flash, so route it on purpose.

MODEL_MAP = {
    'fast': 'deepseek-v4-flash',
    'deep': 'deepseek-v4-pro',
}

def pick_model(task: str) -> str:
    if task in {'code_review', 'architecture', 'debug_hard'}:
        return MODEL_MAP['deep']
    return MODEL_MAP['fast']

Step 3: Re-test streaming and tool calls

Streaming usually works unchanged, but production code often assumes every chunk has content. Guard for the final chunk and for empty deltas.

import os
from openai import OpenAI

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

stream = client.chat.completions.create(
    model='deepseek-v4-flash',
    messages=[{'role': 'user', 'content': 'List five edge cases for a CSV parser.'}],
    stream=True,
)

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

Tool calling is where drop-in claims deserve skepticism. The shape is OpenAI-style, but you should still validate the model's argument JSON against your schema before you run a function. A bad argument should trigger a retry or a clarification, not a database write.

import json, os
from openai import OpenAI

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

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

resp = client.chat.completions.create(
    model='deepseek-v4-flash',
    messages=[{'role': 'user', 'content': 'Where is order A-1042?'}],
    tools=tools,
    tool_choice='auto',
)

msg = resp.choices[0].message
if msg.tool_calls:
    call = msg.tool_calls[0]
    args = json.loads(call.function.arguments)
    print(call.function.name, args)
else:
    print(msg.content)

Step 4: Ship a fallback wrapper

A migration is not finished until a provider hiccup does not take down your feature. This wrapper retries with backoff, then falls back from flash to pro. Tune the policy to your product: for latency-sensitive chat, retry flash first; for batch jobs, fallback is less urgent.

import os, time
from openai import OpenAI, OpenAIError

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

def complete(prompt: str, system: str = 'You are a precise assistant.') -> str:
    models = ['deepseek-v4-flash', 'deepseek-v4-pro']
    last_error = None
    for model in models:
        for attempt in range(3):
            try:
                resp = client.chat.completions.create(
                    model=model,
                    messages=[
                        {'role': 'system', 'content': system},
                        {'role': 'user', 'content': prompt},
                    ],
                    temperature=0.3,
                    max_tokens=800,
                )
                return resp.choices[0].message.content or ''
            except OpenAIError as exc:
                last_error = exc
                time.sleep(2 ** attempt)
    raise RuntimeError(f'All models failed. Last error: {last_error}')

if __name__ == '__main__':
    print(complete('Explain idempotency keys in two sentences.'))

The differences that are not drop-in

AreaWhat to re-checkPractical move
Model stringsOld model IDs will fail or route differently.Use deepseek-v4-flash as default; deepseek-v4-pro only for hard tasks.
Token limitsTokenizers differ, so the same prompt may consume a different budget.Recompute max_tokens and chunk long inputs; test truncation.
Tool callingSchemas and argument JSON can vary.Validate tool arguments with a schema before executing.
StreamingFinal chunks may carry finish_reason with no content.Guard for empty deltas; handle finish_reason explicitly.
EmbeddingsChat models are not embedding models.Keep OpenAI embeddings or use another provider.
Fine-tunesProvider-specific fine-tune IDs do not move.Re-tune or replace with prompt engineering and few-shot examples.
BillingRates and discounts differ by provider and time.Check aicreditsapi.com/pricing; batch off-peak; enable caching.

Treat the migration as a port, not a string replace. The SDK is compatible; your prompts, evals, tool schemas, and error paths are the real surface area.

A realistic cutover plan

Do not flip all traffic on day one. Start with internal or low-risk tasks: summarizing tickets, explaining lint findings, generating test cases, and drafting documentation. Keep a shadow path to OpenAI for a week and compare outputs on a fixed eval set built from real failures. Log enough to debug: model, prompt hash, token counts, finish_reason, latency, and error class.

  • Week 1: dual-run a small set of internal prompts; fix prompt and schema issues.

  • Week 2: route a slice of non-critical production traffic to deepseek-v4-flash.

  • Week 3: move customer-facing chat if evals hold; keep pro for escalated tasks.

  • Ongoing: batch non-urgent jobs off-peak, cache repeated prompts, and check aicreditsapi.com/pricing for current rates.

AiCredits also sells code linting tools, which fit naturally here: generate or refactor code with DeepSeek, then lint before merge. The migration is not about brand loyalty; it is about routing each task to the model that gives you the best quality-per-cost for that task.

FAQ

Is DeepSeek a true drop-in replacement for OpenAI?

At the SDK and HTTP shape, mostly yes: change base_url and model. At the semantic level, no. Prompts, token limits, tool schemas, structured output, and embeddings need re-testing. Treat it as a port with a checklist, not a find-and-replace.

Do I need a Chinese phone number or bank account to use DeepSeek?

Not through AiCredits. You can buy DeepSeek API credits with a card or PayPal and get an API key without a Chinese phone number or bank account. That is the main reason international developers use AiCredits as the billing layer.

Can I keep using the official OpenAI Python SDK?

Yes. Set base_url to https://api.aicreditsapi.com/v1, use your AiCredits key, and set model to deepseek-v4-flash. The same applies to the Node SDK and most OpenAI-compatible clients.

What should I do about embeddings and fine-tunes?

Keep OpenAI or another provider for embeddings, because DeepSeek chat models are not embedding models. Provider-specific fine-tune IDs do not migrate either; plan to re-tune or replace that work with prompt engineering and few-shot examples.

How do I control cost after migrating?

Route most traffic to deepseek-v4-flash, reserve deepseek-v4-pro for hard tasks, batch non-urgent work off-peak, and cache repeated prompts. Cache hits are cheaper, off-peak costs less, and pro costs more than flash. Check aicreditsapi.com/pricing for current rates.

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 ×