如何使用 Python 调用 DeepSeek-R1 API?深入的分步指南

2025-06-08

如何使用 Python 调用 DeepSeek-R1 API?深入的分步指南

本教程将指导您使用 Python 调用 DeepSeek 的 R1 大型模型 API。即使您没有任何编程经验,也可以轻松跟进。文章末尾还包含常见问题解答部分,建议您保存以备参考!

步骤1. 准备

获取您的 API 密钥

首先,登录DeepSeek 平台并获取您的 API 密钥。

如何使用 Python 调用 DeepSeek-R1 API

在“API 密钥”页面,点击“创建 API 密钥”并复制生成的密钥(例如 sk-123456789abc)。请务必保存该密钥,因为如果忘记或丢失,您需要重新生成一个 API 密钥。

如何使用 Python 调用 DeepSeek-R1 API

注意:您需要先充值您的账户,然后才能使用您的 API Key。

步骤2.Python设置

1. 设置环境:安装 Python(如果已经安装则跳过)

  • 如果您的计算机上尚未安装 Python,则需要安装它(macOS 预装了 Python 3)。您可以从python.org下载。

  • 下载最新版本(推荐:3.8+)。

  • 安装过程中请务必检查“将 Python 添加到 PATH”。

如果您不需要 Python 环境并且想要使用可视化界面调用 API,请参考本指南:如何使用 Deepseek API(R1 和 V3):带有屏幕截图的分步指南

2.安装Requests库(如果已经安装请跳过)

在 VSCode 或其他 IDE 中创建一个新的项目文件夹,然后打开终端(顶部菜单:终端 → 新建终端)并运行以下命令:

pip install requests
Enter fullscreen mode Exit fullscreen mode

或者:

pip3 install requests
Enter fullscreen mode Exit fullscreen mode

如何使用 Python 调用 DeepSeek-R1 API

如果命令成功运行,您应该会看到如下内容:

如何使用 Python 调用 DeepSeek-R1 API

或者这样:

Successfully installed requests-x.x.x
Enter fullscreen mode Exit fullscreen mode

如果安装失败,并且您的计算机上已经安装了 Python,则可能是因为安装了多个 Python 版本。该requests库可能仅安装在一个版本的环境中。

您可以在屏幕右下角切换 Python 版本。

如何使用 Python 调用 DeepSeek-R1 API

你也可以在 VSCode 中安装一个“Python”扩展,并检查当前版本。然后,打开相应版本的控制台面板运行命令。

如何使用 Python 调用 DeepSeek-R1 API

如果您无法解决这些错误,请跳至本文的最后一部分,其中提供了更简单的调用 DeepSeek-R1 API 的方法。或者,您也可以使用此处的可视化界面方法:如何使用 Deepseek API(R1 和 V3):带屏幕截图的分步指南

深度搜索

3. 基本调用代码

一旦上述命令成功执行,.py在您的项目中创建一个文件(例如,deepseek.py)并粘贴以下代码(记得替换sk-your-key为您的实际 API 密钥)。

# 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)
Enter fullscreen mode Exit fullscreen mode

您可以通过指定 来调用 DeepSeek-V3 API model='deepseek-chat'

要调用 DeepSeek-R1,请使用model='deepseek-reasoner'

4.运行代码

您可以通过多种方式运行代码:

  • 点击右上角的“▶”按钮运行代码。

  • 在终端中运行命令python3 deepseek.py或。python deepseek.py

  • 右键单击编辑器并选择“在终端中运行 Python 文件”。

如何使用 Python 调用 DeepSeek-R1 API

5. 成功输出

当您看到这样的输出时,表示调用成功:

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.
Enter fullscreen mode Exit fullscreen mode

如何使用 Python 调用 DeepSeek-R1 API

步骤3.代码解释

1. 关键参数

范围

描述

model

deepseek-reasoner适用于 R1 型号

messages

对话历史(支持多轮对话)

stream

设置True为流式输出(适合长文本)

2. 多轮对话示例

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"}
]
Enter fullscreen mode Exit fullscreen mode

步骤4.流模式

修改以下参数以启用流式传输:

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)
Enter fullscreen mode Exit fullscreen mode

完整代码:

# 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)
Enter fullscreen mode Exit fullscreen mode

以下输出来自 V3 模型 (deepseek-chat)。为什么不使用 R1?它非常流行,但经常响应迟钝😂。

如何使用 Python 调用 DeepSeek-R1 API

如何使用 Python 调用 DeepSeek-R1 API


常问问题

Q1:如何区分V3和R1型号?

  • V3版本model: "deepseek-chat"

  • R1model: "deepseek-reasoner"

Q2:如何修复401错误?

  • 检查 API 密钥是否输入正确。

  • 确保密钥尚未过期。

Q3:出现“No module named 'requests'”怎么办?

  • 确保您pip install requests在正确的终端中运行。

  • 确保 VSCode 使用正确的 Python 解释器。

Q4:是什么requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 意思?

  • 此错误通常表示服务器繁忙或 API 未返回有效的 JSON 数据,导致响应为空。

Q5:为什么流输出总是显示“keep-alive”?

  • 如果服务器负载过重,长时间保持连接打开,则可能会发生这种情况。

更简单的调用 DeepSeek-R1 API 的方法(推荐)

您可以通过Apidog调用 DeepSeek-R1 API 或 DeepSeek-V3 API。Apidog支持式和非流式结果:

如何使用 Python 调用 DeepSeek-R1 API

如何使用 Python 调用 DeepSeek-R1 API

有关详细指南,请查看:如何使用 Deepseek API(R1 和 V3):带有屏幕截图的分步指南


通过本教程,您已经学习了调用 DeepSeek API 的核心方法。首先测试简单的对话,然后逐步探索流式对话和多轮对话等高级功能。如果您遇到任何问题,请随时发表评论进行讨论!

了解更多:

鏂囩珷鏉ユ簮锛�https://dev.to/auden/how-to-call-the-deepseek-r1-api-using-python-an-in-deep-step-by-step-guide-311o
PREV
如何从头构建 graphql api
NEXT
浴室窗户教会了我代码质量