Skip to content

JSON 模式指南

JSON 模式是 DeepSeek API 的一项强大功能,可以强制模型输出有效的 JSON 格式数据,确保结构化输出的一致性和可靠性。

概述

JSON 模式功能允许您:

  • 强制模型输出有效的 JSON 格式
  • 确保数据结构的一致性
  • 简化后续的数据处理流程
  • 提高应用程序的可靠性

基本用法

启用 JSON 模式

python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DEEPSEEK_API_KEY"),
    base_url="https://api.deepseek.com"
)

response = client.chat.completions.create(
    model="deepseek-chat",
    messages=[
        {
            "role": "user", 
            "content": "生成一个包含姓名、年龄、职业的人物信息"
        }
    ],
    response_format={"type": "json_object"},  # 启用 JSON 模式
    max_tokens=200
)

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

输出示例

json
{
    "name": "张三",
    "age": 28,
    "profession": "软件工程师"
}

高级用法

1. 指定 JSON 结构

python
response = client.chat.completions.create(
    model="deepseek-chat",
    messages=[
        {
            "role": "user",
            "content": """
            生成一个用户配置文件,包含以下字段:
            - name: 用户姓名
            - email: 邮箱地址
            - preferences: 偏好设置对象,包含 theme 和 language
            - created_at: 创建时间(ISO格式)
            """
        }
    ],
    response_format={"type": "json_object"},
    max_tokens=300
)

输出示例

json
{
    "name": "李四",
    "email": "lisi@example.com",
    "preferences": {
        "theme": "dark",
        "language": "zh-CN"
    },
    "created_at": "2025-01-27T10:30:00Z"
}

2. 复杂数据结构

python
response = client.chat.completions.create(
    model="deepseek-chat",
    messages=[
        {
            "role": "user",
            "content": """
            生成一个产品目录,包含3个产品,每个产品包含:
            - id: 产品ID
            - name: 产品名称
            - price: 价格
            - tags: 标签数组
            - specifications: 规格对象
            """
        }
    ],
    response_format={"type": "json_object"},
    max_tokens=800
)

输出示例

json
{
    "products": [
        {
            "id": "P001",
            "name": "智能手机",
            "price": 2999.99,
            "tags": ["电子产品", "通讯", "智能设备"],
            "specifications": {
                "screen_size": "6.1英寸",
                "storage": "128GB",
                "color": "黑色"
            }
        },
        {
            "id": "P002",
            "name": "无线耳机",
            "price": 299.99,
            "tags": ["音频", "无线", "便携"],
            "specifications": {
                "battery_life": "24小时",
                "connectivity": "蓝牙5.0",
                "color": "白色"
            }
        },
        {
            "id": "P003",
            "name": "智能手表",
            "price": 1299.99,
            "tags": ["可穿戴", "健康", "智能"],
            "specifications": {
                "display": "AMOLED",
                "battery_life": "7天",
                "water_resistance": "50米"
            }
        }
    ]
}

实际应用场景

1. 数据提取和转换

python
def extract_contact_info(text):
    response = client.chat.completions.create(
        model="deepseek-chat",
        messages=[
            {
                "role": "user",
                "content": f"""
                从以下文本中提取联系信息,以JSON格式返回:
                
                {text}
                
                请提取:name, phone, email, address
                """
            }
        ],
        response_format={"type": "json_object"},
        max_tokens=300
    )
    
    return json.loads(response.choices[0].message.content)

# 使用示例
text = "我是王五,电话是13812345678,邮箱wangwu@email.com,住址是北京市朝阳区"
contact_info = extract_contact_info(text)
print(contact_info)

2. 配置文件生成

python
def generate_app_config(requirements):
    response = client.chat.completions.create(
        model="deepseek-chat",
        messages=[
            {
                "role": "user",
                "content": f"""
                根据以下需求生成应用配置文件:
                {requirements}
                
                配置应包含:
                - database: 数据库配置
                - server: 服务器配置
                - features: 功能开关
                - logging: 日志配置
                """
            }
        ],
        response_format={"type": "json_object"},
        max_tokens=500
    )
    
    return json.loads(response.choices[0].message.content)

3. API 响应格式化

