Skip to content

POST /chat/completions 是 DeepSeek API 的核心接口,完全兼容 OpenAI Chat Completions 格式。在此基础上新增 thinking(思考模式)、prefix(对话前缀续写)等扩展参数。支持流式输出(SSE)和工具调用(Tool Calls)。

DeepSeek Chat Completions API 参考

端点: POST https://api.deepseek.com/chat/completions
Beta 端点: POST https://api.deepseek.com/beta/chat/completions(支持 prefix 续写)

请求体参数

必填参数

参数类型说明
messagesobject[]对话消息列表,按时间顺序排列
modelstring模型 ID,如 deepseek-v4-pro

messages 对象

每条消息包含以下字段:

字段类型必填说明
rolestringsystem / user / assistant / tool
contentstring | null消息内容(assistant 在有 tool_calls 时可为 null)
namestring角色名称(可选)
prefixbooleantrue 表示此消息为续写前缀(仅 Beta 端点,必须是最后一条 assistant 消息)
reasoning_contentstring思考模式的推理链内容(仅 assistant 消息,Beta 端点)
tool_call_idstring工具调用 ID(仅 role=tool 时使用)
tool_callsobject[]工具调用列表(仅 assistant 消息)

可选参数

参数类型默认值说明
thinkingobject思考模式控制:{ type: "enabled" } 开启,{ type: "disabled" } 关闭
frequency_penaltynumber0范围 [-2, 2],正值降低重复内容概率
max_tokensinteger最大输出 token 数(deepseek-v4 最大 384K)
presence_penaltynumber0范围 [-2, 2],正值鼓励探讨新话题
response_formatobject{type:"text"}输出格式,{type:"json_object"} 开启 JSON 模式
stopstring | string[]遇到指定字符串时停止生成
streambooleanfalsetrue 启用流式 SSE 输出
stream_optionsobject{include_usage: true} 在流末尾输出 token 用量
temperaturenumber1采样温度,范围 [0, 2]。越高越随机,与 top_p 二选一
top_pnumber1核采样参数,范围 (0, 1],与 temperature 二选一
toolsobject[]可调用的 Function 列表
tool_choicestring | objectauto工具调用策略:none / auto / required / {type:"function",function:{name:"..."}}
logprobsboolean是否在响应中包含 token 对数概率
top_logprobsinteger每个 token 返回前 N 个概率(0-20,需 logprobs=true)

tools 对象结构

typescript
{
  type: "function",
  function: {
    name: string,          // 函数名称(必填)
    description?: string,  // 函数描述,帮助模型决定是否调用
    parameters?: object,   // JSON Schema 格式的参数描述
    strict?: boolean,      // true 启用 Strict 模式(Beta)
  }
}

响应体

非流式响应

json
{
  "id": "930c60df-bf64-41c9-a88e-3ec75f81e00e",
  "object": "chat.completion",
  "created": 1705651092,
  "model": "deepseek-v4-pro",
  "system_fingerprint": "fp_...",
  "choices": [
    {
      "index": 0,
      "finish_reason": "stop",
      "message": {
        "role": "assistant",
        "content": "Hello! How can I help you today?",
        "reasoning_content": null,
        "tool_calls": null
      },
      "logprobs": null
    }
  ],
  "usage": {
    "prompt_tokens": 16,
    "completion_tokens": 10,
    "total_tokens": 26,
    "prompt_cache_hit_tokens": 8,
    "prompt_cache_miss_tokens": 8,
    "completion_tokens_details": {
      "reasoning_tokens": 0
    }
  }
}

finish_reason 取值

说明
stop正常结束(遇到停止词或生成完毕)
length达到 max_tokens 限制
tool_calls模型请求调用工具
content_filter内容被过滤
insufficient_system_resource系统资源不足(重试即可)

流式响应

stream: true 时返回 SSE 事件流:

data: {"id":"...","object":"chat.completion.chunk","choices":[{"delta":{"role":"assistant","content":"Hello"},"finish_reason":null}]}

data: {"id":"...","object":"chat.completion.chunk","choices":[{"delta":{"content":" World"},"finish_reason":null}]}

data: {"id":"...","object":"chat.completion.chunk","choices":[{"delta":{},"finish_reason":"stop"}]}

data: [DONE]

代码示例

typescript
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.deepseek.com",
  apiKey: process.env.DEEPSEEK_API_KEY,
});

// 基础对话
const response = await client.chat.completions.create({
  model: "deepseek-v4-pro",
  messages: [
    { role: "system", content: "你是一个专业的 TypeScript 开发者" },
    { role: "user", content: "解释 TypeScript 泛型约束" },
  ],
  temperature: 0.7,
  max_tokens: 2048,
});

console.log(response.choices[0].message.content);
console.log(`Token 用量:${response.usage?.total_tokens}`);
console.log(`KV 缓存命中:${response.usage?.prompt_cache_hit_tokens}`);
typescript
// 流式输出
const stream = await client.chat.completions.create({
  model: "deepseek-v4-pro",
  messages: [{ role: "user", content: "写一首关于代码的诗" }],
  stream: true,
  stream_options: { include_usage: true },
});

for await (const chunk of stream) {
  const delta = chunk.choices[0]?.delta?.content ?? "";
  process.stdout.write(delta);
  
  // 最后一个 chunk 包含 usage 信息
  if (chunk.usage) {
    console.log(`\nTotal tokens: ${chunk.usage.total_tokens}`);
  }
}
python
# Python 版本
from openai import OpenAI

client = OpenAI(
    api_key="<your api key>",
    base_url="https://api.deepseek.com",
)

response = client.chat.completions.create(
    model="deepseek-v4-pro",
    messages=[{"role": "user", "content": "Hello"}],
)
print(response.choices[0].message.content)

常见问题

Q: reasoning_content 字段什么时候会有值?

A: 只有在思考模式(thinking: { type: "enabled" })下,reasoning_content 才会包含模型的思考过程。普通模式下该字段为 null。详见 思考模式指南

Q: prompt_cache_hit_tokens 是什么意思?

A: 这是 KV Cache 命中的 token 数量。命中的 token 以折扣价计费,未命中的按全价计费。详见 KV Cache 文档