DeepSeek API
快速开始
首次调用 API
模型 & 价格
Temperature 设置
Token 用量计算
限速
错误码
API文档
基本信息
对话补全
POST
FIM 补全(Beta)
POST
列出模型
GET
查询余额
GET
API指南
推理模型 (deepseek-reasoner)
多轮对话
对话前缀续写(Beta)
FIM 补全(Beta)
JSON Output
Function Calling
上下文硬盘缓存
提示库
代码改写
代码解释
代码生成
内容分类
结构化输出
角色扮演(自定义人设)
角色扮演(情景续写)
散文写作
诗歌创作
文案大纲生成
宣传标语生成
模型提示词生成
中英翻译专家
常见问题
JSON Output
创建时间: 2025-05-29 17:10

在很多场景下,用户需要让模型严格按照 JSON 格式来输出,以实现输出的结构化,便于后续逻辑进行解析。

DeepSeek 提供了 JSON Output 功能,来确保模型输出合法的 JSON 字符串。

注意事项

  1. 设置 response_format 参数为 {'type': 'json_object'}
  2. 用户传入的 system 或 user prompt 中必须含有 json 字样,并给出希望模型输出的 JSON 格式的样例,以指导模型来输出合法 JSON。
  3. 需要合理设置 max_tokens 参数,防止 JSON 字符串被中途截断。
  4. 在使用 JSON Output 功能时,API 有概率会返回空的 content。我们正在积极优化该问题,您可以尝试修改 prompt 以缓解此类问题。

样例代码

这里展示了使用 JSON Output 功能的完整 Python 代码:

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."

messages = [{"role": "system", "content": system_prompt},
            {"role": "user", "content": user_prompt}]

response = client.chat.completions.create(
    model="deepseek-chat",
    messages=messages,
    response_format={
        'type': 'json_object'
    }
)

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

模型将会输出:

{
    "question": "Which is the longest river in the world?",
    "answer": "The Nile River"
}
最后更新: -