⛏️ ChinaAI.tools
DeepSeek API Tutorial: Python & Node.js Setup
Published June 12, 2026 · 15 min read
← Back to Home
This tutorial covers everything you need to integrate DeepSeek API into your Python or Node.js application. DeepSeek offers GPT-4o quality at 1/100th the cost ($0.14/M tokens vs $15/M).
Prerequisites
- A DeepSeek account (sign up at platform.deepseek.com)
- An API key (generate in the API Keys section)
- Python 3.8+ or Node.js 18+
Part 1: Python Setup
Step 1: Install the OpenAI Library
pip install openai
Step 2: Basic Chat Request
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": "user", "content": "What is the capital of France?"}
]
)
print(response.choices[0].message.content)
Step 3: Streaming Responses
stream = client.chat.completions.create(
model="deepseek-chat",
messages=[
{"role": "user", "content": "Write a short poem about coding"}
],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")
Step 4: Multi-Turn Conversation
messages = [
{"role": "system", "content": "You are a helpful coding assistant."},
{"role": "user", "content": "How do I reverse a string in Python?"}
]
response = client.chat.completions.create(
model="deepseek-chat",
messages=messages
)
messages.append({
"role": "assistant",
"content": response.choices[0].message.content
})
messages.append({
"role": "user",
"content": "Can you explain that step by step?"
})
response2 = client.chat.completions.create(
model="deepseek-chat",
messages=messages
)
Step 5: Function Calling
response = client.chat.completions.create(
model="deepseek-chat",
messages=[
{"role": "user", "content": "What's the weather in Tokyo?"}
],
tools=[{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather for a city",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string"}
},
"required": ["city"]
}
}
}]
)
Part 2: Node.js Setup
Step 1: Install the OpenAI Library
npm install openai
Step 2: Basic Chat Request
import OpenAI from 'openai';
const client = new OpenAI({
apiKey: 'your-deepseek-api-key',
baseURL: 'https://api.deepseek.com'
});
const response = await client.chat.completions.create({
model: 'deepseek-chat',
messages: [{ role: 'user', content: 'Hello!' }]
});
console.log(response.choices[0].message.content);
Step 3: Streaming in Node.js
const stream = await client.chat.completions.create({
model: 'deepseek-chat',
messages: [{ role: 'user', content: 'Tell me a story' }],
stream: true
});
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content;
if (content) process.stdout.write(content);
}
Part 3: Error Handling
from openai import OpenAI, APIError, RateLimitError
client = OpenAI(
api_key="your-key",
base_url="https://api.deepseek.com"
)
try:
response = client.chat.completions.create(
model="deepseek-chat",
messages=[{"role": "user", "content": "Hello"}]
)
except RateLimitError:
print("Rate limited. Wait and retry.")
except APIError as e:
print(f"API error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
Part 4: Cost Optimization Tips
Pro tip: Use DeepSeek's cache feature. When you send the same prefix multiple times, cached tokens cost only $0.0028/M (vs $0.14/M). This is 50x cheaper for repeated prompts.
- Use system prompts wisely: Put instructions in the system message, not repeated in every user message
- Limit max_tokens: Set a reasonable limit to avoid paying for unnecessary output
- Cache common prompts: DeepSeek automatically caches repeated prefixes
- Batch requests: Process multiple items in one API call when possible
- Use the Flash model: For most tasks, V4-Flash ($0.14/M) is sufficient
Part 5: Production Deployment
Environment Variables
DEEPSEEK_API_KEY=your-api-key-here
Rate Limiting
import time
def call_with_retry(func, max_retries=3):
for i in range(max_retries):
try:
return func()
except RateLimitError:
time.sleep(2 ** i)
raise Exception("Max retries exceeded")
Need Help Setting Up?
Our guide includes copy-paste code, troubleshooting tips, and production best practices
Get the Complete Guide →
Conclusion
DeepSeek API is a drop-in replacement for OpenAI. The same library, same format, same code — just change the base_url and API key. You get GPT-4o quality at 1/100th the cost.
The setup takes 5 minutes. The savings last forever.