DeepSeek 网摘deepseek.wang
EN
📄 查看英文原文

API · 2026-04-25 · 机器翻译,仅供参考

How DeepSeek API JSON Mode Works on V4 (With Code)

API·April 25, 2026·By DS Guide Editorial
DeepSeek API JSON-mode tutorial card showing the five steps to force valid JSON output on V4: set response_format to json_object, include the literal word json plus an example schema in the prompt to avoid empty responses, set max_tokens high enough to avoid truncation, parse the response content as JSON, and prefer tool calls when you need a strict schema contract.

如果你曾经将LLM功能部署到生产环境中,你就知道其中的痛苦:模型返回的是散文,而你需要的是可解析的对象,下游代码抛出异常,而值班工程师凌晨2点被叫醒。DeepSeek API JSON模式就是解决方案——它强制`deepseek-v4-pro`和`deepseek-v4-flash`输出有效的JSON字符串而不是自由文本,这样你就可以直接将输出传递给类型解析器。

本指南详细介绍了该功能在V4(发布于2026年4月24日)上的行为,三个防止空响应的提示规则,V4两个级别的成本示例,错误处理以及与结构化提取工具调用的比较。每个声明都有官方文档或测试过的代码路径作为支持。

DeepSeek API JSON模式实际上做什么

Diagram comparing DeepSeek API free-text response and JSON mode response shapes side by side

JSON模式是一个请求级别的标志,它将模型的输出限制为有效的JSON字符串。你可以通过设置 response_format={"type": "json_object"} 在上 POST /chat/completions 请求中。官方DeepSeek文档将该功能描述为旨在确保 JSON模式在V4模型ID上都能正常工作—— valid JSON output, and the parameter reference says setting to { “type”: “json_object” } enables JSON Output, which guarantees the message the model generates is valid JSON.

那个词“保证”需要一些保留意见。在实践中,仍然有两种失败模式:如果提示没有正确引导模型,模型可以返回空内容,而且如果你设置 max_tokens 太低,JSON仍然可能被截断。官方指南直接承认了第一种失败模式:当使用JSON输出功能时,API可能会偶尔返回空内容。我们正在积极优化这个问题。你可以尝试修改提示来减轻此类问题。将JSON模式视为一个强约束,而不是一个合同。

——无论是默认思考模式还是非思考模式(传递 deepseek-v4-flash and deepseek-v4-pro )。它也适用于旧版 extra_body={"thinking": {"type": "disabled"}}). It also works on the legacy deepseek-chat and deepseek-reasoner 当前路由到的ID deepseek-v4-flash and will be retired on 2026-07-24 at 15:59 UTC。如果您有较旧的集成,在该日期之前将值更改为V4 ID—— model 不变。关于迁移机制的更新,请参阅我们的 base_url 相同端点的等效curl调用: DeepSeek OpenAI SDK compatibility notes.

快速入门:最简Python和curl

测试JSON模式最经济的方式是使用指向DeepSeek基础URL的官方OpenAI SDK。聊天请求击中OpenAI兼容的端点。以下是标准的Python代码片段,经过轻微编辑来自DeepSeek自己的JSON输出指南: POST /chat/completions,没有它,DeepSeek在模型运行之前就会拒绝请求。一个针对Node集成的真实错误报告捕捉到了确切的错误:在使用DeepSeek API时,如果提示词没有明确包含单词“json”,API会返回错误:提示词必须以某种形式包含单词“json”,才能使用“response_format”的类型“json_object”。修复方法是系统提示词中的一行——“仅以JSON回复。”就解决了。

import json
from openai import OpenAI

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

system_prompt = """
The user will provide some exam text.
Please parse the "question" and "answer" and output them in JSON format.

EXAMPLE INPUT:
Which is the highest mountain in the world? Mount Everest.

EXAMPLE JSON OUTPUT:
{
  "question": "Which is the highest mountain in the world?",
  "answer": "Mount Everest"
}
"""

user_prompt = "Which is the longest river in the world? The Nile River."

response = client.chat.completions.create(
    model="deepseek-v4-pro",
    messages=[
        {"role": "system", "content": system_prompt},
        {"role": "user",   "content": user_prompt},
    ],
    response_format={"type": "json_object"},
    max_tokens=1024,
)

