This tutorial will guide you through calling DeepSeek's R1 large model API using Python. Even if you have no programming experience, you can easily follow along. The article also includes a FAQ section at the end, which we recommend saving for reference!
Step 1. Preparation
Obtain Your API Key
First, log in to the DeepSeek Platform and get your API key.
On the "API Keys" page, click "Create API Key" and copy the generated key (e.g., sk-123456789abc). Make sure to save it, as you'll need to generate a new API key if you forget or lose it.
Note: You need to top up your account before your API Key can be used.
Step 2. Python Setup
1. Set up the Environment: Install Python (Skip if already installed)
If Python is not installed on your computer, you need to install it (macOS comes with Python 3 pre-installed). You can download it from python.org.
Download the latest version (recommended: 3.8+).
Be sure to check "Add Python to PATH" during installation.
If you don't need a Python environment and want to call the API using a visual interface, refer to this guide: How to Use the Deepseek API (R1 & V3): A Step-by-Step Guide with Screenshots.
2. Install the Requests Library (Skip if already installed)
Create a new project folder in VSCode or another IDE, then open the terminal (Top menu: Terminal → New Terminal) and run the following command:
pip install requests
Or:
pip3 install requests
If the command runs successfully, you should see something like this:
Or this:
Successfully installed requests-x.x.x
If the installation fails and you already have Python on your computer, it may be due to having multiple Python versions installed. The requests
library might only be installed in one version's environment.
You can switch Python versions at the bottom-right corner of the screen.
You can also install a "Python" extension in VSCode and check your current version. Then, open the corresponding version’s console panel to run the command.
If you can't resolve these errors, skip to the last section of the article, where a simpler method of calling the DeepSeek-R1 API is provided. Or, you can use the visual interface method here: How to Use the Deepseek API (R1 & V3): A Step-by-Step Guide with Screenshots.
3. Basic Calling Code
Once the above command is executed successfully, create a .py
file in your project (e.g., deepseek.py) and paste the following code (remember to replace sk-your-key
with your actual API key).
# deepseek.py
import requests
# Enter your API Key
API_KEY = "sk-your-key"
url = "https://api.deepseek.com/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}"
}
data = {
"model": "deepseek-reasoner", # Use 'deepseek-reasoner' for R1 model or 'deepseek-chat' for V3 model
"messages": [
{"role": "system", "content": "You are a professional assistant"},
{"role": "user", "content": "Who are you?"}
],
"stream": False # Disable streaming
}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 200:
result = response.json()
print(result['choices'][0]['message']['content'])
else:
print("Request failed, error code:", response.status_code)
You can call the DeepSeek-V3 API by specifying model='deepseek-chat'
.
To call DeepSeek-R1, use model='deepseek-reasoner'
.
4. Run the Code
You can run the code in several ways:
Click the "▶" button in the top-right corner to run the code.
Run the command
python3 deepseek.py
orpython deepseek.py
in the terminal.Right-click the editor and select "Run Python File in Terminal."
5. Successful Output
When you see output like this, the call was successful:
Hi! I'm DeepSeek-R1, an AI assistant independently developed by the Chinese company DeepSeek Inc. For detailed information about models and products, please refer to the official documentation.
Step 3. Code Explanation
1. Key Parameters
Parameter |
Description |
|
|
|
Dialogue history (supports multi-turn dialogues) |
|
Set to |
2. Multi-Turn Dialogue Example
messages = [
{"role": "system", "content": "You are a poet"},
{"role": "user", "content": "Write a poem about spring"},
{"role": "assistant", "content": "The spring breeze caresses, the willow branches grow..."},
{"role": "user", "content": "Please continue the second stanza"}
]
Step 4. Streaming Mode
Modify the following parameter to enable streaming:
data["stream"] = True
response = requests.post(url, headers=headers, json=data, stream=True)
for line in response.iter_lines():
if line:
decoded_line = line.decode('utf-8')
print(decoded_line)
Complete code:
# deepseek.py
import requests
# Enter your API Key
API_KEY = "sk-your-API-Key"
url = "https://api.deepseek.com/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}"
}
data = {
"model": "deepseek-chat", # Use 'deepseek-reasoner' for R1 model or 'deepseek-chat' for V3 model
"messages": [
{"role": "system", "content": "You are a professional assistant"},
{"role": "user", "content": "Who are you?"}
],
"stream": False # Disable streaming
}
data["stream"] = True
response = requests.post(url, headers=headers, json=data, stream=True)
for line in response.iter_lines():
if line:
decoded_line = line.decode('utf-8')
print(decoded_line)
The following output is from the V3 model (deepseek-chat). Why not use R1? It's extremely popular and often unresponsive😂.
FAQ
Q1: How do I distinguish between V3 and R1 models?
V3:
model: "deepseek-chat"
R1:
model: "deepseek-reasoner"
Q2: How to fix a 401 error?
Check if the API key is entered correctly.
Ensure the key has not expired.
Q3: What to do if "No module named 'requests'" appears?
Make sure you run
pip install requests
in the correct terminal.Ensure VSCode is using the correct Python interpreter.
Q4: What doesrequests.exceptions.JSONDecodeError: Expecting value: line 1 column 1
mean?
- This error typically indicates that the server is busy or the API did not return valid JSON data, resulting in an empty response.
Q5: Why does streaming output always show "keep-alive"?
- This may happen if the server is under heavy load, keeping the connection open for long periods.
Easier Method to Call DeepSeek-R1 API (Recommended)
You can call the DeepSeek-R1 API or DeepSeek-V3 API via Apidog. Apidog supports both streaming and non-streaming results:
For a detailed guide, check out: How to Use the Deepseek API (R1 & V3): A Step-by-Step Guide with Screenshots.
With this tutorial, you have learned the core method of calling the DeepSeek API. Start by testing simple dialogues, then gradually explore advanced features like streaming and multi-turn conversations. If you encounter any issues, feel free to leave a comment for discussion!
Learn more:
Top comments (0)