DeepSeek Python SDK: Setup, Examples, and Troubleshooting

Last reviewed: November 16, 2026.

To use DeepSeek from Python, install the openai package and configure it with a DeepSeek API key, https://api.deepseek.com as the base URL, and a current DeepSeek model ID. This is the approach shown in the official DeepSeek API quickstart.

The phrase DeepSeek Python SDK can also refer to the separate DeepSeek Harness SDK for agents. This guide explains which package to choose, then walks through a small Python project for chat requests, streaming, asynchronous calls, conversation history, and JSON output.

Which Python SDK should you use for DeepSeek?

Your goalPackage or approachWhat it provides
Call the hosted DeepSeek APIopenaiA Python client configured to send requests to DeepSeek.
Run an agent through DeepSeek Harnessdeepseek-harness-sdkThe Harness runtime integration, profiles, and sessions.
Use a separately maintained DeepSeek wrapperCheck the specific package and publisherIts own interface and maintenance policy; compatibility depends on that project.

For ordinary API calls, start with openai. Its name identifies the client library; the configured endpoint determines where it sends your requests. The examples below use DeepSeek credentials and DeepSeek infrastructure.

Official DeepSeek Python API example using the OpenAI SDK with DeepSeek base URL and model configuration

A package named deepseek-sdk exists on PyPI, but its name alone does not establish that DeepSeek publishes or recommends it. Its imports also differ from those used here. Avoid mixing examples from different packages in the same script.

If your goal is an agent runtime with tools and sessions, use the official Harness Python SDK guide. Installing that package is a different setup from installing an HTTP API client.

 Official DeepSeek Harness Python SDK installation guide showing prerequisites and Windows PowerShell commands

Install the client and set your API key

You need Python 3.10 or later for the current OpenAI Python library, an internet connection, and a key from the DeepSeek API platform. Check your API account balance before running paid inference requests.

1. Create an isolated Python environment

macOS or Linux:

mkdir deepseek-python-demo
cd deepseek-python-demo
python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade openai

Windows PowerShell:

mkdir deepseek-python-demo
cd deepseek-python-demo
py -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install --upgrade openai

Use python -m pip so installation targets the same Python interpreter you are running. Confirm the environment before continuing:

python --version
python -c "import openai; print(openai.__version__)"
VS Code terminal showing Python 3.13.15 and OpenAI SDK 3.57.0 installed in a virtual environment

If PowerShell prevents activation, you can call the environment’s interpreter directly: .\.venv\Scripts\python.exe -m pip install --upgrade openai. Use that same interpreter when running the examples.

2. Set DEEPSEEK_API_KEY

Replace the placeholder with your own DeepSeek API key in your local terminal. These commands set it for the current shell session.

DeepSeek API platform dashboard showing the Create new API key button and API key management section

macOS or Linux:

export DEEPSEEK_API_KEY="replace-with-your-deepseek-key"

Windows PowerShell:

$env:DEEPSEEK_API_KEY = "replace-with-your-deepseek-key"

Keep the real key out of source files, public notebooks, screenshots, and Git commits. Terminal commands may be saved in shell history; use your deployment platform’s secret settings for a deployed application. Creating a .env file alone does not load its contents into Python.

Make your first DeepSeek API call in Python

Create the following two files in your project folder. Later examples reuse the configuration file, so you can change the model or connection settings in one place.

Save as deepseek_config.py:

import os

MODEL = os.getenv("DEEPSEEK_MODEL", "deepseek-flash")


def client_options():
    return {
        "api_key": os.environ["DEEPSEEK_API_KEY"],
        "base_url": "https://api.deepseek.com",
        "timeout": 90.0,
        "max_retries": 2,
    }

Save as quickstart.py:

from openai import OpenAI
from deepseek_config import MODEL, client_options

with OpenAI(**client_options()) as client:
    response = client.chat.completions.create(
        model=MODEL,
        messages=[{
            "role": "user",
            "content": "Explain a Python dictionary in two sentences.",
        }],
        max_tokens=300,
        extra_body={"thinking": {"type": "disabled"}},
    )

choice = response.choices[0]
answer = (choice.message.content or "").strip()
if choice.finish_reason != "stop" or not answer:
    raise RuntimeError(f"No complete answer: {choice.finish_reason}")

