moonshot_schema.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. """Translate OpenAI-style tool schemas to Moonshot's (Kimi) stricter JSON Schema subset.
  2. Violations fail with HTTP 400 "tools.function.parameters is not a valid moonshot
  3. flavored json schema". Rules: (1) every property schema carries a ``type``;
  4. (2) with ``anyOf``, ``type`` belongs on the children, never the parent; (3) enum
  5. arrays under scalar types may not contain null / empty string; (4) every object
  6. schema carries a ``required`` array, even an empty one. The ``#/definitions/`` →
  7. ``#/$defs/`` rewrite lives in ``tools/mcp_tool`` so it applies to all providers.
  8. """
  9. from __future__ import annotations
  10. import copy
  11. from typing import Any, Dict, List
  12. # Values are maps of name → schema: recurse into the values, but the map itself
  13. # is not a schema and gets no repairs.
  14. _SCHEMA_MAP_KEYS = frozenset({"properties", "patternProperties", "$defs", "definitions"})
  15. # Values are lists of schemas.
  16. _SCHEMA_LIST_KEYS = frozenset({"anyOf", "oneOf", "allOf", "prefixItems"})
  17. # Values are a single nested schema (additionalProperties may also be a bool).
  18. _SCHEMA_NODE_KEYS = frozenset(
  19. {"items", "contains", "not", "additionalProperties", "propertyNames", "if", "then", "else"}
  20. )
  21. _SCALAR_TYPES = frozenset({"string", "integer", "number", "boolean"})
  22. # bool before int: bool is an int subclass.
  23. _ENUM_SAMPLE_TYPES = ((bool, "boolean"), (int, "integer"), (float, "number"))
  24. def _empty_object_schema() -> dict[str, Any]:
  25. return {"type": "object", "properties": {}, "required": []}
  26. def _repair_schema(node: Any) -> Any:
  27. """Recursively apply the Moonshot repairs to a schema node."""
  28. if isinstance(node, list):
  29. return [_repair_schema(item) for item in node]
  30. if not isinstance(node, dict):
  31. return node
  32. repaired: dict[str, Any] = {}
  33. for key, value in node.items():
  34. if key in _SCHEMA_MAP_KEYS and isinstance(value, dict):
  35. repaired[key] = {sub_key: _repair_schema(sub_val) for sub_key, sub_val in value.items()}
  36. elif (key in _SCHEMA_LIST_KEYS and isinstance(value, list)) or (
  37. key in _SCHEMA_NODE_KEYS and isinstance(value, dict)
  38. ):
  39. repaired[key] = _repair_schema(value)
  40. else:
  41. repaired[key] = value
  42. # Rule 2, plus: Moonshot rejects null-type branches inside anyOf. Drop
  43. # them; a single surviving branch is promoted into this node and falls
  44. # through to rules 1/3/4, otherwise the pruned anyOf is returned as-is.
  45. if "anyOf" in repaired and isinstance(repaired["anyOf"], list):
  46. repaired.pop("type", None)
  47. non_null = [b for b in repaired["anyOf"] if isinstance(b, dict) and b.get("type") != "null"]
  48. if not non_null or len(non_null) == len(repaired["anyOf"]):
  49. return repaired
  50. if len(non_null) > 1:
  51. repaired["anyOf"] = non_null
  52. return repaired
  53. repaired = {**{k: v for k, v in repaired.items() if k != "anyOf"}, **non_null[0]}
  54. # Moonshot also rejects the non-standard ``nullable`` keyword.
  55. repaired.pop("nullable", None)
  56. # Rule 1 ($ref nodes take their type from the referenced definition).
  57. # Runs before rule 3 so enum cleanup can see the type.
  58. if "$ref" not in repaired:
  59. repaired = _fill_missing_type(repaired)
  60. # Rule 3: drop null/"" enum values under scalar types; drop an emptied enum.
  61. if isinstance(repaired.get("enum"), list) and repaired.get("type") in _SCALAR_TYPES:
  62. cleaned = [v for v in repaired["enum"] if v is not None and v != ""]
  63. if cleaned:
  64. repaired["enum"] = cleaned
  65. else:
  66. repaired.pop("enum")
  67. # Rule 4.
  68. if repaired.get("type") == "object":
  69. repaired = _ensure_required_array(repaired)
  70. return repaired
  71. def _ensure_required_array(node: dict[str, Any]) -> dict[str, Any]:
  72. """Guarantee an object schema carries a ``required`` list, pruning names not in
  73. ``properties`` (Moonshot also rejects dangling names). Mutates and returns ``node``."""
  74. props = node.get("properties")
  75. req = node.get("required")
  76. if isinstance(req, list):
  77. if isinstance(props, dict):
  78. node["required"] = [r for r in req if r in props]
  79. else:
  80. node["required"] = []
  81. return node
  82. def _fill_missing_type(node: dict[str, Any]) -> dict[str, Any]:
  83. """Infer a ``type`` if this schema node has none.
  84. A type list collapses to its first concrete member; otherwise
  85. ``properties``/``required``/``additionalProperties`` → object,
  86. ``items``/``prefixItems`` → array, ``enum`` → type of its first value,
  87. else ``string`` (safest scalar). A bare ``if``/``then``/``else`` node
  88. constrains whatever instance it is attached to rather than describing
  89. its own type, so it is left untyped instead of defaulting to ``string``.
  90. """
  91. node_type = node.get("type")
  92. if isinstance(node_type, list):
  93. concrete = next((t for t in node_type if isinstance(t, str) and t not in {"", "null"}), "string")
  94. return {**node, "type": concrete}
  95. if "type" in node and node_type not in {None, ""}:
  96. return node
  97. if "properties" in node or "required" in node or "additionalProperties" in node:
  98. inferred = "object"
  99. elif "items" in node or "prefixItems" in node:
  100. inferred = "array"
  101. elif isinstance(node.get("enum"), list) and node["enum"]:
  102. sample = node["enum"][0]
  103. inferred = next((t for cls, t in _ENUM_SAMPLE_TYPES if isinstance(sample, cls)), "string")
  104. elif "if" in node or "then" in node or "else" in node:
  105. return node
  106. else:
  107. inferred = "string"
  108. return {**node, "type": inferred}
  109. def sanitize_moonshot_tool_parameters(parameters: Any) -> dict[str, Any]:
  110. """Deep-copied, Moonshot-compatible object schema; input is not mutated."""
  111. if not isinstance(parameters, dict):
  112. return _empty_object_schema()
  113. repaired = _repair_schema(copy.deepcopy(parameters))
  114. if not isinstance(repaired, dict):
  115. return _empty_object_schema()
  116. # Top-level must be an object schema.
  117. repaired["type"] = "object"
  118. repaired.setdefault("properties", {})
  119. return _ensure_required_array(repaired)
  120. def sanitize_moonshot_tools(tools: list[dict[str, Any]]) -> list[dict[str, Any]]:
  121. """Apply ``sanitize_moonshot_tool_parameters`` to every tool's parameters.
  122. Returns the input list object itself when nothing needed repairing.
  123. """
  124. if not tools:
  125. return tools
  126. sanitized: list[dict[str, Any]] = []
  127. any_change = False
  128. for tool in tools:
  129. fn = tool.get("function") if isinstance(tool, dict) else None
  130. if isinstance(fn, dict):
  131. params = fn.get("parameters")
  132. repaired = sanitize_moonshot_tool_parameters(params)
  133. if repaired is not params:
  134. any_change = True
  135. tool = {**tool, "function": {**fn, "parameters": repaired}}
  136. sanitized.append(tool)
  137. return sanitized if any_change else tools
  138. def is_moonshot_model(model: str | None) -> bool:
  139. """True for any Kimi / Moonshot model slug, regardless of aggregator prefix.
  140. Matches bare names (``kimi-k2.6``, ``moonshotai/Kimi-K2.6``) and
  141. aggregator-prefixed slugs (``nous/moonshotai/kimi-k2.6``), since aggregators
  142. route to Moonshot inference under their own base URL.
  143. """
  144. if not model:
  145. return False
  146. bare = model.strip().lower()
  147. tail = bare.rsplit("/", 1)[-1]
  148. if tail.startswith("kimi-") or tail == "kimi":
  149. return True
  150. # Kimi Coding Plan serves K3 under the bare slug ``k3`` (plus ``k3.1`` / ``k3-turbo``).
  151. if tail == "k3" or tail.startswith(("k3.", "k3-")):
  152. return True
  153. return "moonshot" in bare or "/kimi" in bare or bare.startswith("kimi")