DeepSeek API Guide: Setup, V4 Models and Working Examples

The DeepSeek API uses the OpenAI-compatible base URL https://api.deepseek.com. Create an API key, choose deepseek-v4-flash or deepseek-v4-pro, and send requests through Chat Completions or the Responses API. Both current V4 models support the Responses API.

This independent DeepSeek API guide provides working cURL, PowerShell, Python, and Node.js examples; explains the current V4 models, pricing, thinking mode, streaming, tools, errors, and context caching; and publishes redacted results from our own API checks. Current documentation and pricing were last verified on ; dated API test results remain tied to their recorded run dates. Chat-Deep.ai is not the official DeepSeek Platform.

DeepSeek API quick reference

SettingCurrent value
OpenAI-compatible base URLhttps://api.deepseek.com
Chat endpointPOST /chat/completions
Responses endpointPOST /responses — supported by Flash and Pro
Current model IDsdeepseek-v4-flash, deepseek-v4-pro
Current model versionsDeepSeek-V4-Flash-0731, DeepSeek-V4-Pro-0813
AuthenticationAuthorization: Bearer $DEEPSEEK_API_KEY
Context window1M tokens for both current V4 models
Maximum output384K tokens for both current V4 models
Dated live verificationAugust 3: Chat Flash and Pro passed 3/3; Responses Flash passed 3/3; Responses Pro returned HTTP 400 before the August 13 GA release.
Current official contractAugust 14: Pro-0813 is GA, and both current models support Responses.

Create an official DeepSeek API key or jump to the 60-second quickstart. For account setup and key safety, use our dedicated DeepSeek API key guide.

DeepSeek API quickstart in 60 seconds

1. Create and store an API key

Sign in to the official DeepSeek Platform, create a key, and copy it once. Never paste a real key into browser tools, frontend JavaScript, screenshots, public repositories, or support messages.

Store the key in an environment variable for the current terminal session:

# macOS or Linux
export DEEPSEEK_API_KEY="replace-with-your-key"
# Windows PowerShell
$env:DEEPSEEK_API_KEY = "replace-with-your-key"

2. Send a minimal request

This cURL request uses the current Flash model and explicitly disables thinking for a short connectivity check:

curl --silent --show-error --fail \
  https://api.deepseek.com/chat/completions \
  -H "Authorization: Bearer $DEEPSEEK_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek-v4-flash",
    "messages": [
      {"role": "user", "content": "Reply with exactly: API_OK"}
    ],
    "thinking": {"type": "disabled"},
    "max_tokens": 16
  }'

A successful response is HTTP 200. Read the answer from choices[0].message.content and token counts from usage. The API can include other documented response fields, so production code should validate required fields without rejecting harmless additions.

3. Separate authentication, balance, and service health

A valid key is not proof of sufficient credit, and a funded account is not proof that every model is healthy. Use the read-only DeepSeek balance endpoint for current funding availability and DeepSeek status for incident checks.

For dated multi-region measurements rather than a provider SLA, use our independent DeepSeek API reliability and performance report, which publishes validated observations, latency percentiles, and downloadable data.

DeepSeek V4 models and current API status

DeepSeek's August 13, 2026 change log rolled out DeepSeek-V4-Pro-0813 as GA on App, Web, and API. The deepseek-v4-pro request ID did not change. Flash continues to serve DeepSeek-V4-Flash-0731 in public beta behind deepseek-v4-flash.

Capabilitydeepseek-v4-flashdeepseek-v4-pro
Version listed by DeepSeekDeepSeek-V4-Flash-0731DeepSeek-V4-Pro-0813
Current release statusOfficial API release in public betaGA on App, Web, and API
Context window1M tokens1M tokens
Maximum output384K tokens384K tokens
Thinking and non-thinkingSupportedSupported
Responses APISupportedSupported
JSON outputSupportedSupported
Tool callsSupportedSupported
Anthropic API formatSupportedSupported
Documented account concurrency2,500500

Dated test boundary: our August 3 live test returned HTTP 400 for Pro Responses before the August 13 GA rollout. That result remains valid evidence for its test date, but it is not the current support contract. The current Responses API reference lists both V4 model IDs.