print(answer)
if response.usage:
    print("Total tokens:", response.usage.total_tokens)

Run the request from that folder:

python quickstart.py

A successful run prints a short explanation and, when reported, the token count. The exact wording and token usage can vary. The context manager closes the client’s HTTP resources after the request.

Save every later example in this same folder, alongside deepseek_config.py, and run it with python filename.py. Keep the virtual environment active and the API key available in that terminal.

SettingWhy it matters
api_keyReads your DeepSeek key explicitly. A missing environment variable fails locally.
base_urlPoints the client at DeepSeek. Supply the API root, not the full /chat/completions endpoint.
modelSelects the model ID sent to the API.
max_tokensCaps this request’s output budget.
extra_bodyCarries DeepSeek-specific request fields such as the thinking toggle.

Thinking is enabled by default in the current API. This first example explicitly disables it to keep the request focused on a short answer. See the thinking mode documentation for the provider-specific controls.

The Chat Completions reference distinguishes a completed response from a truncated or interrupted one through finish_reason. In these plain-text examples, accept stop; investigate length or other values before using the output. Completion does not establish factual accuracy.

Choose a current model and control thinking

At the review date, the official model table lists these API IDs:

API model IDDocumented model versionThinking modes
deepseek-flashDeepSeek-V4.1-Flash-1017Thinking and non-thinking
deepseek-v4-proDeepSeek-V4-Pro-0813Thinking and non-thinking
Official DeepSeek API model comparison showing deepseek-flash and deepseek-v4-pro versions and thinking modes

Start with the default used in this guide, then compare models on examples from your application. Evaluate answer quality, latency, and actual usage together. A model that handles one task well is not automatically the best choice for every workload.

Older tutorials may use deepseek-chat, deepseek-reasoner, or deepseek-v4-flash. Prefer the current documented IDs for new code. To inspect the models currently exposed by the models endpoint, save this as list_models.py:

from openai import OpenAI
from deepseek_config import client_options

with OpenAI(**client_options()) as client:
    for model in client.models.list().data:
        print(model.id)

To enable thinking, use the same model with thinking.type set to enabled. Save this as thinking_example.py:

from openai import OpenAI
from deepseek_config import MODEL, client_options

with OpenAI(**client_options()) as client:
    response = client.chat.completions.create(
        model=MODEL,
        messages=[{
            "role": "user",
            "content": "How would you detect duplicate orders safely?",
        }],
        max_tokens=4096,
        reasoning_effort="high",
        extra_body={"thinking": {"type": "enabled"}},
    )

choice = response.choices[0]
answer = (choice.message.content or "").strip()
if choice.finish_reason != "stop" or not answer:
    raise RuntimeError(f"No complete answer: {choice.finish_reason}")
print(answer)

The final answer is in message.content; the separate reasoning_content field contains the model’s reasoning output. The example prints only the answer. Allow a larger output budget when using thinking, and check for truncation. Parameters such as temperature do not affect thinking mode; see the documented parameter behavior.

DeepSeek Thinking Mode documentation showing reasoning effort levels and Python API configuration

Stream a DeepSeek response in Python

Streaming lets your interface display text as it arrives. With Chat Completions, read incremental text from delta.content. Save this as stream_example.py:

from openai import OpenAI
from deepseek_config import MODEL, client_options

finish_reason = None
parts = []

with OpenAI(**client_options()) as client:
    stream = client.chat.completions.create(
        model=MODEL,
        messages=[{
            "role": "user",
            "content": "Give three tips for readable Python functions.",
        }],
        max_tokens=500,
        stream=True,
        extra_body={"thinking": {"type": "disabled"}},
    )
    try:
        for chunk in stream:
            if not chunk.choices:
                continue
            choice = chunk.choices[0]
            text = choice.delta.content or ""
            parts.append(text)
            print(text, end="", flush=True)
            if choice.finish_reason is not None:
                finish_reason = choice.finish_reason
    finally:
        stream.close()

print()
if finish_reason != "stop" or not "".join(parts).strip():
    raise RuntimeError(f"Stream incomplete: {finish_reason}")

In an application, mark displayed text as provisional until the stream finishes successfully. A connection that ends after a few chunks can leave you with readable but incomplete text. Keep any partial result separate from the completed answer.

