Overview of JSON Mode

Both DeepSeek V4 Flash and Pro support JSON Mode. By setting the response_format parameter, you can force the model to output structured data that strictly conforms to a JSON Schema. This is crucial in scenarios such as data extraction, API responses, and automated workflows.

Basic Usage

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": "You are an information extraction assistant. Extract structured information from text."
    }, {
        "role": "user",
        "content": "Zhang San, 28 years old, software engineer, based in Beijing, monthly salary 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': 'Zhang San', 'age': 28, 'job': 'software engineer', 'city': 'Beijing', 'salary': 35000}

Detailed Explanation of strict Mode

When "strict": true is set, DeepSeek guarantees:

  • The output is always valid JSON.
  • All required fields are always present.
  • No fields outside additionalProperties will appear.
  • Field types strictly match the Schema definition.

When using strict mode, note that object types in the Schema must include additionalProperties: false, and all properties must be defined in required.

Complex Nested 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 Integration

Automatically convert Pydantic models to JSON Schema for end-to-end type safety:

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

# Automatically generate Schema
schema = CodeReview.model_json_schema()

# Use when sending the request
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
        }
    }
)

# Directly deserialize into a Pydantic model
review = CodeReview.model_validate_json(response.choices[0].message.content)

Best Practices for Production

  • System Prompt Coordination: Explain the output format and field meanings in the system prompt.
  • Always Use strict: In production, strict=true must be enabled to avoid format anomalies.
  • Validation Layer: Even with strict, validate again in code (defensive programming).
  • Fallback Handling: If JSON parsing fails, log the raw output and notify developers.
  • enum Constraints: Use enum for fields with limited options to ensure valid values.