Structured output
Set response_format to get valid JSON back from the model.
JSON schema
With json_schema, the output is constrained to the schema you pass:
response = client.chat.completions.create(
model="moonshotai/kimi-k3.1-pro",
messages=[{"role": "user", "content": "Extract: Ada Lovelace, born 1815 in London."}],
response_format={
"type": "json_schema",
"json_schema": {
"name": "person",
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"born": {"type": "integer"},
"city": {"type": "string"},
},
"required": ["name", "born", "city"],
"additionalProperties": False,
},
},
},
)
response.choices[0].message.content is a JSON string you can parse as is.
JSON mode
If you only need valid JSON without a fixed schema, use {"type": "json_object"} and describe the shape you want in the prompt.
Supported schema keywords
Schemas can use type, properties, required, additionalProperties, items, enum, const, anyOf, minItems, maxItems, minLength, maxLength, pattern, minimum and maximum, plus $defs with $ref. A schema that uses an unsupported keyword returns 400.
Tips
- Keep schemas small and flat. The model fills deeply nested optional fields less reliably.
- Set
max_tokenshigh enough for the full object. Output cut off at the limit is incomplete JSON and won’t parse, so check thatfinish_reasonisstop.