DeepSeek API UML 文档

本文档以 PlantUML 建模语言,完整梳理 DeepSeek API 的架构、数据结构和交互行为。按 行为图 → 结构图 递进组织,从系统"做什么"到"由什么组成"。

第1部分:行为图(系统做什么)

描述 DeepSeek API 的动态行为:接口调用流程、数据流转、错误处理、定价规则等。

1. 系统交互总览

从宏观视角展示客户端与 DeepSeek API 各层的交互关系。客户端通过不同 Base URL 访问不同格式的 API,经认证后请求模型推理。

系统交互总览
图1:DeepSeek API 系统交互总览(组件图)

通用请求格式

所有 API 调用统一使用 Authorization: Bearer {API_KEY} 认证头。

curl https://api.deepseek.com/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $DEEPSEEK_API_KEY" \
  -d '{ ... }'

2. 对话补全流程

Chat Completion API 是非流式对话补全的核心入口。支持两种模式:非流式(一次性返回完整响应)和 流式(SSE 逐 token 推送)。

对话补全时序图
图2:Chat Completion 对话补全流程(序列图)

非流式请求

curl https://api.deepseek.com/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $DEEPSEEK_API_KEY" \
  -d '{
    "model": "deepseek-v4-flash",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "Hello!"}
    ],
    "thinking": {"type": "disabled"},
    "stream": false
  }'

响应:

{
  "id": "chatcmpl-xxx",
  "object": "chat.completion",
  "created": 1720000000,
  "model": "deepseek-v4-flash",
  "choices": [{
    "index": 0,
    "message": {
      "role": "assistant",
      "content": "Hello! How can I help you today?"
    },
    "finish_reason": "stop"
  }],
  "usage": {
    "prompt_tokens": 18,
    "completion_tokens": 9,
    "total_tokens": 27,
    "prompt_cache_hit_tokens": 0,
    "prompt_cache_miss_tokens": 18,
    "completion_tokens_details": { "reasoning_tokens": 0 }
  }
}

流式请求

curl https://api.deepseek.com/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $DEEPSEEK_API_KEY" \
  -d '{
    "model": "deepseek-v4-flash",
    "messages": [{"role": "user", "content": "Hello!"}],
    "stream": true
  }'

流式响应(SSE):

data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}
data: {"choices":[{"index":0,"delta":{"content":"Hello"},"finish_reason":null}]}
data: {"choices":[{"index":0,"delta":{"content":"!"},"finish_reason":null}]}
data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens": 5,"completion_tokens":2,"total_tokens":7}}
data: [DONE]

3. Thinking Mode 思维链流程

Thinking Mode 启用后,模型会首先生成思维链(reasoning_content),再输出最终答案。工具调用场景下,思维链内容处理规则与普通对话不同。

关键规则:
Thinking Mode 思维链流程
图3:Thinking Mode 思维链交互流程(序列图)

启用 Thinking Mode 请求

curl https://api.deepseek.com/chat/completions \
  -H "Authorization: Bearer $DEEPSEEK_API_KEY" \
  -d '{
    "model": "deepseek-v4-pro",
    "messages": [
      {"role": "user", "content": "What is 15% of 280?"}
    ],
    "thinking": {"type": "enabled"},
    "reasoning_effort": "high"
  }'

响应(含思维链):

{
  "choices": [{
    "message": {
      "role": "assistant",
      "reasoning_content": "To find 15% of 280, I multiply 280 by 0.15...",
      "content": "15% of 280 is 42."
    }
  }],
  "usage": {
    "completion_tokens": 23,
    "completion_tokens_details": { "reasoning_tokens": 15 }
  }
}

多轮对话(无 Tool Call)— 无需回传 reasoning_content

curl ... -d '{
  "messages": [
    {"role": "user", "content": "What is 15% of 280?"},
    {"role": "assistant", "content": "15% of 280 is 42."},
    {"role": "user", "content": "What about 20%?"}
  ],
  "thinking": {"type": "enabled"}
}'

多轮对话(有 Tool Call)— 必须回传 reasoning_content

