BigModel structured output: return JSON and validate its fields
Set response_format to json_object, describe the fields in the system message, then parse with json.loads and validate with jsonschema. No API call was made here.
Task and deliverable · Prepare the input and environment · How the parameters work
At a glance
The Zhipu open platform (BigModel) "结构化输出" page splits the job into three steps: open JSON mode with response_format={"type": "json_object"}, use a model that supports structured output, and define the expected JSON structure and field requirements in the system message. The page then shows parsing and validation: json.loads on message.content, jsonschema validate on the fields, and two separate exception branches. This tutorial follows that order through one complete task, turning a ticket description into a fixed set of fields and validating it, and marks clearly what the page does not state. Passages marked editorial are this site's checking practice, not vendor-defined behavior. No API was called in this batch, and none of the sample code was executed.
From JSON mode to field validation
Open JSON mode with response_format
The page is direct about
response_format: set it to{"type": "json_object"}to enable JSON mode. Its boundary matters, because the page itself only claims it "确保 AI 返回符合预定义格式的 JSON 数据". A JSON object is guaranteed, the field structure is not. Reading the whole fetched page body,json_objectis the only value used and nojson_schemaorstrictform appears, so this article does not assume either is available.Describe the field shape in the system message
The third core parameter on the page is
messages: define the expected JSON structure and field requirements in the system message. The full sample puts a five-field JSON template straight into system, while the "Schema 验证" section switches tojson.dumps(schema, indent=2, ensure_ascii=False)and embeds theschemaverbatim. Both share one idea: the same structure description serves as the prompt and, in the second form, as the validator. The page's practical advice adds that detailed descriptions and examples for key fields help the model produce conforming JSON.Send the request with zai-sdk
The install step is
pip install zai-sdk, with a pinned alternativepip install zai-sdk==0.2.3, verified by printingzai.__version__afterimport zai. The client isfrom zai import ZhipuAiClient, constructed asZhipuAiClient(api_key="YOUR_API_KEY"), and the call isclient.chat.completions.create(...), with every sample on the page usingmodelset toglm-5.2. The page gives nobase_urland no HTTP endpoint path, so this article ships no curl version and claims no REST address.Parse, validate, branch
The "Schema 验证" section chains two steps:
json.loads(response.choices[0].message.content)and thenvalidate(instance=result, schema=schema), catchingjsonschema.exceptions.ValidationError("JSON 验证失败", return None) andjson.JSONDecodeError("JSON 解析失败", return None) separately. The order is worth copying: unparsable output and wrong fields are different failures, and one shared except block leaves you unable to tell a non-JSON answer from a JSON answer with the wrong shape.Exits and boundaries
The page defines no retry count, truncation behavior, concurrency limit or billing rule, and says nothing about combining streaming with JSON mode; this article fills none of those gaps. The editorial exit is: parse succeeds, required fields are present, types and enums match the schema, and a human confirms the summary against the source text. All four must pass before delivery. If any fails, keep the raw
contentand the exception, and mark the attempt undelivered.
Task and deliverable
The task is to turn unstructured text into JSON with fixed fields, and to know for certain whether this particular JSON is usable. The page answers in three layers: response_format={"type": "json_object"} opens JSON mode, the system message describes the structure, and json.loads plus jsonschema.validate settle it. The deliverable is a dict that passes schema validation, not a string that looks like JSON. The example extracts ticket_id, priority, needs_human, keywords and summary from a ticket, with an enum for priority and a boolean for needs_human, which covers the enum, boolean, array and required constraints that appear in the page's own schema sample.
Prepare the input and environment
- A BigModel API key in an environment variable (the sample here uses
BIGMODEL_API_KEY). The page only writesapi_key="YOUR_API_KEY"and does not explain key creation, quota or rate limits, so this article leaves those out. - A Python environment with
zai-sdk: the page givespip install zai-sdkorpip install zai-sdk==0.2.3, verified withimport zaiandzai.__version__. - The
jsonschemapackage: the validation sample doesimport jsonschemaandfrom jsonschema import validate, but the install section only listszai-sdk. Installing it is on you (an editorial addition, since the page gives no such command). - Text to extract from, and an explicit field expectation. The page stresses input quality: "请确保输入数据的质量和格式" for the best extraction result.
- A model ID you have confirmed supports structured output; every page sample uses
glm-5.2, so this article follows it.
How the parameters work
Division of labor: the page defines response_format as the response-format switch ({"type": "json_object"}), model as "使用支持结构化输出的模型", and messages as the place to define the expected JSON structure and field requirements. That division admits JSON mode carries no structure of its own: the prompt describes it and your code validates it. The switch being on and the fields being right are two different guarantees.
SDK and call shape: after installing zai-sdk you construct a ZhipuAiClient and call client.chat.completions.create(...) with model, messages and response_format. The samples read response.choices[0].message.content and hand it straight to json.loads, which means that in JSON mode content holds JSON text rather than an object. The page shows no raw HTTP request or response body, and no base_url.
Two-stage validation: the "Schema 验证" section parses first and validates second, with two exception branches, ValidationError and JSONDecodeError, both printing a message and returning None. The page frames it as sentiment analysis with validation; this article treats it as the general landing pattern. The practical-advice section also names "多层验证:Schema 验证 + 业务逻辑验证" and "降级方案:准备简化的备用 Schema", but gives strategy without code.
The page's own caveat: JSON mode "要求 AI 严格按照指定格式输出,但在某些复杂场景下可能影响回答的自然性", and it suggests balancing function against user experience, starting from simple schemas and adding complexity gradually. That admission is your basis for deciding how strict a schema should be.
Fields and requirements
| Field or object | Page requirement or practice | Symptom when it breaks |
|---|---|---|
response_format | Set to {"type": "json_object"} to enable JSON mode | The page never says what differs without it; it is presented only as the switch |
model | "使用支持结构化输出的模型"; every sample writes glm-5.2 | No supported-model list on the page, so another model cannot be confirmed from it |
messages | Define the expected JSON structure and fields in the system message; the second sample dumps the schema into system | A vague description yields different fields, and only validation catches it |
choices[0].message.content | Treated as a string and passed to json.loads | Non-JSON text raises json.JSONDecodeError |
| JSON Schema | type, properties, enum, minimum, maximum, required | Mismatch raises jsonschema.exceptions.ValidationError |
| Error handling | Two exception branches, each printing a reason and returning None | A single except hides whether JSON or its fields were wrong |
Complete the task
Install and set the key: run pip install zai-sdk, add jsonschema, and put the key in BIGMODEL_API_KEY. The sample reads it with os.environ, so a missing variable fails at client construction or the first call, which is easier to diagnose than sending an empty key.
Write the schema before the prompt: fix fields, types, enums and required keys first, because the schema does two jobs later, describing the answer in the system message and validating the answer afterwards. In the sample priority is an enum of high/normal/low, needs_human is boolean, keywords is an array of strings, and required lists four fields while leaving keywords optional on purpose, so a missing optional field does not fail the whole run, which also matches the page's advice to start simple.
Send the request: client.chat.completions.create(model="glm-5.2", messages=[system, user], response_format={"type": "json_object"}), with json.dumps(schema, indent=2, ensure_ascii=False) and a short task line in system and the raw text in user. The page dumps the schema into system with an f-string; this article does the same with a shorter instruction.
Parse and validate: json.loads(raw) first, then validate(instance=result, schema=schema), with separate exception branches. A parse failure means the answer was not JSON; a validation failure means the JSON exists but the fields or types are wrong. In both cases do not pass a half-built object downstream; the page's samples return None.
Confirm meaning by hand (editorial recommendation): schema constrains shape, not content. Read back against the source and check that summary invents nothing, that priority matches the urgency in the text, and that keywords are words that actually appear. The page defines no such semantic check; this one is this site's addition.
Choose an exit and clean up (editorial recommendation): only hand the dict downstream when everything passed; otherwise keep the raw content fragment and the exception, delete any sensitive text printed during the attempt, and never write unvalidated output to a database. The page sets no retry policy, so this article fixes no retry count, but it does set one rule: after two consecutive validation failures on the same schema, simplify the schema instead of retrying.
Worked example
Sample input is a Chinese support ticket: "工单 A-1043:客户反馈登录页在 Safari 下白屏,影响全体用户,请立刻处理。" The expected output is a five-field JSON object where priority is restricted to one of three enum values. The bash excerpt is the install step (the jsonschema line is an editorial addition), the python excerpt is a full script in the page's shape, and the JSON excerpt shows the expected parsed result. It is not page output, since the page never shows a raw response body.
pip install zai-sdk
pip install jsonschema
python -c 'import zai; print(zai.__version__)'
import json
import os
import jsonschema
from jsonschema import validate
from zai import ZhipuAiClient
client = ZhipuAiClient(api_key=os.environ['BIGMODEL_API_KEY'])
schema = {
'type': 'object',
'properties': {
'ticket_id': {'type': 'string'},
'priority': {'type': 'string', 'enum': ['high', 'normal', 'low']},
'needs_human': {'type': 'boolean'},
'keywords': {'type': 'array', 'items': {'type': 'string'}},
'summary': {'type': 'string'},
},
'required': ['ticket_id', 'priority', 'needs_human', 'summary'],
}
system = (
'你是一个工单信息提取器,只返回 JSON,字段与类型如下:\n'
+ json.dumps(schema, indent=2, ensure_ascii=False)
)
response = client.chat.completions.create(
model='glm-5.2',
messages=[
{'role': 'system', 'content': system},
{'role': 'user', 'content': '工单 A-1043:客户反馈登录页在 Safari 下白屏,影响全体用户,请立刻处理。'},
],
response_format={'type': 'json_object'},
)
raw = response.choices[0].message.content
try:
result = json.loads(raw)
validate(instance=result, schema=schema)
except json.JSONDecodeError as error:
print('JSON 解析失败:', error)
except jsonschema.exceptions.ValidationError as error:
print('字段校验失败:', error.message)
else:
print(result['priority'], result['needs_human'])
{
"ticket_id": "A-1043",
"priority": "high",
"needs_human": true,
"keywords": ["登录页", "Safari", "白屏"],
"summary": "登录页在 Safari 下白屏,影响全体用户,需要人工跟进。"
}
What to check afterwards: whether raw is a string starting with {; whether json.loads passes; whether validate passes; whether priority falls inside the three enum values; and whether needs_human is a real boolean rather than the string "true". That last one is the classic type trap, since JSON true and "true" both survive json.loads and only the schema's boolean constraint rejects the string.
Check the result and failure paths
- Success (editorial rule):
contentparses into an object, required fields are present, types and enums match the schema,validateraises nothing, and a human confirms the summary against the source. The page only covers parse plus validate; the semantic check is an editorial addition. - Parse failure:
json.JSONDecodeError. Following the page sample, print "JSON 解析失败" and return None; do not re-parse the same response hoping it heals, and first keep the raw text to see whether extra prose wrapped it. - Wrong fields:
jsonschema.exceptions.ValidationError. Following the page sample, print "JSON 验证失败" and return None; the editorial addition is to also recorderror.messageand the failing field path so you can tell a model problem from an over-strict schema. - Risk of direct indexing: the page's full sample reads
result["sentiment"],result["confidence"]and so on, which raises KeyError when a field is missing, while its exception branches cover only parse errors and schema violations. That is a gap between the page's code and its error handling; this article records it and tells you to validate before indexing. - Suspected truncation: the page never describes truncation behavior, an end marker, or the effect of
max_tokensin JSON mode. Ifcontentis half a JSON document the outcome is aJSONDecodeError, so treat it as undelivered and do not try to repair the string. - Stopping and rollback (editorial recommendation): after two consecutive validation failures on one schema, simplify the structure or relax the enum as the page suggests; if it still fails, stop that model path, keep the evidence, and never write unvalidated output downstream.
Scope and limits
- The page shows only the SDK call (
client.chat.completions.create); it gives nobase_urland no HTTP endpoint path. This article therefore ships no curl version and claims no REST address. - The page has no list of models that support structured output; it only says "使用支持结构化输出的模型" and uses
glm-5.2throughout. Whether another model supports it cannot be confirmed from this page. - The page says nothing about combining JSON mode with streaming, retry policy, concurrency limits, timeouts or billing, and this article fills none of those gaps.
- The "数据提取和结构化完整实现" sample contains
json.loads(response.choices[0].message.content)["properties"]and then validates with the rootschemaviavalidate(instance=result, schema=schema); taking thepropertiessub-object and validating it as the root object do not line up. This article records the page as written, does not correct it, and does not recommend copying that block. - The page warns that JSON mode can affect how natural an answer reads and that complex schemas may be followed less reliably; that is an admission of cost, not a promise of success rate.
No BigModel API, model or code excerpt was run, installed or called in this batch, and no account, login state, key validity or billing was checked. Every fact comes from the single official "结构化输出" page. The sample script is an editorial completion in the page's request and validation shape; what glm-5.2 actually returns, how it truncates and which error codes it emits were not verified, so you need one real response in your own environment to judge.
Article sources
Original editorial content; official descriptions and checking suggestions are distinguished.