DeepSeek documents the chunk format and final completion state in its streaming response schema. Its Responses API uses a different event format, covered below.

Use AsyncOpenAI for asynchronous requests

Use AsyncOpenAI when integrating with an asynchronous application. The SDK’s async client uses await for requests. Save this as async_example.py:

import asyncio
from openai import AsyncOpenAI
from deepseek_config import MODEL, client_options


async def main():
    async with AsyncOpenAI(**client_options()) as client:
        response = await client.chat.completions.create(
            model=MODEL,
            messages=[{
                "role": "user",
                "content": "Explain an HTTP timeout in one sentence.",
            }],
            max_tokens=300,
            extra_body={"thinking": {"type": "disabled"}},
        )
        choice = response.choices[0]
        answer = (choice.message.content or "").strip()
        if choice.finish_reason != "stop" or not answer:
            raise RuntimeError(f"No complete answer: {choice.finish_reason}")
        print(answer)


if __name__ == "__main__":
    asyncio.run(main())

Run it with python async_example.py. In a notebook that already runs an event loop, omit the final if __name__ == "__main__": block and run await main() in a cell instead. Python does not allow asyncio.run() inside another running event loop in the same thread.

Async allows other work to proceed while a request waits; it does not inherently make one model response faster. For many requests, add a queue or an asyncio.Semaphore rather than launching an unbounded batch. DeepSeek applies account-level concurrency limits, so creating more API keys does not create separate account quotas.

Keep conversation history between requests

A normal Chat Completions request does not remember your previous call automatically. Send the relevant user and assistant messages again, as described in the multi-round conversation guide. Save this as conversation_example.py:

Official DeepSeek Python example showing multi-round conversation history using messages.append
from openai import OpenAI
from deepseek_config import MODEL, client_options

messages = [{"role": "system", "content": "Give concise Python explanations."}]
questions = [
    "What is a Python generator?",
    "Show a small example of the concept you just explained.",
]

with OpenAI(**client_options()) as client:
    for question in questions:
        messages.append({"role": "user", "content": question})
        response = client.chat.completions.create(
            model=MODEL,
            messages=messages,
            max_tokens=600,
            extra_body={"thinking": {"type": "disabled"}},
        )
        choice = response.choices[0]
        answer = (choice.message.content or "").strip()
        if choice.finish_reason != "stop" or not answer:
            raise RuntimeError(f"No complete answer: {choice.finish_reason}")
        messages.append({"role": "assistant", "content": answer})
        print(answer)

This example makes two billable inference requests. In a chatbot, keep each user’s history separate and decide how much past context each new request needs. Long histories increase input usage; summarize or trim them deliberately instead of silently dropping context.

This pattern covers plain text without tools. When adding tools or server-side features, follow their documented history format. Also, “stateless” describes how you supply conversation context; it is not a claim about the provider’s data retention policy.

Request JSON and validate the result

For machine-readable output, set response_format={"type": "json_object"}, explicitly request JSON, and show the desired shape. DeepSeek’s JSON Output guide also warns that a response can contain only whitespace, even when its completion state is stop.

Official DeepSeek JSON Output documentation showing response_format settings and blank response warnings

The following example classifies a fictional support ticket. Save it as json_example.py:

import json
from openai import OpenAI
from deepseek_config import MODEL, client_options

with OpenAI(**client_options()) as client:
    response = client.chat.completions.create(
        model=MODEL,
        messages=[
            {
                "role": "system",
                "content": (
                    'Return only JSON like {"category":"account",'
                    '"summary":"Short description"}. '
                    'Category must be account, billing, or technical.'
                ),
            },
            {"role": "user", "content": "I cannot reset my password."},
        ],
        response_format={"type": "json_object"},
        max_tokens=400,
        extra_body={"thinking": {"type": "disabled"}},
    )

choice = response.choices[0]
raw = (choice.message.content or "").strip()
if choice.finish_reason != "stop" or not raw:
    raise ValueError("The JSON response is incomplete or blank.")

data = json.loads(raw)
if not isinstance(data, dict) or set(data) != {"category", "summary"}:
    raise ValueError("Unexpected JSON fields.")
if not isinstance(data["category"], str):
    raise ValueError("Category must be a string.")
if data["category"] not in {"account", "billing", "technical"}:
    raise ValueError("Unexpected category.")
