forked from google/adk-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_gemini_schema_util.py
More file actions
233 lines (197 loc) · 8.02 KB
/
_gemini_schema_util.py
File metadata and controls
233 lines (197 loc) · 8.02 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
# 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 re
from typing import Any
from typing import Optional
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
# Pre-compiled regex patterns for _to_snake_case
_RE_NON_ALNUM = re.compile(r"[^a-zA-Z0-9]+")
_RE_LOWER_UPPER = re.compile(r"([a-z0-9])([A-Z])")
_RE_UPPER_UPPER_LOWER = re.compile(r"([A-Z]+)([A-Z][a-z])")
_RE_MULTI_UNDERSCORE = re.compile(r"_+")
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_NON_ALNUM.sub("_", text)
# Insert underscores before uppercase letters (handling both CamelCases)
text = _RE_LOWER_UPPER.sub(r"\1_\2", text) # lowerCamelCase
text = _RE_UPPER_UPPER_LOWER.sub(
r"\1_\2", text
) # UpperCamelCase and acronyms
# Convert to lowercase
text = text.lower()
# Remove consecutive underscores (clean up extra underscores)
text = _RE_MULTI_UNDERSCORE.sub("_", 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"})
return schema
def _dereference_schema(schema: dict[str, Any]) -> dict[str, Any]:
"""Resolves $ref pointers in a JSON schema."""
defs = schema.get("$defs", {})
def _resolve_refs(sub_schema: Any) -> Any:
if isinstance(sub_schema, dict):
if "$ref" in sub_schema:
ref_key = sub_schema["$ref"].split("/")[-1]
if ref_key in defs:
# Found the reference, replace it with the definition.
resolved = defs[ref_key].copy()
# Merge properties from the reference, allowing overrides.
sub_schema_copy = sub_schema.copy()
del sub_schema_copy["$ref"]
resolved.update(sub_schema_copy)
# Recursively resolve refs in the newly inserted part.
return _resolve_refs(resolved)
else:
# Reference not found, return as is.
return sub_schema
else:
# No $ref, so traverse deeper into the dictionary.
return {key: _resolve_refs(value) for key, value in sub_schema.items()}
elif isinstance(sub_schema, list):
# Traverse into lists.
return [_resolve_refs(item) for item in sub_schema]
else:
# Not a dict or list, return as is.
return sub_schema
dereferenced_schema = _resolve_refs(schema)
# Remove the definitions block after resolving.
if "$defs" in dereferenced_schema:
del dereferenced_schema["$defs"]
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")
snake_case_schema[field_name] = [
_sanitize_schema_formats_for_gemini(
value, preserve_null_type=should_preserve
)
for value in field_value
]
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)
return Schema.from_json_schema(
json_schema=_ExtendedJSONSchema.model_validate(sanitized_schema),
api_option=get_google_llm_variant(),
)