DeepSeek API 接口使用说明

1. 准备工作

1.1 获取 API Key

  1. 访问 DeepSeek 官网
  2. 注册/登录账号
  3. 进入控制台,创建 API Key
  4. 保存好生成的 API Key(只显示一次)

1.2 基础信息

  • API 地址: https://api.deepseek.com
  • 模型名称: deepseek-chat(推荐)或 deepseek-coder
  • 认证方式: Bearer Token

2. API 调用示例

2.1 使用 cURL

curl -X POST https://api.deepseek.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "model": "deepseek-chat",
    "messages": [
      {"role": "system", "content": "你是一个有用的助手"},
      {"role": "user", "content": "你好,请介绍一下自己"}
    ],
    "temperature": 0.7,
    "max_tokens": 1000
  }'

2.2 使用 Python

import requests
import json

# 配置
api_key = "YOUR_API_KEY"
url = "https://api.deepseek.com/v1/chat/completions"

# 请求头
headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {api_key}"
}

# 请求数据
data = {
    "model": "deepseek-chat",
    "messages": [
        {"role": "system", "content": "你是一个有用的助手"},
        {"role": "user", "content": "你好,请介绍一下自己"}
    ],
    "temperature": 0.7,
    "max_tokens": 1000
}

# 发送请求
response = requests.post(url, headers=headers, json=data)
result = response.json()

# 输出结果
print(result["choices"][0]["message"]["content"])

2.3 使用 JavaScript/Node.js

const axios = require('axios');

const apiKey = 'YOUR_API_KEY';
const url = 'https://api.deepseek.com/v1/chat/completions';

const data = {
  model: 'deepseek-chat',
  messages: [
    { role: 'system', content: '你是一个有用的助手' },
    { role: 'user', content: '你好,请介绍一下自己' }
  ],
  temperature: 0.7,
  max_tokens: 1000
};

axios.post(url, data, {
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${apiKey}`
  }
})
.then(response => {
  console.log(response.data.choices[0].message.content);
})
.catch(error => {
  console.error('Error:', error.response?.data || error.message);
});

3. 请求参数说明

参数类型必填说明
modelstring模型名称:deepseek-chatdeepseek-coder
messagesarray对话消息列表
temperaturefloat控制随机性,范围 0-2,默认 1.0
max_tokensinteger最大输出长度,默认 4096
top_pfloat核采样参数,范围 0-1,默认 1.0
frequency_penaltyfloat频率惩罚,范围 -2 到 2,默认 0
presence_penaltyfloat存在惩罚,范围 -2 到 2,默认 0
streamboolean是否流式输出,默认 false

messages 格式

[
  {"role": "system", "content": "系统提示词"},
  {"role": "user", "content": "用户消息"},
  {"role": "assistant", "content": "助手回复"}
]

4. 响应格式

4.1 非流式响应

{
  "id": "chatcmpl-xxx",
  "object": "chat.completion",
  "created": 1701234567,
  "model": "deepseek-chat",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "你好!我是DeepSeek..."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 20,
    "completion_tokens": 50,
    "total_tokens": 70
  }
}

4.2 流式响应

{
  "id": "chatcmpl-xxx",
  "object": "chat.completion.chunk",
  "created": 1701234567,
  "model": "deepseek-chat",
  "choices": [
    {
      "index": 0,
      "delta": {
        "content": "你好"
      },
      "finish_reason": null
    }
  ]
}

5. Python 完整示例(含流式输出)

import requests
import json

def chat_with_deepseek(api_key, messages, stream=False):
    url = "https://api.deepseek.com/v1/chat/completions"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
    }
    
    data = {
        "model": "deepseek-chat",
        "messages": messages,
        "temperature": 0.7,
        "stream": stream
    }
    
    if stream:
        # 流式输出
        response = requests.post(url, headers=headers, json=data, stream=True)
        for line in response.iter_lines():
            if line:
                line = line.decode('utf-8')
                if line.startswith('data: '):
                    line = line[6:]
                    if line != '[DONE]':
                        chunk = json.loads(line)
                        if chunk['choices'][0]['delta'].get('content'):
                            print(chunk['choices'][0]['delta']['content'], end='', flush=True)
    else:
        # 非流式输出
        response = requests.post(url, headers=headers, json=data)
        result = response.json()
        return result['choices'][0]['message']['content']

# 使用示例
api_key = "YOUR_API_KEY"
messages = [
    {"role": "system", "content": "你是一个专业的编程助手"},
    {"role": "user", "content": "用Python写一个快速排序算法"}
]

# 流式输出
print("流式输出:")
chat_with_deepseek(api_key, messages, stream=True)

6. 错误处理

常见错误码

状态码说明处理方法
401API Key 无效检查 API Key 是否正确
429请求频率超限降低请求频率或升级套餐
500服务器错误稍后重试

错误处理示例

def safe_chat(api_key, messages):
    try:
        response = requests.post(url, headers=headers, json=data)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")
        if hasattr(e, 'response') and e.response:
            print(f"错误详情: {e.response.text}")
        return None

7. 计费说明

  • 按 token 数量计费(输入+输出)
  • 具体价格请参考官网最新定价
  • 可在控制台查看使用量和费用

8. 最佳实践

  1. 安全存储 API Key:使用环境变量,不要硬编码
  2. 合理设置 temperature:创意任务用高值,事实任务用低值
  3. 使用流式输出:提升用户体验
  4. 错误重试机制:使用指数退避策略
  5. 监控使用量:定期查看控制台统计

9. 更多资源


注意:请妥善保管您的 API Key,避免泄露。如有任何问题,欢迎查阅官方文档或联系技术支持。

浏览 100
点赞 0