The older names deepseek-chat and deepseek-reasoner were scheduled for discontinuation on July 24, 2026. New code should use the V4 model IDs. Our live compatibility table records what the legacy names actually returned at the verification time without treating a past schedule as present availability.

Redacted live DeepSeek API model catalog and compatibility test showing the current V4 model IDs and observed endpoint support.
Live model and endpoint verification on August 3, 2026. Credentials and account data are redacted.

Working DeepSeek API examples

Every example in this section is designed to run as shown after the environment variable is set. The validation table records the exact runtime, dependency version, exit status, HTTP status, and observed output from the published blocks.

Windows PowerShell

$headers = @{
  Authorization = "Bearer $env:DEEPSEEK_API_KEY"
  "Content-Type" = "application/json"
}

$body = @{
  model = "deepseek-v4-flash"
  messages = @(
    @{ role = "user"; content = "Reply with exactly: API_OK" }
  )
  thinking = @{ type = "disabled" }
  max_tokens = 16
} | ConvertTo-Json -Depth 5

$response = Invoke-RestMethod `
  -Method Post `
  -Uri "https://api.deepseek.com/chat/completions" `
  -Headers $headers `
  -Body $body

$response.choices[0].message.content

Python with the OpenAI SDK

Install the current OpenAI Python package with python -m pip install --upgrade openai, then run:

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["DEEPSEEK_API_KEY"],
    base_url="https://api.deepseek.com",
)

response = client.chat.completions.create(
    model="deepseek-v4-flash",
    messages=[
        {"role": "user", "content": "Reply with exactly: API_OK"}
    ],
    max_tokens=16,
    extra_body={"thinking": {"type": "disabled"}},
)

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

For setup, typed parsing, streaming, async calls, and environment troubleshooting, see the full DeepSeek Python SDK guide.

Node.js with the OpenAI package

Install the dependency with npm install openai. Save this as an ES module such as deepseek.mjs:

import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.DEEPSEEK_API_KEY,
  baseURL: "https://api.deepseek.com",
});

const response = await client.chat.completions.create({
  model: "deepseek-v4-flash",
  messages: [
    { role: "user", content: "Reply with exactly: API_OK" },
  ],
  thinking: { type: "disabled" },
  max_tokens: 16,
});

console.log(response.choices[0].message.content);

Use the dedicated DeepSeek Node.js and TypeScript guide for strict TypeScript typing, server frameworks, and production project structure.

Exact code validation results

We copied each block from the saved article without rewriting it. Python and Node.js were executed against the live API with the temporary environment variable; cURL and PowerShell were executed unchanged against a local contract endpoint because the Windows test runner’s TLS stack failed before it could deliver those two live requests. The key, full response body, request ID, and account data were not published.

ExampleEnvironmentDependencyHTTPObserved outputResult
cURLcurl 7.55.1 on Windows 11NoneLocal mock 200API_OKContract pass; not a live API run
PowerShellPowerShell 5.1.21996.1 on Windows 11NoneLocal mock 200API_OKContract pass; not a live API run
PythonPython 3.12.13 on Windows 11openai 2.48.0Live 200API_OKPass
Node.jsNode.js 24.14.0 on Windows 11openai 6.49.0Live 200API_OKPass

The Python and Node.js blocks were executed live exactly as published. The cURL and PowerShell request shapes, headers, JSON bodies, and output selectors passed unchanged against a local contract endpoint, but are not presented as live executions because the runner’s Windows TLS stack failed before those requests reached DeepSeek.

DeepSeek Responses API: support and differences

DeepSeek's native Responses API now supports both deepseek-v4-flash and deepseek-v4-pro at the same https://api.deepseek.com base URL. The interface remains stateless, so clients must resend the required conversation history. The August 3 test table below is retained as dated pre-GA evidence.

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["DEEPSEEK_API_KEY"],
    base_url="https://api.deepseek.com",
)

