You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JSON Schema条件语句中正确引用子Schema属性?

正确实现JSON Schema中基于子Schema属性的互斥约束

要实现你需要的约束,核心是在interaction子Schema内部使用if/then逻辑,结合additionalProperties: false来限制mock_results_metadata的结构,以下是正确的配置示例:

"$defs": {
  "interaction": {
    "type": "object",
    "properties": {
      "user_prompt": {
        "type": "string",
        "description": "User prompt that the assistant model receives."
      },
      "type": {
        "type": "string",
        "description": "Type of request in the user prompt. Allowed values: 'get_value', 'get_table', 'verification', 'chat', 'malicious'",
        "enum": ["get_value", "get_table", "verification", "chat", "malicious"]
      },
      "mock_results_metadata": {
        "type": "object"
      }
    },
    "required": ["type"],
    "allOf": [
      // 处理type为get_value的场景
      {
        "if": {
          "properties": {
            "type": { "const": "get_value" }
          }
        },
        "then": {
          "properties": {
            "mock_results_metadata": {
              "type": "object",
              "properties": {
                "value": { "type": "string" } // 可根据实际需求修改value的类型
              },
              "required": ["value"], // 若value为必填则添加
              "additionalProperties": false
            }
          }
        }
      },
      // 处理type为get_table的场景
      {
        "if": {
          "properties": {
            "type": { "const": "get_table" }
          }
        },
        "then": {
          "properties": {
            "mock_results_metadata": {
              "type": "object",
              "properties": {
                "no_rows": { "type": "boolean" } // 可根据实际需求修改no_rows的类型
              },
              "required": ["no_rows"], // 若no_rows为必填则添加
              "additionalProperties": false
            }
          }
        }
      },
      // 可选:处理其他type值的场景(比如不允许mock_results_metadata存在)
      {
        "if": {
          "properties": {
            "type": { "enum": ["verification", "chat", "malicious"] }
          }
        },
        "then": {
          "properties": {
            "mock_results_metadata": { "not": {} }
          }
        }
      }
    ]
  }
}

关键注意事项:

  • 条件引用逻辑:在if块中直接通过properties.type.const匹配目标值,因为是在interaction Schema内部,无需额外$ref引用,路径为当前Schema的相对路径。
  • 严格属性限制:必须添加additionalProperties: false,确保mock_results_metadata只能包含指定属性,避免多余属性通过验证。
  • 必填属性约束:若value或no_rows是必填项,需在对应then块的mock_results_metadata中添加required数组。
  • 确保type存在:给interaction添加required: ["type"],避免type缺失时条件判断失效。

内容的提问来源于stack exchange,提问作者danielampr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 12:02:10