DeepSeek API: Complete Python Integration Guide
Category: AI Coding Difficulty: Intermediate Updated: 2026-05-28
Complete guide to integrating DeepSeek API in Python. Learn authentication, chat completions, streaming, structured outputs, and pricing optimization.
OpenAI-Compatible API
DeepSeek's API is fully compatible with the OpenAI SDK. You can switch from OpenAI to DeepSeek by changing just the base URL and API key. This means all your existing code works with minimal changes.
Quick Start
pip install openai
from openai import OpenAI
client = OpenAI(
api_key="your-deepseek-api-key",
base_url="https://api.deepseek.com"
)
response = client.chat.completions.create(
model="deepseek-chat",
messages=[
{"role": "system", "content": "You are a helpful coding assistant."},
{"role": "user", "content": "Write a Python function to merge two sorted lists."}
],
stream=False
)
print(response.choices[0].message.content)Using Deep Think (R1) via API
response = client.chat.completions.create(
model="deepseek-reasoner", # Enables Deep Think mode
messages=[{"role": "user", "content": "Solve this complex algorithm problem..."}]
)
# You can access the reasoning trace:
print("Reasoning:", response.choices[0].message.reasoning_content)
print("Answer:", response.choices[0].message.content)Pricing Optimization Tips
- DeepSeek API costs ~$0.14 per million input tokens (vs OpenAI $2.50) — 18x cheaper
- Use
deepseek-chatfor simple tasks,deepseek-reasoneronly for complex ones - Enable caching for repeated queries to reduce costs
- Batch non-urgent requests during off-peak hours for lower latency