response = client.responses.create(
    model="deepseek-v4-flash",
    instructions="Reply with exactly API_OK.",
    input="Run the connectivity check.",
)

print(response.output_text)

DeepSeek's Responses API is stateless. It does not support previous_response_id, conversation, or server-side store; the response reports store: false. Unsupported parameters may be silently ignored, so a request returning HTTP 200 does not prove that every requested feature was applied. Validate the returned behavior and fields.

Responses featureDeepSeek statusProduction implication
input, instructions, streamSupportedUse at least input or instructions.
Function and web-search toolsSupportedValidate actual tool events and outputs.
apply_patch custom toolSupported for Codex compatibilityOther custom tool names return 400.
previous_response_id and conversationNot supportedSend the required history yourself.
storeNot supportedResponses remain stateless and report false.
Image and file inputNot supportedDo not interpret a non-error placeholder as vision support.
file_search, code interpreter, computer use, MCPIgnoredHTTP success does not mean these tools ran.
prompt_cache_keyNot supportedDeepSeek manages context caching automatically.

Responses API streaming

Responses streaming uses semantic server-sent events with increasing sequence numbers. It ends with response.completed, response.incomplete, or response.failed; unlike Chat Completions streaming, it does not end with data: [DONE].

stream = client.responses.create(
    model="deepseek-v4-flash",
    instructions="Answer in one short sentence.",
    input="What is an API?",
    stream=True,
)

for event in stream:
    if event.type == "response.output_text.delta":
        print(event.delta, end="", flush=True)
Redacted August 3 DeepSeek Responses API test showing Flash response events, terminal stream event, token usage, and the observed pre-GA Pro compatibility result.
Dated August 3 evidence: Chat Completions and Responses API were tested separately because their streaming contracts and compatibility differed at that time.

Thinking mode and reasoning effort

Thinking mode is enabled by default. In the OpenAI Chat Completions format, toggle it with {"thinking":{"type":"enabled"}} or disabled, and control depth with reasoning_effort. With the Python OpenAI SDK, pass the DeepSeek-specific thinking object through extra_body.

response = client.chat.completions.create(
    model="deepseek-v4-pro",
    messages=[
        {"role": "user", "content": "Which is larger: 9.11 or 9.8?"}
    ],
    reasoning_effort="high",
    extra_body={"thinking": {"type": "enabled"}},
)

print(response.choices[0].message.reasoning_content)
print(response.choices[0].message.content)
Requested effortFlash maps toPro maps to
lowlowlow
mediumhighhigh
highhighhigh
xhighhighhigh
maxmaxmax

The current mapping is identical for both V4 models. The documented direct Chat effort values are low, high, and max; compatibility inputs medium and xhigh map to high. Thinking is enabled by default with high effort. In thinking mode, temperature, top_p, presence_penalty, and frequency_penalty have no effect even though compatibility behavior may avoid an error.

If a thinking-mode turn performs a tool call, preserve and send its complete reasoning_content with the assistant tool-call message in subsequent turns. DeepSeek documents a 400 error when that required content is omitted. See our thinking mode guide for the complete message loop.

Streaming, JSON output, and tool calls

Chat Completions streaming

Set stream: true to receive data-only SSE chunks. Chat Completions streaming ends with data: [DONE]. DeepSeek may send : keep-alive comments while a request waits for inference; a custom parser must ignore those comments rather than treating them as JSON.

For end-to-end timing, measure request start, response headers, first reasoning token, first answer token, and final event separately. A single “latency” number hides the difference between queueing and generation.

JSON output

Chat Completions: set response_format to {"type":"json_object"}, include the word “json” in the prompt, show the desired shape, and validate the result. Responses API: use text.format with type: "json_object" or type: "json_schema"; schema mode also requires a name and a valid JSON Schema object. Allow enough output tokens to avoid truncation, and validate every response. The full implementation is in our DeepSeek JSON output guide.

Tool calls

Tool calling lets the model request a function; your application remains responsible for validating arguments, authorizing the action, running the function, and returning the result. Both current V4 models support tools. Strict tool schemas are a beta feature that require the https://api.deepseek.com/beta base URL and a supported JSON Schema subset. Use the DeepSeek tool-calling guide for a complete safe loop.

