Updated 2026-10-11
How to Use DeepSeek in Python — From Zero to Production
DeepSeek V4.1 Flash exposes an OpenAI-compatible API and accepts native text and image input under the exact Model ID `deepseek-flash`. The standard openai package still works: change the base URL and API key, then use the same model for ordinary coding, streaming, screenshots, and tool-driven workflows.
1. Install the SDK and set your API key
You do not need a DeepSeek-specific package. The official openai Python SDK speaks the DeepSeek endpoint natively. Install it with pip, then load the API key from an environment variable — never hardcode it.
Get a production-grade API key from the DeepSeek console, or use the Base URL and access Key delivered with an active plan from /pricing. Put the credential in your shell as DEEPSEEK_API_KEY.
pip install "openai>=1.40.0" python-dotenv
echo "DEEPSEEK_API_KEY=sk-..." >> .env2. Your first DeepSeek chat completion
Create an OpenAI client and point base_url at the DeepSeek endpoint. The chat.completions.create call is identical to OpenAI; only the model name changes. Use `deepseek-flash` for new configurations. It is the native multimodal V4.1 Flash route, while the older V4 IDs are compatibility names for existing integrations.
import os
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
client = OpenAI(
api_key=os.environ["DEEPSEEK_API_KEY"],
base_url="https://api.deepseek.com/v1",
)
response = client.chat.completions.create(
model="deepseek-flash",
messages=[
{"role": "system", "content": "You are a concise technical assistant."},
{"role": "user", "content": "Write a Python one-liner to flatten a nested list."},
],
temperature=0.2,
)
print(response.choices[0].message.content)
print("tokens used:", response.usage.total_tokens)3. Streaming responses for low-latency UIs
For chat UIs, CLIs, or agent loops you want tokens to appear as they are generated. Pass stream=True and iterate over the chunks. Each chunk is an OpenAI-compatible delta object.
stream = client.chat.completions.create(
model="deepseek-flash",
messages=[{"role": "user", "content": "Explain MoE architectures in 3 sentences."}],
stream=True,
)
for chunk in stream:
delta = chunk.choices[0].delta.content
if delta:
print(delta, end="", flush=True)4. Function calling (tool use) with DeepSeek V4
DeepSeek V4 supports OpenAI-style tool use. You declare a JSON schema for each tool, the model decides when to call it, and you execute the tool and return the result for the next turn. V4 is significantly more reliable at this than V3, so agent loops break less often.
Always validate the tool arguments before executing the call — treat them as untrusted input, exactly as you would for user input.
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
messages = [{"role": "user", "content": "What's the weather in Tokyo?"}]
response = client.chat.completions.create(
model="deepseek-v4-pro",
messages=messages,
tools=tools,
)
call = response.choices[0].message.tool_calls[0]
# → call.function.name == "get_weather"
# → call.function.arguments == '{"city":"Tokyo"}'5. Controlling cost: tokens, context window, caching
Official Pro API pricing: Off-peak: $0.66 input / $1.98 output per 1M tokens (cache-miss input); Peak: $1.32 input / $3.96 output per 1M tokens (cache-miss input). Peak hours are 09:00–12:00 and 14:00–18:00 Beijing time (01:00–04:00 and 06:00–10:00 UTC), Monday–Friday, excluding Chinese public holidays. All other hours, weekends, and Chinese public holidays are off-peak. Cached input is billed separately; see the complete pricing table.
Official Flash API rates: Off-peak: $0.15 input / $0.6 output per 1M tokens (cache-miss input); Peak: $0.3 input / $1.2 output per 1M tokens (cache-miss input). Peak hours are 09:00–12:00 and 14:00–18:00 Beijing time (01:00–04:00 and 06:00–10:00 UTC), Monday–Friday, excluding Chinese public holidays. All other hours, weekends, and Chinese public holidays are off-peak. See the pricing guide for cache-hit rates.
Three practical tactics: (1) keep the system prompt short and stable (it can be cached), (2) summarise older turns and drop raw history once the chat exceeds ~6k tokens, (3) cap max_tokens on the output to avoid the model running away when it should be terse.
For teams burning millions of tokens a day, compare the current inventory-backed plans on /pricing. Each card states its endpoint, quota, access term, and supported model routes before checkout.
6. Production checklist
Timeouts and retries: wrap every call with a timeout (15–30s for chat, 60–120s for long reasoning) and retry on 429 / 5xx with exponential backoff.
Structured output: use response_format={"type":"json_object"} when you need machine-parseable answers, and validate with Pydantic or jsonschema.
Observability: log model, prompt_tokens, completion_tokens, latency, and a truncated prompt hash. You will thank yourself the first time the bill spikes.
FAQ
Do I need a special DeepSeek Python SDK?
No. The standard openai package works with DeepSeek — just change base_url and api_key. Any OpenAI-compatible library (LangChain, LlamaIndex, Instructor) also works.
Which model name should I use?
Use the exact Model ID `deepseek-flash` for new text and image configurations. Keep an older V4 ID only while an existing integration is being migrated.
Can I use async in Python?
Yes. Use openai.AsyncOpenAI instead of OpenAI and await the call. Everything else is identical.
How do I get a cheaper API key?
Current DeepSeek access plans are listed on /pricing when inventory is available. Use the Base URL and credential shown for the specific plan.
Does streaming cost more?
No. Streaming only changes transport; pricing is still per-token and identical to non-streaming calls.
Python + DeepSeek V4.1 Flash keeps the OpenAI-compatible setup simple while adding native image input. Add `deepseek-flash`, verify one text and one screenshot request, then retire older model IDs only after active integrations have migrated.
Related model comparisons
Continue from this guide into structured DeepSeek-first comparison pages with model tables, routing advice, and pricing context.