结构化输出
结构化输出(JSON 模式)让模型按照指定的 JSON 格式生成响应,确保输出可控、可解析。适用于数据提取、表单填充、分类标签输出、API 响应格式化等需要结构化数据的场景。
支持的模型
当前支持 mimo-v2.6-flash,mimo-v2.6-pro,mimo-v2.6-pro-ultraspeed,mimo-v2.5-pro 和 mimo-v2.5 模型。
请求参数
-
response_format:响应格式控制参数,传入{"type": "json_object"}开启 JSON 模式输出能力。 -
messages:需在系统消息或用户消息中明确告知模型:要求只返回 JSON 并且完整定义返回 JSON 的字段、层级、数据类型,附带示例更佳。
注意合理规划 max_completion_tokens 的值。设置过小可能导致输出被截断,JSON 不完整无法解析。
调用示例
基础调用
import os
import json
from openai import OpenAI
client = OpenAI(
api_key=os.environ.get("MIMO_API_KEY"),
base_url="https://api.xiaomimimo.com/v1"
)
completion = client.chat.completions.create(
model="mimo-v2.6-pro",
messages=[
{
"role": "system",
"content": "You are MiMo, an AI assistant developed by Xiaomi. Today is date: Tuesday, December 16, 2025. Your knowledge cutoff date is December 2024.\nDo not add any explanations outside JSON. Parse meeting information and return nested structured JSON: {\"meeting_meta\": {\"meeting_topic\": string | null, \"start_time\": string | null, \"participants\": array<string>}, \"action_items\": [{\"task\": string, \"responsible_person\": string, \"deadline\": string}]}\nFill null for unknown fields."
},
{
"role": "user",
"content": "Product iteration meeting at 14:00 tomorrow. Attendees: Li Ming, Wang Hua. Task: Complete API document revision by Friday, taken by Wang Hua."
}
],
response_format={
"type": "json_object"
}
)
result = completion.choices[0].message.content
try:
parsed_json_data = json.loads(result)
print(json.dumps(parsed_json_data, indent=4, ensure_ascii=False))
except json.JSONDecodeError as e:
print(f"JSON parsing failed: {str(e)}")
print(f"Raw complete content: {result}")
响应示例
{
"id": "d7bbc231-ed6a-4884-a9e4-d7caff96cf25_c37a9ce97e9542079b9d948b07c10209",
"choices": [
{
"finish_reason": "stop",
"index": 0,
"message": {
"content": "{\"meeting_meta\": {\"meeting_topic\": \"Product iteration meeting\", \"start_time\": \"2025-12-17 14:00\", \"participants\": [\"Li Ming\", \"Wang Hua\"]}, \"action_items\": [{\"task\": \"Complete API document revision\", \"responsible_person\": \"Wang Hua\", \"deadline\": \"2025-12-19\"}]}",
"role": "assistant",
"tool_calls": null,
"reasoning_content": "The user wants me to parse meeting information and return structured JSON.\n\nMeeting: Product iteration meeting\nTime: 14:00 tomorrow\nParticipants: Li Ming, Wang Hua\nTask: Complete API document revision by Friday, responsible: Wang Hua\n\nI need to fill unknown fields with null. Today's date is Tuesday, December 16, 2025, so tomorrow is December 17, 2025. But I should probably just put what was given: \"14:00 tomorrow\" — I could interpret it. The instruction says to fill null for unknown fields. \"Tomorrow\" relative to today (2025-12-16) is 2025-12-17. I'll provide \"2025-12-17 14:00\" as start_time. Actually, the user message just says \"at 14:00 tomorrow\" — it's reasonable to resolve it. Friday relative to 2025-12-17 would be 2025-12-19. I'll provide that.\n\nI'll return JSON only, no explanations outside JSON."
}
}
],
"created": 1790008400,
"model": "mimo-v2.6-pro",
"object": "chat.completion",
"usage": {
"completion_tokens": 344,
"prompt_tokens": 161,
"total_tokens": 505,
"completion_tokens_details": {
"reasoning_tokens": 253
},
"prompt_tokens_details": {
"cached_tokens": 0
}
}
}
流式输出
流式模式下,模型增量输出 JSON 内容。需在客户端拼接完整的 JSON 字符串后再解析,避免截断导致解析失败。
import os
import json
from openai import OpenAI
client = OpenAI(
api_key=os.environ.get("MIMO_API_KEY"),
base_url="https://api.xiaomimimo.com/v1"
)
completion = client.chat.completions.create(
model="mimo-v2.6-pro",
messages=[
{
"role": "system",
"content": "You are MiMo, an AI assistant developed by Xiaomi. Today is date: Tuesday, December 16, 2025. Your knowledge cutoff date is December 2024.\nReturn only compact JSON without any extra explanations. Use the specified format: {\"destination\": string, \"trip_days\": number, \"core_activity\": array<string>, \"budget_level\": \"low\"|\"mid\"|\"high\"}"
},
{
"role": "user",
"content": "Plan a 3-day city trip focusing on museums and local food with a moderate budget."
}
],
response_format={
"type": "json_object"
},
stream=True
)
full_json_content = ""
for chunk in completion:
if not chunk.choices:
continue
message_delta = chunk.choices[0].delta
if message_delta.content:
full_json_content += message_delta.content
try:
parsed_json_data = json.loads(full_json_content)
print(json.dumps(parsed_json_data, indent=4, ensure_ascii=False))
except json.JSONDecodeError as e:
print(f"JSON parsing failed: {str(e)}")
print(f"Raw complete content: {full_json_content}")
响应示例(流式响应拼接结果)
{
"destination": "Lisbon, Portugal",
"trip_days": 3,
"core_activity": [
"Visit the National Museum of Ancient Art",
"Explore the MAAT and Belém cultural district",
"Wander the Calouste Gulbenkian Museum",
"Taste pastéis de nata at Pastéis de Belém",
"Sample petiscos and seafood at Time Out Market",
"Try bacalhau and bifana in local tascas",
"Walk through Alfama with fado dinner"
],
"budget_level": "mid"
}
如何获得准确的 JSON 输出
json_object 模式仅能保证输出语法合法的 JSON,最终返回的数据结构完全由提示词定义。提示词定义越清晰、约束越完整,模型无需自主推测,输出的 JSON 结构就越贴合预期。
1. 强制仅输出 JSON
明确要求「只返回 JSON,不附带任何解释、注释、Markdown 代码块」,防止多余文本导致解析报错。
2. 提供完整 JSON 结构模板
完整列出所有字段、数据类型、嵌套层级,搭配示例更易约束模型:
{
"name": string,
"count": number,
"tags": string[],
"date": "YYYY-MM-DD"
}
3. 限定枚举值与数值范围
-
固定选项可用枚举标注:
"status": "active" | "inactive" | "pending" -
数值限定区间:
score: number (0-100)
4. 约定空值处理规则
提前说明未知信息统一填充 null,例如提示词写明:未知字段请填充 null。
5. 确保 JSON 输出可靠
开启 json_object 模式仅能保障输出语法合法的 JSON,无法约束返回字段、数据类型与预设结构完全匹配。线上生产环境推荐搭配 jsonschema 库对模型输出进行强制结构校验;若校验不通过,可执行重试强化提示词、业务降级等兜底逻辑。
下方提供了一个 Python 示例,示例场景:解析客服对话文本,自动抽取工单核心信息,实现工单自动分类、紧急等级划分与智能派单。
import json
import os
from jsonschema import validate, ValidationError
from openai import OpenAI
client = OpenAI(
api_key=os.environ.get("MIMO_API_KEY"),
base_url="https://api.xiaomimimo.com/v1"
)
ticket_schema = {
"type": "object",
"properties": {
"problem_type": {
"type": "string",
"enum": ["device_fault", "consult", "complaint", "other"]
},
"device_model": {"type": ["string", "null"]},
"urgent_level": {
"type": "string",
"enum": ["low", "normal", "high"]
},
"user_requirements": {"type": "array", "items": {"type": "string"}}
},
"required": ["problem_type", "device_model", "urgent_level", "user_requirements"]
}
def extract_ticket(text: str):
sys_prompt = (
"You are MiMo, an AI assistant developed by Xiaomi. Today is date: Tuesday, December 16, 2025. Your knowledge cutoff date is December 2024.\n"
"Return JSON only, no explanations, no extra text.\n"
"Format: {\"problem_type\":\"device_fault|consult|complaint|other\",\"device_model\":string|null,\"urgent_level\":\"low|normal|high\",\"user_requirements\":array<string>}\n"
"Fill null if device model is unknown."
)
messages = [
{"role": "system", "content": sys_prompt},
{"role": "user", "content": text}
]
resp = client.chat.completions.create(
model="mimo-v2.6-pro",
messages=messages,
response_format={"type": "json_object"},
stream=False
)
json_text = resp.choices[0].message.content
data = json.loads(json_text)
try:
validate(instance=data, schema=ticket_schema)
return {"ok": True, "data": data}
except ValidationError as e:
return {"ok": False, "error": e.message, "raw": data}
if __name__ == "__main__":
# Test with two sample tickets
input_list = [
"My speaker can't connect Wi-Fi, I restarted it but no use, hope to solve quickly, don't know the model.",
"Want to ask how to set timing function, device model is Watch S1, no urgent demand."
]
for idx, text in enumerate(input_list, 1):
print(f"==== Ticket {idx} extraction result ====")
res = extract_ticket(text)
if res["ok"]:
print(json.dumps(res["data"], indent=4))
else:
print(f"Validation failed: {res['error']}")