Multi-turn requests and context caching

Chat Completions and Responses are stateless: the application sends the history needed for each turn. Keep only relevant messages, summarize when appropriate, and budget the entire repeated prefix. DeepSeek's context cache is automatic. In response usage, cached input is reported separately; no manual cache key is required.

Cache hits depend on repeated prefixes. Preserve stable system instructions and shared context at the beginning, then append changing user data. Do not treat caching as a privacy boundary; use documented user_id isolation and keep personal data out of identifiers. See the context caching guide for measurement and cost calculations.

Observed cache result: we sent the same 890-token prefix three times. The first request reported 0 cache-hit tokens and 890 misses. Requests two and three each reported 768 cache-hit tokens and 122 misses, an 86.3% hit share for this fixture. That is a dated observation, not a guarantee that every repeated prompt will be cached.

DeepSeek API endpoints and compatibility

PurposeMethod and pathNotes
Chat CompletionsPOST /chat/completionsPrimary OpenAI-compatible text and tool interface
Responses APIPOST /responsesSupported by both current V4 models; stateless
List modelsGET /modelsUse for a dated account-visible catalog, not as the only capability test
Text completion / FIMPOST /beta/completionsBeta; FIM is non-thinking only
Account balanceGET /user/balanceRead-only account funding state
Anthropic formathttps://api.deepseek.com/anthropicSeparate compatibility surface with documented mappings

OpenAI compatibility does not mean every OpenAI endpoint, parameter, tool, modality, or persistence feature exists. Keep compatibility tests in CI, pin SDK versions where appropriate, and inspect DeepSeek's current API documentation before adopting a new client feature. Our OpenAI SDK migration guide covers the required configuration changes.

DeepSeek API pricing

DeepSeek bills input and output tokens, with a lower input rate for cache hits. Both tables use USD per one million tokens. The first table contains the current rates; the second table preserves the historical rates that were effective through August 16, 2026 at 15:59 UTC.

Current pricing: DeepSeek applies peak rates during 01:00–04:00 and 06:00–10:00 UTC and off-peak rates at all other times. Peak rates are twice the current off-peak rates.

ModelCurrent rate periodCache-hit inputCache-miss inputOutput
deepseek-v4-flashOff-peak$0.007$0.22$0.66
deepseek-v4-flashPeak$0.014$0.44$1.32
deepseek-v4-proOff-peak$0.022$0.66$1.98
deepseek-v4-proPeak$0.044$1.32$3.96
ModelCache-hit inputCache-miss inputOutput
deepseek-v4-flash$0.0028$0.14$0.28
deepseek-v4-pro$0.003625$0.435$0.87

Always confirm the official current pricing before budgeting.

Use our DeepSeek API pricing guide for billing interpretation or the DeepSeek API cost calculator to model cache-hit, cache-miss, and output tokens without sending a request.

Original DeepSeek API test results

We ran a preregistered, low-cost compatibility suite from a managed test environment (network region not asserted) between 2026-08-03T23:16:24Z and 2026-08-03T23:26:05Z. Calls were sequential with concurrency one, a 60-second timeout, and no automatic retries. The temporary API key remained in process memory and was never written to evidence files.

Frozen test evidence: the tables in this section report the August 3 run exactly as observed. The Pro Responses limitation, the effort mapping quoted inside the result matrix, and phrases such as “use Flash for now” are scoped to that pre-GA test date. DeepSeek changed the current contract on August 13; the present-day guidance appears above.