python
def format_api_response(data, format_spec):
    response = client.chat.completions.create(
        model="deepseek-chat",
        messages=[
            {
                "role": "user",
                "content": f"""
                将以下数据按照指定格式转换为JSON:
                
                数据:{data}
                格式要求:{format_spec}
                """
            }
        ],
        response_format={"type": "json_object"},
        max_tokens=400
    )
    
    return json.loads(response.choices[0].message.content)

最佳实践

1. 明确指定结构

在提示中明确说明期望的 JSON 结构:

python
prompt = """
请生成用户信息,JSON格式如下:
{
    "user": {
        "id": "用户ID",
        "profile": {
            "name": "姓名",
            "age": 年龄数字,
            "skills": ["技能1", "技能2"]
        },
        "metadata": {
            "created": "ISO时间格式",
            "active": 布尔值
        }
    }
}
"""

2. 处理嵌套对象

python
response = client.chat.completions.create(
    model="deepseek-chat",
    messages=[
        {
            "role": "user",
            "content": """
            生成一个订单信息,包含:
            - 订单基本信息(ID、日期、状态)
            - 客户信息(姓名、联系方式)
            - 商品列表(每个商品包含名称、数量、价格)
            - 总计信息(小计、税费、总额)
            """
        }
    ],
    response_format={"type": "json_object"},
    max_tokens=600
)

3. 数组和列表处理

python
response = client.chat.completions.create(
    model="deepseek-chat",
    messages=[
        {
            "role": "user",
            "content": """
            生成一个课程表,包含一周的课程安排:
            - 每天包含多个课程
            - 每个课程包含:时间、科目、教师、教室
            - 以JSON数组格式返回
            """
        }
    ],
    response_format={"type": "json_object"},
    max_tokens=800
)

错误处理

1. 验证 JSON 格式

python
import json

def safe_json_parse(response_content):
    try:
        return json.loads(response_content)
    except json.JSONDecodeError as e:
        print(f"JSON 解析错误: {e}")
        return None

# 使用示例
response = client.chat.completions.create(
    model="deepseek-chat",
    messages=[{"role": "user", "content": "生成用户信息"}],
    response_format={"type": "json_object"}
)

data = safe_json_parse(response.choices[0].message.content)
if data:
    print("解析成功:", data)
else:
    print("解析失败")

2. 结构验证

python
def validate_user_data(data):
    required_fields = ["name", "email", "age"]
    
    if not isinstance(data, dict):
        return False, "数据不是字典格式"
    
    for field in required_fields:
        if field not in data:
            return False, f"缺少必需字段: {field}"
    
    if not isinstance(data["age"], int):
        return False, "年龄必须是整数"
    
    return True, "验证通过"

# 使用示例
is_valid, message = validate_user_data(parsed_data)
if not is_valid:
    print(f"数据验证失败: {message}")

性能优化

1. 减少 Token 使用

python
# 简洁的提示
response = client.chat.completions.create(
    model="deepseek-chat",
    messages=[
        {
            "role": "user",
            "content": "JSON格式返回:姓名、年龄、城市"
        }
    ],
    response_format={"type": "json_object"},
    max_tokens=100  # 限制输出长度
)

2. 批量处理

python
def batch_json_generation(items):
    prompt = f"""
    为以下{len(items)}个项目生成JSON数据:
    {items}
    
    返回格式:{{"items": [...]}}
    """
    
    response = client.chat.completions.create(
        model="deepseek-chat",
        messages=[{"role": "user", "content": prompt}],
        response_format={"type": "json_object"},
        max_tokens=1000
    )
    
    return json.loads(response.choices[0].message.content)

常见问题

Q: JSON 模式是否支持所有数据类型?

A: 支持标准 JSON 数据类型:字符串、数字、布尔值、数组、对象和 null。

Q: 如何处理大型 JSON 输出?

A: 可以增加 max_tokens 参数,或者将大型结构分解为多个较小的请求。

Q: JSON 模式是否保证输出格式正确?

A: JSON 模式会尽力确保输出有效的 JSON,但建议在应用中添加验证逻辑。

Q: 可以指定 JSON Schema 吗?

A: 目前不直接支持 JSON Schema,但可以在提示中详细描述期望的结构。

相关资源


最后更新: 2025年1月27日

基于 DeepSeek AI 大模型技术