JSON Mode 概述
DeepSeek V4 Flash 和 Pro 均支持 JSON Mode,通过设置 response_format 参数,可以强制模型输出严格符合 JSON Schema 的结构化数据。这在数据提取、API 响应、自动化工作流等场景中至关重要。
基础用法
from openai import OpenAI
import os
client = OpenAI(
api_key=os.environ.get('DEEPSEEK_API_KEY'),
base_url='https://api.deepseek.com'
)
response = client.chat.completions.create(
model='deepseek-v4-flash',
messages=[{
"role": "system",
"content": "你是一个信息提取助手,从文本中提取结构化信息。"
}, {
"role": "user",
"content": "张三,28岁,软件工程师,base北京,月薪35000"
}],
response_format={
"type": "json_schema",
"json_schema": {
"name": "person_info",
"strict": True,
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
"job": {"type": "string"},
"city": {"type": "string"},
"salary": {"type": "number"}
},
"required": ["name", "age", "job", "city", "salary"],
"additionalProperties": False
}
}
}
)
import json
result = json.loads(response.choices[0].message.content)
print(result)
# {'name': '张三', 'age': 28, 'job': '软件工程师', 'city': '北京', 'salary': 35000}strict 模式详解
设置 "strict": true 后,DeepSeek 保证:
- 输出一定是合法的 JSON
- 所有 required 字段必定存在
- 不会出现 additionalProperties 之外的字段
- 字段类型严格匹配 Schema 定义
使用 strict 模式时需要注意:Schema 中的对象类型必须包含 additionalProperties: false,且所有属性必须定义在 required 中。
复杂嵌套 Schema
{
"type": "json_schema",
"json_schema": {
"name": "code_review",
"strict": True,
"schema": {
"type": "object",
"properties": {
"overall_score": {"type": "number", "minimum": 0, "maximum": 100},
"issues": {
"type": "array",
"items": {
"type": "object",
"properties": {
"file": {"type": "string"},
"line": {"type": "integer"},
"severity": {"type": "string", "enum": ["critical", "major", "minor"]},
"description": {"type": "string"},
"suggestion": {"type": "string"}
},
"required": ["file", "severity", "description", "suggestion"],
"additionalProperties": False
}
},
"summary": {"type": "string"}
},
"required": ["overall_score", "issues", "summary"],
"additionalProperties": False
}
}
}Pydantic 集成
将 Pydantic 模型自动转换为 JSON Schema,实现端到端类型安全:
from pydantic import BaseModel, Field
from typing import List, Optional
class Issue(BaseModel):
file: str
line: int
severity: str = Field(pattern="^(critical|major|minor)$")
description: str
suggestion: str
class CodeReview(BaseModel):
overall_score: int = Field(ge=0, le=100)
issues: List[Issue]
summary: str
# 自动生成 Schema
schema = CodeReview.model_json_schema()
# 发送请求时使用
response = client.chat.completions.create(
model='deepseek-v4-pro',
messages=[{"role": "user", "content": f"Review this code:\n{code}"}],
response_format={
"type": "json_schema",
"json_schema": {
"name": "code_review",
"strict": True,
"schema": schema
}
}
)
# 直接反序列化为 Pydantic 模型
review = CodeReview.model_validate_json(response.choices[0].message.content)生产环境最佳实践
- System Prompt 配合:在 system prompt 中说明输出格式和字段含义
- 始终使用 strict:生产环境必须启用 strict=true,避免格式异常
- 验证层:即使使用 strict,也要在代码中再次验证(防御性编程)
- Fallback 处理:如果 JSON 解析失败,记录原始输出并通知开发者
- enum 约束:对有限选项的字段使用 enum,保证值合法