TestModel or controlExpectedObservedHTTPResult
List current modelsGET /modelsAuthenticated catalogTwo model IDs: deepseek-v4-flash and deepseek-v4-pro200Pass
Chat Completionsdeepseek-v4-flashExact short answer3/3 exact outputs; median complete time 1,648 ms200 in 3/3Pass
Chat Completionsdeepseek-v4-proExact short answer3/3 exact outputs at 128 tokens; the 32-token control truncated in 3/3200 in 6/6Pass with output-budget finding
Responses APIdeepseek-v4-flashSupported3/3 completed responses with the exact fixture200 in 3/3Pass
Responses APIdeepseek-v4-proDocumented state checked liveRejected with the provider’s early-August availability message; use Flash for now400Expected current limitation observed
Streaming terminal eventFlash ResponsesSemantic terminal event, no [DONE]response.completed; no [DONE]200Pass
Thinking effort mappingFlash and ProOfficial mapping or dated deviationAll eight documented Flash/Pro request values returned 200. Current published mapping: Flash low→low, high→high, xhigh→high, max→max; Pro low/high→high and xhigh/max→max.200 in 8/8 documented casesPass; mapped effort is not returned in the response
Function calldeepseek-v4-flashValid named function and JSON argumentsget_weather with {"city":"Tokyo"}; finish_reason=tool_calls200Pass
Invalid authentication controlSynthetic non-secret value401Redacted authentication_error401Pass
Invalid parameter controlSafe malformed test4xx documented errorUnsupported model returned invalid_request_error400Pass

Timing, tokens, and cost

TestRunsMedian response headersMedian completeInput tokensOutput tokensReasoning tokensCalculated cost
Flash Chat Completions3985 ms1,648 ms288 total75 total57 total$0.00006132 derived
Pro Chat Completions3344 ms1,181 ms51 total101 total83 total$0.00011006 derived
Flash Responses API3694 ms1,820 ms285 total113 total95 total$0.00007154 derived

These tests establish point-in-time contract behavior, not a provider SLA, universal latency ranking, or regional availability claim. The Pro output-budget control shows why reasoning workloads need headroom. The legacy aliases still routed to Flash on the test date, but explicit V4 IDs remain the production recommendation. The undocumented medium effort value was accepted but is not represented here as supported. Costs are deterministic estimates from observed usage and the dated standard list prices, not invoice readings.

For a dedicated evaluation of very large Chat Completions requests rather than short contract checks, see the reproducible long-context API benchmark with matched V4 Flash and Pro cases and downloadable data.

Redacted original DeepSeek API test results showing model calls, endpoint compatibility, HTTP outcomes, timing definitions, token usage, and checks passed.
The results are a dated compatibility observation from one account and region, not an uptime guarantee or universal speed benchmark.

Download the sanitized test harness, runnable examples, assertions, and redacted result format from the DeepSeek API request builder repository on GitHub. No credential, raw authenticated response, request identifier, or account value is included.

DeepSeek API request builder and error decoder

Choose an API surface, model, thinking setting, and common feature to generate cURL, PowerShell, Python, or Node.js code. The tool also explains common HTTP errors. It runs entirely in your browser, never asks for an API key, never sends an API request, and does not store your selections.

Interactive developer tool

DeepSeek API Request Builder

Configure a request once, then generate ready-to-review cURL, PowerShell, Python, Node.js, and JSON examples.

Private by design: this page only generates text in your browser. It never asks for an API key, sends a request, or saves your prompts. Every example reads the key from DEEPSEEK_API_KEY.
Load an example:

1. Configure the request

Use the official HTTPS endpoint. The builder appends the selected route.
Request options

2. Copy the generated code

3. Decode a DeepSeek API error

Try 400, 401, 402, 404, 422, 429, 500, or 503.

429: Rate or concurrency limit reached

The account is sending too many simultaneous or rapid requests.

  • Honor Retry-After when the header is present.
  • Add exponential backoff with jitter and cap retries.
  • Queue requests and reduce concurrency.

Retry guidance: Retry after a delay; do not retry in a tight loop.

The generated code deliberately contains an environment-variable reference instead of a credential. Review generated requests before running them, particularly beta features, tools, and any operation that can trigger external actions.

DeepSeek API errors and production checklist

HTTP statusOfficial meaningFirst action
400Invalid request formatInspect the error and validate the JSON body.
401Authentication failedCheck key loading, revocation, base URL, and Bearer header without logging the key.
402Insufficient balanceStop unchanged retries and check account funding.
422Invalid parametersCompare the request with the current endpoint schema.
429Rate or concurrency limit reachedReduce concurrency and use bounded backoff with jitter.
500Server errorRetry safely after a short delay and preserve observability.
503Server overloadedUse bounded retry, a queue, and a degradation plan.

