【AI测试必学】DeepSeek API 快速入门:获取 API Key 与调用 API 步骤详解
DeepSeek API 快速入门:获取 API Key 与调用 API 步骤详解
- 一、获取 API Key
- 二、调用 DeepSeek API
- 方法 1:使用 OpenAI Python SDK 调用 DeepSeek API
- 方法 2:使用 requests 库直接发送 HTTP 请求
- 方法 3:使用 curl 命令
- 相关链接
一、获取 API Key
-
访问 DeepSeek 官方平台:https://platform.deepseek.com/sign_in
-
注册并登录账号,进入左侧导航栏的
API Keys
页面,点击创建 API Key
。
生成的 API Key 只会显示一次,请妥善保存。
二、调用 DeepSeek API
方法 1:使用 OpenAI Python SDK 调用 DeepSeek API
DeepSeek API 使用与 OpenAI 兼容的格式,可以通过修改配置使用 OpenAI SDK。
安装 openai 库:
pip install openai
配置参数说明:
api_key
:需要将 your_api_key_here 替换为你 DeepSeek API 的实际 API 密钥。base_url
: https://api.deepseek.com 或 https://api.deepseek.com/v1。model
: deepseek-chat(DeepSeek-V3)或 deepseek-reasoner(DeepSeek-R1)。
示例代码(Python):
from openai import OpenAI
client = OpenAI(
base_url="https://api.deepseek.com/",
api_key="your_api_key_here"
)
response = client.chat.completions.create(
model="deepseek-chat",
messages=[
{
"role": "user",
"content": "你好"
}
],
stream=False
)
print(response.choices[0].message.content)
执行结果如下:
方法 2:使用 requests 库直接发送 HTTP 请求
import requests
import json
api_key = "your_api_key_here"
base_url = "https://api.deepseek.com/v1/chat/completions" # 注意这里使用了/v1/chat/completions 端点
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
data = {
"model": "deepseek-chat",
"messages": [{"role": "user", "content": "你好,DeepSeek!"}],
"stream": True #启用流式响应
}
try:
response = requests.post(base_url, headers=headers, data=json.dumps(data), stream=True)
response.raise_for_status() # 检查HTTP错误
# 处理流式响应
for line in response.iter_lines(decode_unicode=True):
if line:
if line.startswith("data: "):
json_data = line[6:].strip()
if json_data == "[DONE]":
break
try:
data = json.loads(json_data)
# 从数据中提取内容
if 'choices' in data and len(data['choices']) > 0:
content = data['choices'][0].get('delta', {}).get('content', '')
print(content, end="", flush=True)
# 处理一些其他的message类型
elif 'error' in data:
print(f"Error from API: {data['error']}")
break #遇到错误也停止
except json.JSONDecodeError as e:
print(f"JSON 解码错误:{e}, 数据: {json_data}")
continue #解码错误,跳过此行
except requests.exceptions.RequestException as e:
print(f"请求错误:{e}")
except Exception as e:
print(f"发生错误:{e}")
执行结果如下:
方法 3:使用 curl 命令
curl https://api.deepseek.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"model": "deepseek-chat",
"messages": [{"role": "user", "content": "你好,DeepSeek!"}],
"stream": true
}'
执行结果如下:
相关链接
- DeepSeek 开放平台: https://platform.deepseek.com/
- DeepSeek API 官方文档: https://api-docs.deepseek.com/zh-cn/
- OpenAI Python SDK: https://github.com/openai/openai-python