if not isinstance(data["summary"], str) or not data["summary"].strip():
    raise ValueError("Summary must be a nonempty string.")

print(data)

There are three separate checks: the response finished, the content parses as JSON, and the parsed object satisfies your application’s rules. A valid JSON object can still contain the wrong fields or an incorrect classification. For larger schemas, move validation into a dedicated model or schema validator.

Handle a failed validation as a distinct application outcome. You might request a corrected result once, route the item for review, or reject it. Avoid a retry loop that keeps spending tokens without changing the failed condition.

Add a small function-calling workflow

With a custom function tool, the model returns a function name and arguments. Your Python application validates them, runs the allowed function, sends back its result, and requests the next response. DeepSeek documents this sequence in its Tool Calls guide.

Official DeepSeek function calling workflow showing the four steps of tool execution and model response

This example uses a read-only function containing fictional help-desk hours. Save it as tool_example.py:

import json
from openai import OpenAI
from deepseek_config import MODEL, client_options


def get_support_hours():
    return {"hours": "Monday-Friday, 09:00-17:00 UTC", "demo_data": True}


tools = [{
    "type": "function",
    "function": {
        "name": "get_support_hours",
        "description": "Read the fictional help desk's support hours.",
        "parameters": {"type": "object", "properties": {}},
    },
}]
messages = [{
    "role": "user",
    "content": "Use the support-hours tool and tell me when the demo desk opens.",
}]

with OpenAI(**client_options()) as client:
    for step in range(3):
        response = client.chat.completions.create(
            model=MODEL,
            messages=messages,
            tools=tools,
            tool_choice="required" if step == 0 else "auto",
            max_tokens=400,
            extra_body={"thinking": {"type": "disabled"}},
        )
        choice = response.choices[0]
        message = choice.message

        if choice.finish_reason == "stop" and not message.tool_calls:
            answer = (message.content or "").strip()
            if not answer:
                raise RuntimeError("The final answer is blank.")
            print(answer)
            break

        if choice.finish_reason != "tool_calls" or not message.tool_calls:
            raise RuntimeError(f"Unexpected completion: {choice.finish_reason}")

        messages.append(message)
        for call in message.tool_calls:
            if call.type != "function" or call.function.name != "get_support_hours":
                raise ValueError("Unknown tool.")
            if json.loads(call.function.arguments) != {}:
                raise ValueError("This tool accepts no arguments.")
            messages.append({
                "role": "tool",
                "tool_call_id": call.id,
                "content": json.dumps(get_support_hours()),
            })
    else:
        raise RuntimeError("The tool loop reached its request limit.")

The first request requires a tool call; later requests allow the model to finish its answer. The loop permits at most three model calls. Its function only reads fixed demo data. For a real tool, validate arguments and authorization before performing external actions.

The example disables thinking. If you combine thinking with tools, preserve the required reasoning_content in subsequent requests, including prior turns, as specified in the thinking-with-tools instructions. Do not rebuild that history using only the visible answer text.

Use the Responses API when your application needs it

DeepSeek also documents client.responses.create() with the same API base URL. You can use it with the same configuration file. Save this as responses_example.py:

from openai import OpenAI
from deepseek_config import MODEL, client_options

with OpenAI(**client_options()) as client:
    response = client.responses.create(
        model=MODEL,
        instructions="Answer in plain English.",
        input="What problem does a Python virtual environment solve?",
        reasoning={"effort": "none"},
        max_output_tokens=300,
    )

if response.status != "completed" or not response.output_text.strip():
    raise RuntimeError(f"No complete response: {response.status}")
print(response.output_text)
TaskChat CompletionsResponses
Send inputmessagesinput, optionally instructions
Read final textchoices[0].message.contentoutput_text
Set the output budgetmax_tokensmax_output_tokens
Disable thinkingextra_body={"thinking":{"type":"disabled"}}reasoning={"effort":"none"}

Check DeepSeek’s Responses compatibility guide before migrating an application. Features such as previous_response_id, conversation, and background are unsupported; you cannot rely on them for stored conversation state or background execution. Streaming uses events such as response.output_text.delta, not Chat Completions chunks.

Official DeepSeek Responses API compatibility table showing unsupported conversation, storage, and background parameters

