Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 77 additions & 10 deletions src/google/adk/models/lite_llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,19 @@
_LITELLM_STRUCTURED_TYPES = {"json_object", "json_schema"}
_JSON_DECODER = json.JSONDecoder()
_UNQUOTED_KEY_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
# Besides JSONDecodeError (a ValueError), the json decoder raises a plain
# ValueError for an integer over the int max str digits limit, and
# RecursionError for deep nesting.
_JSON_DECODE_ERRORS = (ValueError, RecursionError)
# What ast.literal_eval documents raising for malformed input, such as
# TypeError for an unhashable key like `{[]: 1}`.
_LITERAL_EVAL_ERRORS = (
SyntaxError,
ValueError,
TypeError,
MemoryError,
RecursionError,
)

# Mapping of major MIME type prefixes to LiteLLM content types for URL blocks.
# Audio is handled separately as `input_audio` content blocks because LiteLLM
Expand Down Expand Up @@ -243,8 +256,52 @@ def _parse_tool_call_arguments(
The parsed arguments (typically a dict).

Raises:
json.JSONDecodeError: When the arguments cannot be parsed.
json.JSONDecodeError: When the arguments cannot be parsed, or parse to
something JSON cannot carry: a non-string key, a set or bytes from a
Python literal, or nesting too deep to encode. The function call is
serialized back to JSON later, so such a value cannot become one.
"""
result = _decode_tool_call_arguments(arguments, function_name=function_name)
doc = arguments if isinstance(arguments, str) else ""
try:
json.dumps(result)
except (TypeError, ValueError, RecursionError):
raise json.JSONDecodeError(
"Tool call arguments cannot be encoded as JSON", doc, 0
) from None
# After the encoding check, which has ruled out cycles and deep nesting.
if not _has_only_string_keys(result):
raise json.JSONDecodeError(
"Tool call argument keys must be strings", doc, 0
)
return result


def _has_only_string_keys(value: Any) -> bool:
"""Whether every dict in `value`, at any depth, has only string keys.

A Python literal repair can give `{1: 2}` at any level, and json.dumps
would quietly turn the key into "1". Expects a value json.dumps has
already accepted, so it has no cycles.
"""
stack = [value]
while stack:
item = stack.pop()
if isinstance(item, dict):
if not all(isinstance(key, str) for key in item):
return False
stack.extend(item.values())
elif isinstance(item, (list, tuple)):
stack.extend(item)
return True


def _decode_tool_call_arguments(
arguments: Any,
*,
function_name: str | None = None,
) -> Any:
"""Decodes tool call arguments; see `_parse_tool_call_arguments`."""
if not arguments:
return {}
if not isinstance(arguments, str):
Expand All @@ -254,6 +311,12 @@ def _parse_tool_call_arguments(
return json.loads(arguments)
except json.JSONDecodeError as exc:
json_error = exc
except _JSON_DECODE_ERRORS:
# Too large an integer or too deep a nesting; the repairs below would
# only reach the same limit.
raise json.JSONDecodeError(
"Tool call arguments exceed the decoder's limits", arguments, 0
) from None

# Retry with Python literal eval (handles single-quoted keys, etc.).
try:
Expand All @@ -265,7 +328,7 @@ def _parse_tool_call_arguments(
level=logging.DEBUG,
)
return result
except (SyntaxError, ValueError):
except _LITERAL_EVAL_ERRORS:
pass

# Retry after quoting unquoted JSON object keys.
Expand All @@ -279,7 +342,7 @@ def _parse_tool_call_arguments(
function_name=function_name,
)
return result
except json.JSONDecodeError:
except _JSON_DECODE_ERRORS:
try:
result = ast.literal_eval(repaired_arguments)
_log_repaired_arguments(
Expand All @@ -289,7 +352,7 @@ def _parse_tool_call_arguments(
function_name=function_name,
)
return result
except (SyntaxError, ValueError):
except _LITERAL_EVAL_ERRORS:
pass

# Retry after stripping Markdown code fences (```json ... ```).
Expand All @@ -316,7 +379,7 @@ def _parse_tool_call_arguments(
function_name=function_name,
)
return result
except json.JSONDecodeError:
except _JSON_DECODE_ERRORS:
pass
try:
result = ast.literal_eval(text)
Expand All @@ -326,7 +389,7 @@ def _parse_tool_call_arguments(
function_name=function_name,
)
return result
except (SyntaxError, ValueError):
except _LITERAL_EVAL_ERRORS:
pass

raise json_error
Expand Down Expand Up @@ -2225,6 +2288,10 @@ def _build_tool_call_from_json_dict(
else:
try:
arguments_payload = json.dumps(args, ensure_ascii=False)
except RecursionError:
# Too deep to encode, and the str() fallback would recurse as well.
# Leave the text as text.
return None
except (TypeError, ValueError):
arguments_payload = _safe_json_serialize(args)

Expand Down Expand Up @@ -2289,7 +2356,7 @@ def _extract_json_from_deepseek_args(args_text: str) -> Optional[str]:
try:
json.loads(candidate)
return candidate
except json.JSONDecodeError:
except _JSON_DECODE_ERRORS:
pass
# Fall back to the first balanced { … } block.
open_brace = args_text.find("{")
Expand All @@ -2298,7 +2365,7 @@ def _extract_json_from_deepseek_args(args_text: str) -> Optional[str]:
try:
candidate, _ = _JSON_DECODER.raw_decode(args_text, open_brace)
return json.dumps(candidate, ensure_ascii=False)
except json.JSONDecodeError:
except _JSON_DECODE_ERRORS:
return None


Expand Down Expand Up @@ -2452,7 +2519,7 @@ def _decode_tool_calls(
):
try:
candidate, end = _JSON_DECODER.raw_decode(text, pos)
except json.JSONDecodeError:
except _JSON_DECODE_ERRORS:
break
candidates = candidate if isinstance(candidate, list) else [candidate]
calls = [
Expand Down Expand Up @@ -5130,7 +5197,7 @@ def _has_held_back_tool_calls() -> bool:
json.loads("".join(args_parts))
function_calls[index]["args_complete"] = True
fallback_index += 1
except json.JSONDecodeError:
except _JSON_DECODE_ERRORS:
pass

function_calls[index]["id"] = (
Expand Down
16 changes: 14 additions & 2 deletions src/google/adk/utils/streaming_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -737,13 +737,19 @@ def handle_chunk(self, chunk: str) -> list[types.PartialArg]:

try:
current_dict = json.loads(completed)
except (json.JSONDecodeError, RecursionError):
except (ValueError, RecursionError):
# ValueError also covers an integer over the int max str digits limit.
return []

if not isinstance(current_dict, dict):
return []

diffs = self._get_diff(self.previous_dict, current_dict)
try:
diffs = self._get_diff(self.previous_dict, current_dict)
except RecursionError:
# The diff walks the value recursively; nesting the decoder accepted
# can still be too deep for it. Partial args are optional.
return []
self.previous_dict = current_dict

if self._open_string_path is not None and not any(
Expand Down Expand Up @@ -901,6 +907,12 @@ def _create_partial_arg(self, path: str, val: Any) -> types.PartialArg:
json_path=path, string_value=val, will_continue=False
)
elif isinstance(val, (int, float)) and not isinstance(val, bool):
try:
float(val)
except OverflowError:
# number_value is a float; an integer too large for one is left
# valueless like other unsupported leaves.
return types.PartialArg(json_path=path, will_continue=False)
return types.PartialArg(
json_path=path, number_value=val, will_continue=False
)
Expand Down
Loading
Loading