curl ... -d '{
  "messages": [
    {"role": "user", "content": "Read plot.txt and summarize it."},
    {"role": "assistant", "content": null,
     "reasoning_content": "The user wants to read a file...",
     "tool_calls": [{"id":"call_1","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"plot.txt\"}"}}]
    },
    {"role": "tool", "tool_call_id": "call_1",
     "content": "A story about a detective in Shanghai."},
    {"role": "assistant", "content": null,
     "reasoning_content": "Now I have the file content...",
     "tool_calls": [{"id":"call_2","type":"function","function":{"name":"summarize","arguments":"{\"text\":\"A story about...\"}"}}]
    },
    {"role": "tool", "tool_call_id": "call_2",
     "content": "A detective story set in Shanghai."}
  ],
  "thinking": {"type": "enabled"}
}'

4. Tool Calls 工具调用流程

Tool Calls 允许模型在推理过程中调用外部函数。Non-Thinking 模式下直接返回 tool_calls;Strict Mode (Beta) 下需额外满足 JSON Schema 严格校验。

Tool Calls 工具调用流程
图4:Tool Calls 工具调用流程(序列图)

定义工具并调用

curl https://api.deepseek.com/chat/completions \
  -H "Authorization: Bearer $DEEPSEEK_API_KEY" \
  -d '{
    "model": "deepseek-v4-flash",
    "messages": [
      {"role": "user", "content": "What is the weather in Beijing?"}
    ],
    "tools": [{
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "Get current weather for a city",
        "parameters": {
          "type": "object",
          "properties": {
            "city": { "type": "string", "description": "City name" }
          },
          "required": ["city"]
        }
      }
    }],
    "thinking": {"type": "disabled"}
  }'

模型返回工具调用:

{
  "choices": [{
    "message": {
      "role": "assistant",
      "content": null,
      "tool_calls": [{
        "id": "call_abc123",
        "type": "function",
        "function": {
          "name": "get_weather",
          "arguments": "{\"city\": \"Beijing\"}"
        }
      }]
    },
    "finish_reason": "tool_calls"
  }]
}

回传工具执行结果:

curl ... -d '{
  "messages": [
    {"role": "user", "content": "What is the weather in Beijing?"},
    {"role": "assistant", "content": null, "tool_calls": [
      {"id":"call_abc123","type":"function","function":{"name":"get_weather","arguments":"{\"city\":\"Beijing\"}"}}
    ]},
    {"role": "tool", "tool_call_id": "call_abc123", "content": "Beijing: Sunny, 25 C"}
  ],
  "tools": [{ ... }]
}'

最终响应:

{
  "choices": [{
    "message": {
      "role": "assistant",
      "content": "The weather in Beijing is Sunny, with a temperature of 25 C."
    },
    "finish_reason": "stop"
  }]
}

5. Context Caching 上下文缓存机制

上下文缓存自动检测请求间的公共前缀,持久化缓存单元以降低延迟和费用。缓存命中时 prompt_cache_hit_tokens > 0,按缓存命中价计费。

完全服务端自动管理:上下文缓存由 DeepSeek 服务端全权控制,API 用户无需也无法手动干预——没有开启/关闭/设置 TTL 等参数。用户唯一能做的是通过响应中的 prompt_cache_hit_tokens / prompt_cache_miss_tokens 字段观察缓存命中情况,命中费用自动以低价结算。
Context Caching 上下文缓存
图5:Context Caching 上下文缓存机制(序列图)

缓存命中示例

第一次请求(无缓存):

{
  "usage": {
    "prompt_tokens": 500,
    "prompt_cache_hit_tokens": 0,
    "prompt_cache_miss_tokens": 500,
    "total_tokens": 600
  }
}

第二次请求(相同前缀,缓存命中):

{
  "usage": {
    "prompt_tokens": 500,
    "prompt_cache_hit_tokens": 480,
    "prompt_cache_miss_tokens": 20,
    "total_tokens": 600
  }
}

费用对比:Cache Miss $0.14/1M vs Cache Hit $0.0028/1M(V4 Flash),命中后输入成本降低 ~98%。

6. Chat Prefix Completion 前缀补全

Beta 特性:在 assistant 消息中设置 prefix: true,强制模型从指定前缀开始续写,配合 stop 序列结束输出。