print(json.loads(response.choices[0].message.content))

如果您尚未配置凭证,请首先完成

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 return JSON only. Schema: {"city":string,"temp_c":number}"},
      {"role": "user",   "content": "Hangzhou, 24 degrees."}
    ],
    "response_format": {"type": "json_object"},
    "max_tokens": 256
  }'

API密钥设置向导;本指南的其余部分假设已有一个工作密钥在 中 。字面词“json”必须在提示中出现。 DEEPSEEK_API_KEY.

防止空响应的三个提示规则

Most “JSON mode is broken” reports trace back to one of three preventable mistakes. The official docs are explicit about all three. To enable JSON Output, set the response_format parameter to {‘type’: ‘json_object’}. Include the word “json” in the system or user prompt, and provide an example of the desired JSON format to guide the model in outputting valid JSON. Set the max_tokens parameter reasonably to prevent the JSON string from being truncated midway.

  1. 在提示中提供一个示例模式。 如果响应在字符串中间停止,你会得到无效的JSON和解析异常。Chat Completions参考明确指出:如果finish_reason="length",则消息内容可能被部分截断,这表示生成超过了max_tokens或对话超过了最大上下文长度。估计最大的合理响应并将其加倍;在V4中,你可以达到384,000个输出令牌。
  2. Provide an example schema in the prompt. Without one, the model invents its own keys. The Stagehand catch-22 illustrates this: the project added “json” to satisfy the gate, then found DeepSeek returns a format like: { “action”: “fill”, “element”: {“id”: “…”, “role”: “…”, “name”: “…”}, “argument”: “Cota”, “twoStep”: false } — which did not match the integration’s expected schema at all. Always paste an example object showing exactly the keys, types, and nesting you want.
  3. Set max_tokens 高到足以使JSON无法截断。 工具调用严格模式更为严格——DeepSeek在返回之前会验证你的JSON模式。约束是真实的:每个对象的每个属性都必须设置为必需的,并且对象的additionalProperties属性必须设置为false。JSON模式没有这样的约束,这就是为什么在提示词中的示例模式如此重要的原因。对于代理循环或任何输出键映射到函数签名的情况,请首选工具调用——参见

如果您跳过这些并直接导出 response_format 在上 stock chat prompt, expect failures. 我们的提示工程参考 涵盖了将示例种子放入系统提示的更广泛模式。

JSON模式与工具调用:何时使用哪个

这两个功能都产生结构化输出,但它们解决不同的问题。

Feature JSON mode 工具调用(严格)
激活 response_format={"type":"json_object"} tools=[...] with strict: true
模式强制执行 仅提示级别 服务器端针对JSON Schema
输出形状 自由形式的JSON content 结构化参数输入 工具调用数组中的函数参数
Best for 单次提取、分类、简单对象 Multi-step agents, validated functi在上rguments, enums
需要处理的故障模式 空内容, schema drift 幻觉参数(解析器仍需使用)

JSON模式不会改变计费标准——你将支付与常规聊天完成相同的每令牌费用。问题是系统提示词中的示例模式是每次调用都要付费的令牌,因此上下文缓存比以往更重要。以下价格来自DeepSeek截至2026年4月发布的计费标准;请与当前价格进行核实。 DeepSeek API 函数调用指南对于从文档中临时提取数据,JSON 模式更简单且成本更低。

详细参考:参数和响应形状

JSON 模式的完整请求形状如下所示:

Parameter JSON 模式的值 Notes
model deepseek-v4-flash or deepseek-v4-pro 旧版 ID 将接受至 2026-07-24 15:59 UTC。
messages 包含单词“json”的数组 + 示例 无状态——每次调用重发完整历史记录。
response_format {"type": "json_object"} 激活约束所必需的。
max_tokens 丰富——最小 1024,最多 384,000 防止JSON截断。
temperature 0.0用于确定性提取。 DeepSeek建议代码/数学使用0.0;创意工作则提高该值。
reasoning_effort 可选。 "high" or "max" 配对使用。 extra_body={"thinking": {"type": "enabled"}}.

