Repository navigation
Expand file tree
/
Copy path_gemini_schema_util.py
More file actions
338 lines (293 loc) · 12.2 KB
/
Copy path_gemini_schema_util.py
File metadata and controls
338 lines (293 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
import json
import re
from typing import Any
from typing import Literal
from typing import Optional
import urllib.parse
from google.genai.types import JSONSchema
from google.genai.types import Schema
from pydantic import Field
from ..utils.variant_utils import get_google_llm_variant
from ..utils.variant_utils import GoogleLLMVariant
class _ExtendedJSONSchema(JSONSchema):
property_ordering: Optional[list[str]] = Field(
default=None,
description="""Optional. The order of the properties. Not a standard field in open api spec. Only used to support the order of the properties.""",
)
def _to_snake_case(text: str) -> str:
"""Converts a string into snake_case.
Handles lowerCamelCase, UpperCamelCase, or space-separated case, acronyms
(e.g., "REST API") and consecutive uppercase letters correctly. Also handles
mixed cases with and without spaces.
Examples:
```
to_snake_case('camelCase') -> 'camel_case'
to_snake_case('UpperCamelCase') -> 'upper_camel_case'
to_snake_case('space separated') -> 'space_separated'
```
Args:
text: The input string.
Returns:
The snake_case version of the string.
"""
# Handle spaces and non-alphanumeric characters (replace with underscores)
text = re.sub(r"[^a-zA-Z0-9]+", "_", text)
# Insert underscores before uppercase letters (handling both CamelCases)
text = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", text) # lowerCamelCase
text = re.sub(
r"([A-Z]+)([A-Z][a-z])", r"\1_\2", text
) # UpperCamelCase and acronyms
# Convert to lowercase
text = text.lower()
# Remove consecutive underscores (clean up extra underscores)
text = re.sub(r"_+", "_", text)
# Remove leading and trailing underscores
text = text.strip("_")
return text
def _sanitize_schema_type(
schema: dict[str, Any], preserve_null_type: bool = False
) -> dict[str, Any]:
if not schema:
schema["type"] = "object"
if isinstance(schema.get("type"), list):
types_no_null = [t for t in schema["type"] if t != "null"]
nullable = len(types_no_null) != len(schema["type"])
if "array" in types_no_null:
non_null_type = "array"
else:
non_null_type = types_no_null[0] if types_no_null else "object"
if nullable:
schema["type"] = [non_null_type, "null"]
else:
schema["type"] = non_null_type
elif schema.get("type") == "null" and not preserve_null_type:
schema["type"] = ["object", "null"]
schema_type = schema.get("type")
is_array = schema_type == "array" or (
isinstance(schema_type, list) and "array" in schema_type
)
if is_array:
schema.setdefault("items", {"type": "string"})
effective_type = schema_type
if isinstance(schema_type, list):
non_null = [t for t in schema_type if t != "null"]
effective_type = non_null[0] if non_null else None
if effective_type == "string" and isinstance(schema.get("enum"), list):
# Gemini rejects non-string enum values on a string-typed field; some
# servers emit integer enums on string fields, so render them in their
# JSON form. A null member is dropped: nullability is carried by the
# schema type, not by an enum entry.
schema["enum"] = [
v if isinstance(v, str) else json.dumps(v)
for v in schema["enum"]
if v is not None
]
return schema
def _resolve_json_pointer(ref_path: str, root: dict[str, Any]) -> object | None:
"""Resolves a URI-fragment JSON Pointer (e.g. '#' or '#/path/to/node').
Returns the referenced value, or None if the pointer is not a valid URI
fragment, the path does not exist, or the target value itself is None (JSON
null, which callers treat the same as an unresolved path for defs fallback).
"""
if ref_path == "#":
return root
if not ref_path.startswith("#/"):
return None
parts = [urllib.parse.unquote(part) for part in ref_path[2:].split("/")]
current: object = root
for part in parts:
part = part.replace("~1", "/").replace("~0", "~")
if isinstance(current, dict):
if part not in current:
return None
current = current[part]
elif isinstance(current, list):
if not re.fullmatch(r"0|[1-9][0-9]*", part):
return None
idx = int(part)
if idx >= len(current):
return None
current = current[idx]
else:
return None
return current
def _dereference_schema(schema: dict[str, Any]) -> dict[str, Any]:
"""Resolves $ref pointers in a JSON schema.
Unresolvable or dangling $ref nodes, as well as references resolving to
non-dict values, are left unchanged in the returned schema. Downstream
consumers are responsible for validating that all required references were
dereferenced.
"""
# Support both the draft 2019-09+/2020-12 keyword (`$defs`) and the
# draft-07 keyword (`definitions`). The MCP specification allows tool
# `inputSchema`s to use either, so a server sending draft-07 schemas with
# `definitions` + `$ref: "#/definitions/..."` must dereference correctly.
# If the same definition key appears in both `definitions` and `$defs`,
# `$defs` takes precedence. Note that JSON Pointer resolution takes
# precedence over `defs` lookups.
defs = {**schema.get("definitions", {}), **schema.get("$defs", {})}
def _resolve_refs(sub_schema: object, path_refs: frozenset[str]) -> object:
if isinstance(sub_schema, dict):
if "$ref" in sub_schema:
ref_uri = sub_schema["$ref"]
ref_key = ref_uri.split("/")[-1]
if ref_uri in path_refs:
return {
"type": "object",
"description": f"Circular ref to {ref_key}",
}
new_path = path_refs | {ref_uri}
# Try to resolve as a JSON Pointer reference (e.g. #/properties/foo).
resolved = _resolve_json_pointer(ref_uri, schema)
if isinstance(resolved, dict):
resolved_copy = resolved.copy()
sub_schema_copy = sub_schema.copy()
del sub_schema_copy["$ref"]
resolved_copy.update(sub_schema_copy)
return _resolve_refs(resolved_copy, new_path)
# Fall back to defs lookup if the definition key exists.
if (
resolved is None
and ref_key in defs
and isinstance(defs[ref_key], dict)
):
resolved = defs[ref_key].copy()
sub_schema_copy = sub_schema.copy()
del sub_schema_copy["$ref"]
resolved.update(sub_schema_copy)
return _resolve_refs(resolved, new_path)
# Reference not found or resolves to a non-dict, return as is.
return sub_schema
else:
# No $ref, so traverse deeper into the dictionary.
return {
key: _resolve_refs(value, path_refs)
for key, value in sub_schema.items()
}
elif isinstance(sub_schema, list):
# Traverse into lists.
return [_resolve_refs(item, path_refs) for item in sub_schema]
else:
# Not a dict or list, return as is.
return sub_schema
dereferenced_schema = _resolve_refs(schema, frozenset())
if not isinstance(dereferenced_schema, dict) or not all(
isinstance(key, str) for key in dereferenced_schema
):
raise TypeError("Dereferenced JSON schema must remain an object.")
# Remove the definition blocks after resolving so the leftover keywords do
# not leak into the Gemini schema (which would otherwise raise a KeyError).
for defs_keyword in ("$defs", "definitions"):
if defs_keyword in dereferenced_schema:
del dereferenced_schema[defs_keyword]
return dereferenced_schema
def _sanitize_schema_formats_for_gemini(
schema: Any, preserve_null_type: bool = False
) -> Any:
"""Filters schemas to only include fields supported by JSONSchema."""
if isinstance(schema, list):
return [
_sanitize_schema_formats_for_gemini(
item, preserve_null_type=preserve_null_type
)
for item in schema
]
# JSON Schema allows boolean schemas: `true` (accept any value) and `false`
# (reject all values). Gemini has no equivalent for either. `true` is
# approximated as an unconstrained object schema; `false` has no meaningful
# Gemini representation and is also mapped to an object schema as a safe
# fallback so that schema conversion does not crash.
if isinstance(schema, bool):
return {"type": "object"}
if not isinstance(schema, dict):
return schema
supported_fields: set[str] = set(_ExtendedJSONSchema.model_fields.keys())
# Gemini rejects schemas that include `additionalProperties`, so drop it.
supported_fields.discard("additional_properties")
schema_field_names: set[str] = {"items"}
list_schema_field_names: set[str] = {
"any_of",
"one_of", # 'all_of', 'not' to come
}
snake_case_schema: dict[str, Any] = {}
dict_schema_field_names: tuple[str, ...] = (
"properties",
"defs",
)
for field_name, field_value in schema.items():
field_name = _to_snake_case(field_name)
if field_name in schema_field_names:
snake_case_schema[field_name] = _sanitize_schema_formats_for_gemini(
field_value
)
elif field_name in list_schema_field_names:
should_preserve = field_name in ("any_of", "one_of")
sanitized_branches = [
_sanitize_schema_formats_for_gemini(
value, preserve_null_type=should_preserve
)
for value in field_value
]
if field_name == "one_of":
# Gemini's Schema has no one_of and the conversion drops an unknown
# field silently, which would leave the property with no type at all.
# Widening to any_of keeps the branch types; the difference is that
# any_of also accepts a value matching more than one branch.
field_name = "any_of"
if field_name == "any_of":
# A schema may carry both keywords, in either order, so accumulate
# instead of letting whichever comes second win.
sanitized_branches = (
snake_case_schema.get("any_of", []) + sanitized_branches
)
snake_case_schema[field_name] = sanitized_branches
elif field_name in dict_schema_field_names and field_value is not None:
snake_case_schema[field_name] = {
key: _sanitize_schema_formats_for_gemini(value)
for key, value in field_value.items()
}
# special handle of format field
elif field_name == "format" and field_value:
current_type = schema.get("type")
if (
# only "int32" and "int64" are supported for integer or number type
(current_type == "integer" or current_type == "number")
and field_value in ("int32", "int64")
or
# only 'enum' and 'date-time' are supported for STRING type"
(current_type == "string" and field_value in ("date-time", "enum"))
):
snake_case_schema[field_name] = field_value
elif field_name in supported_fields and field_value is not None:
snake_case_schema[field_name] = field_value
return _sanitize_schema_type(snake_case_schema, preserve_null_type)
def _to_gemini_schema(openapi_schema: dict[str, Any]) -> Schema:
"""Converts an OpenAPI v3.1. schema dictionary to a Gemini Schema object."""
if openapi_schema is None:
return None
if not isinstance(openapi_schema, dict):
raise TypeError("openapi_schema must be a dictionary")
dereferenced_schema = _dereference_schema(openapi_schema)
sanitized_schema = _sanitize_schema_formats_for_gemini(dereferenced_schema)
variant = get_google_llm_variant()
api_option: Literal["VERTEX_AI", "GEMINI_API"] = (
"VERTEX_AI" if variant is GoogleLLMVariant.VERTEX_AI else "GEMINI_API"
)
return Schema.from_json_schema(
json_schema=_ExtendedJSONSchema.model_validate(sanitized_schema),
api_option=api_option,
)