Skip to content

DeepSeek API 按 token 计费,1 个英文字符约 0.3 个 token,1 个中文字符约 0.6 个 token。每次 API 调用会在 response 的 usage 字段返回实际消耗量,用于精确计费追踪和成本控制。

DeepSeek API Token 计算

Token 是什么

Token 是模型处理文本的最小单位,也是 DeepSeek API 计费的基本粒度。

中英文 Token 估算

内容类型大致换算
英文字母/数字1 字符 ≈ 0.3 token
中文汉字1 字符 ≈ 0.6 token
中文标点、空格视具体字符而定

以上为估算值。不同模型的分词方式有差异,以接口实际返回的 usage 为准

用 usage 字段跟踪消耗

每次 API 调用的 response 都包含 usage 字段:

typescript
const response = await client.chat.completions.create({
  model: "deepseek-v4-pro",
  messages: [{ role: "user", content: "用中文解释什么是 Token" }],
});

console.log(response.usage);
// {
//   prompt_tokens: 18,
//   completion_tokens: 120,
//   total_tokens: 138,
//   prompt_cache_hit_tokens: 0,    // KV Cache 命中的 token 数
//   prompt_cache_miss_tokens: 18,  // 未命中缓存的 token 数
// }
字段含义
prompt_tokens输入(包含 system + 历史 + 当前 user)
completion_tokens本次输出
total_tokens总计
prompt_cache_hit_tokens命中 KV Cache 的 token(更低价格)
prompt_cache_miss_tokens未命中缓存的 token(正常价格)

成本控制技巧

1. 监控每次调用的 token 消耗

typescript
let totalCost = 0;

function calculateCost(usage: any, model: string): number {
  const rates = {
    "deepseek-v4-flash": { cacheHit: 0.02, cacheMiss: 1.0, output: 2.0 },
    "deepseek-v4-pro": { cacheHit: 0.025, cacheMiss: 3.0, output: 6.0 },
  };
  const rate = rates[model as keyof typeof rates] ?? rates["deepseek-v4-pro"];
  
  return (
    (usage.prompt_cache_hit_tokens * rate.cacheHit +
      usage.prompt_cache_miss_tokens * rate.cacheMiss +
      usage.completion_tokens * rate.output) / 1_000_000
  );
}

2. 控制输入长度

多轮对话时,历史消息会不断累积,输入 token 会越来越多。建议:

  • 设置最大历史轮数(如保留最近 10 轮)
  • 对早期历史做摘要压缩
  • 利用 KV Cache 降低重复前缀成本

3. 合理设置 max_tokens

避免输出过长导致不必要的 token 消耗:

typescript
{
  model: "deepseek-v4-pro",
  max_tokens: 500,  // 根据实际需要设置
  // ...
}

离线 Tokenizer

DeepSeek 提供官方离线 tokenizer 工具(deepseek_tokenizer.zip),可在本地统计 token 数量,适合批量预估成本。前往 DeepSeek 开放平台 下载。

常见问题

Q: 思考模式(reasoning_content)的 token 也计费吗?

A: 会,reasoning_content 的 token 计入输出 token 计费。如果不需要查看推理过程,可设 thinking: {type: "disabled"} 节省成本。

Q: stream 流式输出会影响 token 计费吗?

A: 不影响,流式和非流式消耗的 token 数量相同,只是返回方式不同。

Q: 中文 prompt 比英文贵吗?

A: 中文字符的 token 比例高于英文(约 2 倍),相同语义内容用中文表达消耗的 token 更多。但 DeepSeek 对中文的理解能力强,不需要为了省 token 改成英文 prompt。