响应对象遵循OpenAI的格式。JSON字符串位于 choices[0].message.content。如果您启用思考模式,API将返回 reasoning_content 旁边 the final content,您的JSON解析应仅针对 content。Token使用情况分解为 prompt_cache_hit_tokens, prompt_cache_miss_tokens, and completion_tokens — 适用于精确的成本核算(参见下一节)。

该API是无状态的。服务器不保留之前调用的记忆;您必须每次重新发送完整的数组。这与维护服务器上会话历史的Web应用不同。 messages 完整的API文档中心 提供了完整的请求/响应模式,如果您想深入了解。 输入缓存命中($/1M)

定价示例

JSON mode does not change the rate card — you pay the same per-token rates as a regular chat completion. The wrinkle is that example schemas in the system prompt are tokens you pay for on every call, so context caching matters more than usual. Pricing below is from DeepSeek’s published rate card as of April 2026; verify against the current DeepSeek API pricing page before committing.

Model tier 输入缓存未命中($/1M) 想象一个文档提取任务:1,000,000份发票通过 Output ($/1M)
deepseek-v4-flash $0.0028 $0.14 $0.28
deepseek-v4-pro $0.003625 (promo, list $0.0145) $0.435 (promo, list $1.74) $0.87 (promo, list $3.48)

Imagine a document-extraction job: 1,000,000 invoices through deepseek-v4-flash,使用包含JSON模式示例的2,000个token的系统提示(跨调用缓存),每张发票200个token的用户消息(未缓存未命中),以及300个token的JSON响应。

  • Cached input: 2,000 × 1,000,000 = 2,000,000,000 tokens × $0.0028/M = $5.60
  • Uncached input: 200 × 1,000,000 = 200,000,000 tokens × $0.14/M = $28.00
  • Output: 300 × 1,000,000 = 300,000,000 tokens × $0.28/M = $84.00
  • Total: $117.60

Same workload on deepseek-v4-pro 用于比较——仅在DeepSeek Chat的质量不足以满足您的特定架构时才适用:

  • Cached input: 2,000,000,000 × $0.003625/M (promo) = $7.25 (list $29.00)
  • Uncached input: 200,000,000 × $0.435/M (promo) = $87.00 (list $348.00)
  • Output: 300,000,000 × $0.87/M (promo) = $261.00 (list $1,044.00)
  • Total: $355.25 在2026-05-31之前的75%促销期间(标价总额1,421.00美元)——促销期间大约是Flash账单的3倍,按列表价格计算大约是14倍。

两个实用提示。首先,缓存仅适用于 重复的前缀 ——您的每张发票用户消息总是未命中,因此未缓存输入行永远不会降至零。其次,不要在一个计算中混合层级费率。有关更多成本建模模式,请参阅 我们对DeepSeek上下文缓存的深入研究.

Error handling patterns

JSON模式引入了两个错误,您需要在正常的API失败处理之外处理这些错误。

空内容

根据官方文档,API可能会偶尔返回空内容。在客户端检测到这种情况,并使用略微调整的提示或温度调整重试。Python中的防御性模式:

raw = response.choices[0].message.content
if not raw or not raw.strip():
    # Retry once with stronger instruction
    return retry_with_stronger_prompt(...)
try:
    parsed = json.loads(raw)
except json.JSONDecodeError:
    # 截断 or malformed - check finish_reason
    if response.choices[0].finish_reason == "length":
        return retry_with_higher_max_tokens(...)
    raise

截断

总是检查 finish_reason。如果它等于 "length",则响应被截断,JSON几乎肯定无效。请增加 max_tokens 并重试。有关更广泛的HTTP级别错误目录(401、402余额不足、429速率限制、503),请参阅 DeepSeek API错误代码参考.

架构漂移

即使在提示中包含示例模式,模型也可能在边缘情况输入中添加或重命名键。请将每个解析后的有效负载与Pydantic模型(Python)或Zod模式(TypeScript)进行验证 before it touches business logic. If validation fails, log the raw output and retry with a strict reminder. This is the pattern that separates demoware from production code; 我们的最佳实践指南 在此方面进行更深入的研究。

思维模式下的JSON模式