Choose the interface that fits your existing application. The availability of a method in the OpenAI package does not, by itself, establish that DeepSeek implements every option behind it.

Troubleshoot installation and API errors

First determine where the failure occurs: importing Python code, connecting to the service, receiving an HTTP response, or validating generated content. That distinction is more useful than repeatedly reinstalling packages.

SymptomLikely issueWhat to check
ModuleNotFoundError: openaiPackage installed in another environmentUse python -m pip show openai with the interpreter running the script.
ImportError involving openaiOld installation or a local module shadowing the packageCheck the installed version and avoid naming your script openai.py.
KeyError: DEEPSEEK_API_KEYEnvironment variable is absentSet it in the same terminal or deployment environment as the Python process.
HTTP 401Authentication failedCheck the DeepSeek key and the configured base URL.
HTTP 402Insufficient DeepSeek balanceCheck the API account balance; retries do not add funds.
HTTP 400 or 422Invalid body or parametersRead the error details, verify the model, and check provider-specific field placement.
HTTP 429Rate or concurrency limitReduce concurrent requests and use bounded backoff.
HTTP 500 or 503Server error or overloadRetry transient failures within a defined limit.
finish_reason="length"Generation reached an applicable limitReview the input and output budget before using the partial answer.
Blank or rejected JSONOutput could not be used as the requested objectCheck completion, whitespace, JSON syntax, and field validation separately.
Official DeepSeek API error codes table showing HTTP errors, causes, and recommended solutions

The HTTP meanings above follow DeepSeek’s error-code reference. SDK exceptions are defined by the OpenAI Python library. For example, HTTP 402 can be handled through APIStatusError.status_code; there is no need to invent a separate balance-error class.

Timeouts and retries

The shared configuration sets timeout=90.0 and max_retries=2 explicitly. The SDK retry policy covers eligible connection failures and certain HTTP errors. This transport timeout is not a guarantee that the entire operation, including retries, finishes within 90 seconds.

Avoid stacking an unlimited application retry loop on top of the SDK’s retries. Also handle interrupted streams explicitly: once partial output has been delivered, automatically starting the same request again can duplicate content. Configure a separate overall deadline when your application needs one.

Monitor usage and control costs

The usage object reports token consumption. For Chat Completions, inspect prompt_tokens, completion_tokens, and total_tokens. DeepSeek also reports cache-hit and cache-miss information; its context caching guide explains those fields.

Estimate costs using the current official pricing table, the selected model, cached versus uncached input, and generated output. Check any applicable time-based rates or additional tool charges. Installing the Python package does not include paid API usage.

  • Set an output budget appropriate to the task, then watch for truncation.
  • Send only the conversation history the request needs.
  • Use thinking deliberately and compare its results with your task requirements.
  • Record the model, completion state, latency, and usage without logging secret keys.
  • Limit concurrency and tool-loop iterations before scaling a workflow.

For repeatable deployments, record the dependency version that passed your own checks. After an upgrade or model change, rerun a small set of representative tasks before increasing traffic.

Frequently asked questions

Is there an official DeepSeek Python SDK?

For direct model requests, DeepSeek’s official quickstart uses the OpenAI Python client configured for DeepSeek. The separate official DeepSeek Harness Python SDK serves agent-runtime workflows. Specify which integration you mean when choosing a package.

Do I need an OpenAI API key?

No. These examples use a DeepSeek API key and send requests to DeepSeek. The openai package is the client library; it does not turn your DeepSeek request into an OpenAI-billed request.

Is using DeepSeek from Python free?

The client library and hosted inference are separate. Check your DeepSeek API balance and current pricing before running requests. Do not assume access to a consumer chat interface includes API credits.

Do I need a GPU?

No local GPU is required for the hosted API examples in this guide. Your script sends network requests to the service. Running downloaded model weights locally is a separate setup with different software and hardware requirements.

Why does an older DeepSeek R1 Python example fail?

Check its package version, base URL, and model ID. An old tutorial may target a retired or changed API configuration. Use the current model list and thinking controls instead of assuming a historical model name still selects the same model.

Can I use these examples in Flask or FastAPI?

Yes, as a starting integration pattern. Keep the key on the server, reuse an appropriately managed client, and apply request limits and output validation. In an async route, use the async client so a blocking request does not stall the event loop. Add application-level authentication before exposing a paid endpoint to users.