DeepSeek documents account-level concurrency of 2,500 for Flash and 500 for Pro. Exceeding the applicable limit returns 429. Requests can remain connected while waiting; non-streaming responses may receive empty lines and streaming responses may receive keep-alive comments. If inference has not started after ten minutes, the server closes the connection.

  • Keep API keys in a secret manager or protected server environment, never client-side code.
  • Set connect, first-byte, idle, and overall timeouts intentionally instead of one ambiguous timeout.
  • Retry only transient failures with exponential backoff, jitter, a maximum attempt count, and duplicate-work protection.
  • Validate structured output and tool arguments before using them.
  • Track model, endpoint, HTTP status, duration, token fields, cache fields, and finish reason without storing prompts by default.
  • Use application-generated pseudonymous user_id values; do not put personal information in them.
  • Keep a feature-compatibility test because unsupported Responses parameters can be silently ignored.
  • Monitor the official change log and re-run contract tests before changing models or SDK versions.

For deeper handling, use the DeepSeek error-code guide, rate-limit guide, API testing guide, and observability guide.

DeepSeek API FAQ

Is the DeepSeek API free?

The DeepSeek API is usage-billed according to input, output, and cache-hit token rates. An account may have granted credit, but availability and amount are account-specific. Check the official Billing page and current pricing rather than assuming a permanent free tier.

What is the DeepSeek API base URL?

The OpenAI-compatible base URL is https://api.deepseek.com. The separate Anthropic-compatible base URL is https://api.deepseek.com/anthropic.

Which DeepSeek API model ID should I use?

Use deepseek-v4-flash for the current Flash model or deepseek-v4-pro for Pro. Avoid starting new integrations with the retired or legacy aliases deepseek-chat and deepseek-reasoner.

Does DeepSeek support the OpenAI Responses API?

Yes. The native Responses API supports both deepseek-v4-flash and deepseek-v4-pro. The API is stateless, so send the required history in each request. The August 3 Pro rejection shown above remains a dated pre-GA observation.

Can I use the OpenAI SDK with DeepSeek?

Yes. Set your DeepSeek key and change base_url or baseURL to https://api.deepseek.com. Compatibility is not universal: test the endpoints, parameters, tools, and modalities your application actually uses.

What is the DeepSeek API context window?

DeepSeek's current model table lists a 1M-token context window and 384K maximum output for both V4 Flash and V4 Pro. A request exceeding the context limit can return HTTP 400, so reserve space for the requested output and tool messages.

Is the DeepSeek API the same as DeepSeek Chat?

No. The API is a metered developer service on the DeepSeek Platform, while the web and app products provide an end-user chat interface. Model availability, billing, limits, and release timing can differ.

Why does the DeepSeek API return 429?

HTTP 429 means the applicable rate or concurrency limit was reached. Concurrency is calculated at account level across keys. Reduce parallel work, queue requests, and retry with bounded exponential backoff and jitter.

Official sources and update log

DateEditorial and test update
2026-08-14Updated Pro-0813 GA status, enabled both V4 models in the Responses request builder, aligned the current reasoning-effort mapping, added the August 16 peak/off-peak rate schedule, and preserved the August 3 test suite as frozen pre-GA evidence.
2026-08-05Updated the request builder with endpoint-specific reasoning controls, the current Chat mapping, Responses API effort values, Responses text.format support for json_object and json_schema, and the documented 384K output ceiling.
2026-08-03Added July 31 Flash-0731 status, Responses API compatibility, current pricing and reasoning mapping; re-ran code, model, endpoint, streaming, tool, and error controls.
2026-07-28Previous verification of Chat Completions, current model IDs, pricing, and production guidance.

Editorial standard: Published prices and capabilities are sourced from DeepSeek's primary documentation. Live-test statements are limited to the exact dated observations shown above. Planned features are described as plans, not as completed releases.