指南
JSON 输出
用 response_format 让 DeepSeek 返回 JSON,并在提示词中描述你想要的结构。务必先解析并检查回复,再信任它。
核对于 2026年10月26日
请求 JSON
import json
import os
from openai import OpenAI
client = OpenAI(
base_url="https://nokeep.ai/v1",
api_key=os.environ["NOKEEP_API_KEY"],
)
reply = client.chat.completions.create(
model="deepseek-v4.1-flash-uncensored",
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": 'Answer as JSON: {"title": string, "tags": string[]}'},
{"role": "user", "content": "A short story about a lighthouse keeper's last night."},
],
)
data = json.loads(reply.choices[0].message.content)
print(data["title"], data["tags"])response_format 会原样传给 DeepSeek,包括 json_schema。同时也请在提示词中描述结构:模型读取的正是提示词。
使用 GLM 时
glm-5.3-flash-uncensored 不支持 response_format;该字段会被丢弃,并在 x-nokeep-ignored 中列出。请在系统消息中要求输出 JSON,解析回复的方式相同。
检查返回结果
- 用
json.loads或JSON.parse放在 try 中解析;遇到解析错误时重试一次。 - 检查你需要的字段是否存在,类型是否正确。Pydantic 或 Zod 等 schema 校验工具一行代码即可完成。
- 给回复留出足够空间:
max_tokens设得太小,JSON 会在闭合前被截断。