跳转至

结构化输出

大模型执行信息抽取或结构化数据生成任务时,常返回多余文本(如 `json 标记),导致下游解析失败。

解决方案

通过设置 response_format 参数开启结构化输出,强制模型返回标准格式的纯 JSON 字符串。

支持的模型

  • GLM-5.1
  • GLM-5
  • GLM-4.7
  • MiniMax-M2.5
  • MiniMax-M2.1

使用方法

response_format: 指定响应格式,设置为 {"type": "json_object"} 启用 JSON 模式

结构化输出示例

在 python 中使用

import requests

url = "https://api.magikcloud.cn/v1/chat/completions"

payload = {
    "model": "${ENDPOINT}", # 替换为你的接入点ID
    "messages": [
        {
            "role": "system",
            "content": "请抽取公司名称和地点"
        },
        {
            "role": "user",
            "content": "您正在使用魔形智能科技(上海)有限公司提供的算力服务"
        }
    ],
    "response_format": {
      "type": "json_object"
    }
}
headers = {
    "Authorization": "Bearer ${API_KEY}", # 请替换为您的 API Key
    "Content-Type": "application/json"
}

response = requests.request("POST", url, json=payload, headers=headers)

print(response.text)

在 curl 中使用

curl --location --request POST 'https://api.magikcloud.cn/v1/chat/completions' \
--header 'Authorization: Bearer ${API_KEY}"' \ # 替换为你的 API Key
--header 'Content-Type: application/json' \
--data-raw '{
    "model": "${ENDPOINT}", # 替换为你的接入点ID
    "messages": [
        {
            "role": "system",
            "content": "请抽取公司名称和地点"
        },
        {
            "role": "user",
            "content": "您正在使用魔形智能科技(上海)有限公司提供的算力服务"
        }
    ],
    "response_format": {
      "type": "json_object"
    }
  }'

返回结果

{
    "公司名称": "魔形智能科技(上海)有限公司", 
    "地点": "上海"
}