Chat Prefix Completion
图6:Chat Prefix Completion 前缀补全流程(序列图)

前缀补全请求(强制以代码块开头)

curl https://api.deepseek.com/beta/chat/completions \
  -H "Authorization: Bearer $DEEPSEEK_API_KEY" \
  -d '{
    "model": "deepseek-v4-flash",
    "messages": [
      {"role": "user", "content": "Write a Python function to calculate factorial."},
      {"role": "assistant", "content": "```python\n", "prefix": true}
    ],
    "stop": ["```"]
  }'

响应(以 `` ```python `` 开头,到 `` ``` `` 自动停止):

{
  "choices": [{
    "message": {
      "role": "assistant",
      "content": "```python\ndef factorial(n):\n    if n <= 1:\n        return 1\n    return n * factorial(n - 1)\n```"
    },
    "finish_reason": "stop"
  }]
}
Chat Prefix Completion 本质:这是 /chat/completions 的扩展而非独立接口(复用同一端点,仅 base_url 换 beta + 末尾 assistant 消息设 prefix: true)。场景较窄——强制模型以特定格式开头(如强制输出代码块),配合 stop 精确控制输出边界。AI Agent 一般不需要:JSON Output 和 Tool Calls 已覆盖结构化输出需求。

7. FIM Completion 中间补全

Beta 特性:Fill-in-the-Middle 代码补全,给定前缀 (prompt) 和后缀 (suffix),模型生成中间填充内容。最大输出 4K tokens。

FIM Completion 中间补全
图7:FIM Completion 中间补全流程(序列图)

FIM 代码补全请求

curl https://api.deepseek.com/beta/completions \
  -H "Authorization: Bearer $DEEPSEEK_API_KEY" \
  -d '{
    "model": "deepseek-v4-flash",
    "prompt": "def fib(a):",
    "suffix": "    return fib(a-1) + fib(a-2)",
    "max_tokens": 128
  }'

响应(模型填充 prefix 和 suffix 之间的内容):

{
  "id": "cmpl-xxx",
  "object": "text_completion",
  "choices": [{
    "index": 0,
    "text": "\n    if a <= 1:\n        return a\n",
    "finish_reason": "stop"
  }],
  "usage": {
    "prompt_tokens": 10,
    "completion_tokens": 12,
    "total_tokens": 22
  }
}

完整结果:def fib(a):\n if a <= 1:\n return a\n return fib(a-1) + fib(a-2)

使用场景区分:FIM Completion 是独立端点 POST /completions(非 /chat/completions),仅 IDE 代码补全场景需要(如 VSCode Continue 插件)。OpenCode、Claude Code、Cursor 等 AI Agent 只用 /chat/completions,不走 FIM 接口——Agent 需要多轮对话、Tool Calls、上下文管理,FIM 的 prompt/suffix 格式无法承载。

Chat Prefix Completion vs FIM Completion 对比

Chat Prefix CompletionFIM Completion
端点/chat/completions (beta)/completions (beta)
输入messages 数组,末尾 assistant 设 prefix: trueprompt + suffix
作用强制以指定文本开头续写,只控起点给定头尾,填充中间,两头都控
输出上限384K tokens4K tokens
典型场景强制输出代码块等格式化内容IDE 实时代码补全
AI Agent 使用极少(JSON Output 更适用)不使用

8. JSON Output 结构化输出

通过 response_format: {type: "json_object"} 强制模型输出有效 JSON。需要在 system/user prompt 中包含 "json" 关键词并给出格式示例。

JSON Output 结构化输出
图8:JSON Output 结构化输出流程(序列图)

JSON 模式请求

curl https://api.deepseek.com/chat/completions \
  -H "Authorization: Bearer $DEEPSEEK_API_KEY" \
  -d '{
    "model": "deepseek-v4-flash",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant.\nResponse in strict json format:\n{\"name\": \"...\", \"age\": 0}"},
      {"role": "user", "content": "Extract info: John is 28 years old."}
    ],
    "response_format": {"type": "json_object"},
    "max_tokens": 200
  }'

响应:

{
  "choices": [{
    "message": {
      "role": "assistant",
      "content": "{\"name\": \"John\", \"age\": 28}"
    },
    "finish_reason": "stop"
  }]
}

9. 错误处理状态机

API 调用过程中的各错误状态及恢复路径。

错误处理状态机
图9:错误处理状态机(状态机图)

常见错误响应示例

HTTP 状态场景响应体示例处理方式
400请求体格式错误
{"error":{"message":"Invalid request format","type":"invalid_request_error"}}
检查 JSON 语法和字段类型
401API Key 无效
{"error":{"message":"Invalid API key","type":"authentication_error"}}
重新生成 API Key
402余额不足
{"error":{"message":"Insufficient balance","type":"insufficient_balance"}}
前往 platform.deepseek.com 充值
422参数无效
{"error":{"message":"Invalid parameter: model","type":"invalid_request_error"}}
按错误提示修正参数
429超过并发限制
{"error":{"message":"Rate limit exceeded","type":"rate_limit_error"}}
降速重试或申请扩容
500服务器内部错误
{"error":{"message":"Internal server error","type":"server_error"}}
等待后重试
503服务器过载
{"error":{"message":"Server is overloaded","type":"server_error"}}
等待后重试,必要时联系支持

10. 计价与扣费规则

余额由授权余额(Granted Balance)和充值余额(Topped-up Balance)组成,优先使用授权余额。费用按 token 数量 × 单价计算。

计价与扣费规则
图10:计价与扣费规则(活动图)

计价实例

模型场景输入 Token输出 Token费用
V4 Flash简单对话~100~50~$0.000028
V4 Flash长文分析 (Cache Hit)~10,000 (9,800 hit)~500~$0.000167
V4 Pro复杂推理~2,000~1,000~$0.00174

余额查询

curl https://api.deepseek.com/user/balance \
  -H "Authorization: Bearer $DEEPSEEK_API_KEY"
{
  "is_available": true,
  "balance_infos": [{
    "currency": "USD",
    "total_balance": "10.00",
    "granted_balance": "5.00",
    "topped_up_balance": "5.00"
  }]
}

扣费优先级:granted_balance 先扣 → topped_up_balance 再扣。

11. Token 计算体系

介绍 Token 基本概念(1 英文字符 ≈ 0.3 token,1 中文字符 ≈ 0.6 token)、离线 Tokenizer 以及 API 响应中 Usage 字段的含义。

Token 计算体系
图11:Token 计算体系(活动图)

Token 消耗示例

文本字符数估算 Token说明
"Hello, world!"13~4纯英文,1 token ≈ 3-4 字符
"你好世界"4~2-3中文,1 token ≈ 1-2 字符
"print('hello')"14~5代码中常见关键字可合并为 1 token

Usage 响应详解

{
  "usage": {
    "completion_tokens": 150,            // 模型生成的 token
    "prompt_tokens": 1200,               // 输入 token 总数 = hit + miss
    "prompt_cache_hit_tokens": 1100,     // 缓存命中的输入 token(低价计费)
    "prompt_cache_miss_tokens": 100,     // 缓存未命中的输入 token(标准计费)
    "total_tokens": 1350,                // 请求总 token = prompt + completion
    "completion_tokens_details": {
      "reasoning_tokens": 80             // Thinking Mode 产生的思维链 token
    }
  }
}

12. Thinking Mode 参数约束

Thinking Mode 启用后,temperature / top_p 等参数被忽略。reasoning_effort 的 low/medium → high,xhigh → max。

Thinking Mode 参数约束
图12:Thinking Mode 参数约束(活动图)

被忽略参数示例

以下请求中 temperature 和 top_p 虽然传入,但在 Thinking Mode 下会被静默忽略:

curl ... -d '{
  "model": "deepseek-v4-pro",
  "messages": [{"role": "user", "content": "Explain quantum computing."}],
  "thinking": {"type": "enabled"},
  "temperature": 0.7,          // 被忽略
  "top_p": 0.9,                // 被忽略
  "reasoning_effort": "high"   // 有效: high/max
}'

reasoning_effort 映射

传入值实际映射
"low", "medium"→ "high"
"xhigh"→ "max"
"high", "max"直接使用