您可以将JSON模式与V4的推理能力相结合。设置 reasoning_effort="high" and extra_body={"thinking": {"type": "enabled"}} 旁边 response_format。该API返回 reasoning_content 旁边 the final content ——JSON位于 content,推理跟踪位于 reasoning_content 仅提供信息。

这对于需要推理链(法律条款、多步骤金融推理、复杂模式映射)的提取任务很有用。对于平面提取来说,这过于强大。输出令牌账单会增加,因为推理令牌被计费为完成令牌。对于高容量、结构简单的任务,请保持非思考模式。

图表:在OpenAI兼容端点上,JSON模式请求的生命周期,显示提示规则、响应格式网关和解析器移交。
Terminal showing a parsed JSON object returned by the DeepSeek API in JSON mode beside the code editor

如果您正在将DeepSeek的结构化输出集成到更广泛的堆栈中:

  • 对于以代理风格的工作流程,其中模型选择工具,请参阅 函数调用.
  • 对于长时间运行的结构化流(例如实时转录清理),将JSON模式与 DeepSeek API streaming 结合——请注意,JSON模式流是可用的,但您必须在解析前缓冲直到关闭括号。
  • 对于端到端可运行的脚本,浏览 DeepSeek API code examples 收藏夹。
  • 对于更广泛的API界面,该 DeepSeek API docs and guides 中心索引了本网站上每个参考页面。

DeepSeek AI Guide is an independent resource and is not affiliated with DeepSeek or its parent company. Model IDs, pricing and API behaviour change; check the official DeepSeek documentati在上nd pricing page before committing to a production decision.

Frequently asked questions

DeepSeek API JSON模式是否保证输出有效的JSON?

官方参数描述称JSON模式保证有效的JSON,但JSON输出指南也指出API偶尔会返回空内容。将其视为强约束,而非合同——始终在try/except中包装解析,检查 finish_reason 用于截断,并针对模式进行验证。 DeepSeek API best practices 指南涵盖了完整的重试模式。

如何修复“提示必须包含单词‘json’”错误?

DeepSeek在尊重之前需要在您的系统或用户提示中包含字面字符串“json”。 response_format={"type": "json_object"}在您的系统消息中添加一句“仅以JSON响应”。当您在那里时,粘贴您想要的精确模式的示例——否则模型会自己发明键。 我们的提示工程指南 包含更多模式。

DeepSeek中JSON模式与工具调用的区别是什么?

JSON模式限制了助手的 content 字段转换为JSON字符串,模式验证由您的提示提供。调用工具返回结构化参数,并在非思考模式和思考模式下分别工作。在那之后退休日期,这些ID将失效。通过更改迁移 tool_calls,当您设置时,会在服务器端针对JSON Schema进行验证。使用JSON模式进行单次提取;使用 strict: true对于代理、枚举或任何需要类型签名的场景。 函数调用 是的,直到

我可以使用JSON模式与旧版deepseek-chat模型ID吗?

字符串到 2026-07-24 at 15:59 UTC. deepseek-chat and deepseek-reasoner currently route to deepseek-v4-flash 在非思考模式和思考模式下分别,JSON模式适用于两种路由。在那之后退休日期,这些ID将失效。通过更改迁移 model OpenAI兼容性说明 deepseek-v4-flash or deepseek-v4-pro — the 覆盖了一行交换。 你触发了

为什么我的DeepSeek JSON响应会被截断?

限制。API在字符串中间停止生成,这会产生无效的JSON。检查 max_tokens ——如果它等于 finish_reason — if it equals "length", raise max_tokens 并重试。V4支持高达384,000个输出令牌,因此您有足够的余量。在发送前,使用[1]准确设置提示的大小。 DeepSeek token counter 使用[1]在发送前准确设置提示的大小。

来源s & Methodology

Last source check: April 30, 2026

Primary sources

Methodology

Pricing figures were checked against the 官方DeepSeek定价页面 and normalised into estimated monthly costs using sample token usage scenarios. Actual costs may vary depending on caching, input/output ratio, regional availability, and provider updates.

Data confidence

High — figures checked directly against the official pricing page on the review date.

Editorial note

DeepSeek occasionally runs promotional discounts that are not always reflected in the headline page. The pricing dataset on this site auto-refreshes monthly; this article reflects the dataset on the date shown above.