DeepSeek's R1 large language model offers powerful capabilities for developers. This tutorial provides a comprehensive, beginner-friendly guide on how to integrate the DeepSeek-R1 API into your Python projects. Whether you're a seasoned coder or just starting, this guide will walk you through each step, ensuring you can harness the potential of DeepSeek-R1. We will also explore how to manage your APIs effectively using tools like Apifox.
DeepSeek-R1 is a cutting-edge large language model, offering advanced reasoning and natural language processing capabilities. Integrating it into your applications can unlock a wide range of possibilities, from creating intelligent chatbots to automating complex tasks.
Install Python: If you don't have Python installed, download and install the latest version (3.8+) ensuring you check "Add Python to PATH" during installation for easy access from the command line.
Create a Project Directory: Create a new folder for your project and open it in your code editor.
Install the requests
Library: Open your terminal (in VSCode, go to Terminal -> New Terminal) and run the following command:
pip install requests
or
pip3 install requests
The requests
library allows you to make HTTP requests in Python.
Troubleshooting requests
Installation: If the installation fails, it might be due to multiple Python versions on your system. Verify your active Python version by using the Python extension in VSCode. Ensure requests
is installed for the correct version.
Create a Python File: Create a new file named deepseek.py
in your project directory.
Paste the Code: Copy and paste the following code into deepseek.py
, replacing "sk-你的密钥"
with your actual DeepSeek API key.
import requests
# 填写你的 API Key
API_KEY = "sk-你的密钥"
url = "https://api.deepseek.com/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}"
}
data = {
"model": "deepseek-reasoner", # 指定使用 R1 模型(deepseek-reasoner)或者 V3 模型(deepseek-chat)
"messages": [
{"role": "system", "content": "你是一个专业的助手"},
{"role": "user", "content": "你是谁?"}
],
"stream": False # 关闭流式传输
}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 200:
result = response.json()
print(result['choices'][0]['message']['content'])
else:
print("请求失败,错误码:", response.status_code)
Key parameters explained:
model
: Specifies the DeepSeek model to use. Use "deepseek-reasoner"
for the R1 model and "deepseek-chat"
for the V3 model.messages
: An array of message objects representing the conversation history. Each message has a role
(either "system", "user", or "assistant") and content
.stream
: A boolean value that enabled or disables streaming.Run the Code: You can run the code in several ways:
python deepseek.py
or python3 deepseek.py
.requests
: The code starts by importing the requests
library, which is essential for making HTTP requests.API_KEY
variable stores your DeepSeek API key, and the url
variable holds the API endpoint.headers
dictionary specifies the content type and authorization token for the request.data
dictionary contains the request payload, including the model to use, the messages for the conversation, and whether to use streaming.requests.post()
function sends a POST request to the API endpoint with the specified headers and data.To create multi-turn conversations, add more message objects to the messages
array, including "user" and "assistant" roles to simulate the conversation history.
messages = [
{"role": "system", "content": "你是一位诗人"},
{"role": "user", "content": "写一首关于春天的诗"},
{"role": "assistant", "content": "春风拂面柳丝长..."},
{"role": "user", "content": "请继续补充第二段"}
]
To receive responses in real-time, enable streaming mode by setting data["stream"] = True
and modify the code to iterate over the response lines:
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)
No module named 'requests'
:
requests
library using pip install requests
in the correct Python environment.requests
library is installed for the correct Python version.JSONDecodeError: Expecting value: line 1 column 1
:
For a more user-friendly experience, consider using Apifox to interact with the DeepSeek API. Apifox provides a visual interface for constructing API requests, managing your API keys, and viewing responses.
See this article for a detailed guide on using Apifox with DeepSeek API. Apifox simplifies the API testing and debugging process. You can also explore its features for API documentation and API Mocking.
This tutorial has equipped you with the knowledge to integrate DeepSeek-R1 into your Python projects. Start with simple conversations, explore streaming functionality, and gradually incorporate more advanced features. By understanding the core concepts and utilizing tools like Apifox, you can empower your applications with the intelligence of DeepSeek-R1.