13. Strict Mode JSON Schema

Beta 特性:启用 Strict Mode 后,工具调用的参数必须严格遵循 JSON Schema 定义。要求 additionalProperties: false,所有 properties 必须设为 required。

Strict Mode JSON Schema
图13:Strict Mode JSON Schema 类型支持(活动图)

Strict Mode 工具定义示例

curl https://api.deepseek.com/beta/chat/completions \
  -H "Authorization: Bearer $DEEPSEEK_API_KEY" \
  -d '{
    "model": "deepseek-v4-flash",
    "messages": [{"role": "user", "content": "Book a flight: Beijing to Shanghai, May 1st, economy."}],
    "tools": [{
      "type": "function",
      "function": {
        "name": "book_flight",
        "description": "Book a flight ticket",
        "strict": true,
        "parameters": {
          "type": "object",
          "properties": {
            "from": {"type": "string"},
            "to": {"type": "string"},
            "date": {"type": "string", "format": "date"},
            "class": {"type": "string", "enum": ["economy", "business", "first"]}
          },
          "required": ["from", "to", "date", "class"],
          "additionalProperties": false
        }
      }
    }],
    "thinking": {"type": "disabled"}
  }'

响应(严格符合 Schema 的 tool_calls):

{
  "choices": [{
    "message": {
      "tool_calls": [{
        "function": {
          "name": "book_flight",
          "arguments": "{\"from\":\"Beijing\",\"to\":\"Shanghai\",\"date\":\"2026-05-01\",\"class\":\"economy\"}"
        }
      }]
    },
    "finish_reason": "tool_calls"
  }]
}
Strict Mode 三要素:
  1. function.strict = true
  2. additionalProperties = false
  3. 所有 properties 必须列入 required 数组

第2部分:结构图(系统由什么组成)

描述 DeepSeek API 的静态结构:组件拓扑、模型定义、API 端点、数据结构、速率限制、格式兼容性等。

14. 系统组件架构

从组件视角展示 DeepSeek API 的内部分层拓扑:认证层 → Base URL 层 → 端点层 → 模型层 → 功能层。

系统组件架构
图14:DeepSeek API 组件架构(组件图)

15. 模型详情

DeepSeek 当前提供两个主力模型和两个即将废弃的别名模型。

属性deepseek-v4-prodeepseek-v4-flash
上下文长度1M tokens1M tokens
最大输出384K tokens384K tokens
并发限制5002500
输入 Cache Hit$0.003625 / 1M$0.0028 / 1M
输入 Cache Miss$0.435 / 1M$0.14 / 1M
输出$0.87 / 1M$0.28 / 1M
Thinking Mode支持支持
FIM Completion仅 Non-Thinking仅 Non-Thinking
模型详情类图
图15:DeepSeek 模型详情与关系(类图)

16. API 端点定义

4 个核心 API 端点均需 Bearer Token 认证,其中 FIM Completion 必须在 Beta URL 下访问。

API 端点定义
图16:API 端点定义与依赖关系(类图)

17. Chat Completion 数据结构

Chat Completion API 的完整请求/响应数据结构,包含 Message、Tool、ThinkingConfig、ResponseFormat、StreamChunk 等核心类型。

Chat Completion 请求结构
图17a:Chat Completion 请求数据结构(类图)
Chat Completion 响应结构
图17b:Chat Completion 响应数据结构(类图)

18. 限流与隔离机制

以 Account 为顶层单位,通过 UserId 实现内容安全、KVCache 和调度三层面的隔离。每个请求从发送到响应完成占用一个并发槽位。

限流与隔离机制
图18:限流与隔离机制(类图)

19. 两类 API 兼容性对比

OpenAI 格式与 Anthropic 格式在 Base URL、字段映射、SDK 调用方式上的差异。

两类 API 兼容性对比
图19:OpenAI vs Anthropic 格式对比(类图)

20. Anthropic 字段兼容矩阵

DeepSeek Anthropic 格式对各 Anthropic API 字段的支持情况——HTTP 头、简单字段、工具字段、消息内容类型的完整兼容性矩阵。

Anthropic 字段兼容矩阵
图20:Anthropic API 字段兼容矩阵(类图)