diff --git a/src/google/adk/models/lite_llm.py b/src/google/adk/models/lite_llm.py index e06eb32248b..e6032abfd9b 100644 --- a/src/google/adk/models/lite_llm.py +++ b/src/google/adk/models/lite_llm.py @@ -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 @@ -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): @@ -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: @@ -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. @@ -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( @@ -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 ... ```). @@ -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) @@ -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 @@ -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) @@ -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("{") @@ -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 @@ -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 = [ @@ -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"] = ( diff --git a/src/google/adk/utils/streaming_utils.py b/src/google/adk/utils/streaming_utils.py index 86bb6d4ddbd..e2ca9153b7a 100644 --- a/src/google/adk/utils/streaming_utils.py +++ b/src/google/adk/utils/streaming_utils.py @@ -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( @@ -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 ) diff --git a/tests/unittests/models/test_litellm.py b/tests/unittests/models/test_litellm.py index 34c17bc9c0b..b850a43f0fb 100644 --- a/tests/unittests/models/test_litellm.py +++ b/tests/unittests/models/test_litellm.py @@ -33,6 +33,7 @@ from google.adk.models.lite_llm import _apply_provider_finish_reason from google.adk.models.lite_llm import _BraceDepthTracker from google.adk.models.lite_llm import _build_function_declaration_log +from google.adk.models.lite_llm import _build_tool_call_from_json_dict from google.adk.models.lite_llm import _content_to_message_param from google.adk.models.lite_llm import _convert_reasoning_value_to_parts from google.adk.models.lite_llm import _enforce_strict_openai_schema @@ -3590,6 +3591,84 @@ def test_message_to_generate_content_response_reports_non_object_tool_call( assert [part.text for part in response.content.parts] == ["Looking that up."] +# Deeper than the json decoder can go. Its limit depends on the Python version +# and the stack size (3.14 decodes 100,000 levels on some machines), so leave +# a wide margin. +_DEEPLY_NESTED = "[" * 1_000_000 + "]" * 1_000_000 +# Balanced braces, so a stream also checks it for completion as it arrives. +_DEEPLY_NESTED_OBJECT = '{"a":' * 1_000_000 + "1" + "}" * 1_000_000 + +# Arguments that used to raise out of response parsing instead of being +# reported, either from the parsers or from building the function call. +_UNUSABLE_TOOL_CALL_ARGUMENTS = [ + pytest.param("{[]: 1}", id="unhashable_key"), + pytest.param("{1: 2}", id="non_string_key"), + pytest.param("{'a': {1: 2}}", id="nested_non_string_key"), + pytest.param("{'a': [{1: 2}]}", id="non_string_key_in_list"), + pytest.param("{'a': ({1: 2},)}", id="non_string_key_in_tuple"), + pytest.param("{'a': {1, 2}}", id="set_value"), + pytest.param("{'a': b'x'}", id="bytes_value"), + pytest.param(_DEEPLY_NESTED, id="deeply_nested"), + pytest.param(_DEEPLY_NESTED_OBJECT, id="deeply_nested_object"), + # Over the int max str digits limit, which raises a plain ValueError. + pytest.param('{"a": ' + "1" * 5000 + "}", id="huge_integer"), +] + + +@pytest.mark.parametrize("arguments", _UNUSABLE_TOOL_CALL_ARGUMENTS) +def test_message_to_generate_content_response_reports_unusable_tool_call( + arguments, +): + """Arguments no repair can turn into a function call are reported.""" + message = ChatCompletionAssistantMessage( + role="assistant", + content="Looking that up.", + tool_calls=[ + ChatCompletionMessageToolCall( + type="function", + id="test_tool_call_id", + function=Function( + name="test_function", + arguments=arguments, + ), + ) + ], + ) + + response = _message_to_generate_content_response(message) + + assert response.finish_reason == types.FinishReason.MALFORMED_FUNCTION_CALL + assert response.error_code == types.FinishReason.MALFORMED_FUNCTION_CALL + assert "test_function" in response.error_message + assert [part.text for part in response.content.parts] == ["Looking that up."] + + +def test_build_tool_call_from_json_dict_too_deep_to_encode_returns_none(): + """Arguments that decoded but cannot be re-encoded leave the text as text. + + How deep that is depends on the Python version and the stack size, so the + encoder is made to fail instead. + """ + candidate = {"name": "test_function", "arguments": {"a": 1}} + + with patch.object(json, "dumps", side_effect=RecursionError): + tool_call = _build_tool_call_from_json_dict(candidate, index=0) + + assert tool_call is None + + +def test_message_to_generate_content_response_keeps_deeply_nested_text(): + """Text that only looks like the start of a JSON tool call stays text.""" + message = ChatCompletionAssistantMessage( + role="assistant", + content=_DEEPLY_NESTED, + ) + + response = _message_to_generate_content_response(message) + + assert [part.text for part in response.content.parts] == [_DEEPLY_NESTED] + + @pytest.mark.parametrize("arguments", [42, 3.14, True, ["test_arg"]]) def test_message_to_generate_content_response_reports_non_string_arguments( arguments, @@ -4922,6 +5001,22 @@ def test_extract_json_from_deepseek_args_invalid_fence_returns_none(): assert _extract_json_from_deepseek_args('```json\n{"a": 1,}\n```') is None +@pytest.mark.parametrize( + "args_text", + [ + pytest.param(_DEEPLY_NESTED_OBJECT, id="bare"), + pytest.param( + "```json\n" + _DEEPLY_NESTED_OBJECT + "\n```", id="fenced" + ), + ], +) +def test_extract_json_from_deepseek_args_deeply_nested_returns_none( + args_text, +): + """Arguments nested past the decoder's limit are rejected, not raised.""" + assert _extract_json_from_deepseek_args(args_text) is None + + @pytest.mark.parametrize( "text", [ @@ -8862,6 +8957,54 @@ async def test_streaming_tool_call_non_object_json_arguments_reports_malformed( assert not any(part.function_call for part in final_response.content.parts) +@pytest.mark.asyncio +@pytest.mark.parametrize("arguments", _UNUSABLE_TOOL_CALL_ARGUMENTS) +async def test_streaming_tool_call_unusable_arguments_reports_malformed( + arguments, mock_completion, lite_llm_instance +): + """Streamed arguments no repair can turn into a function call are refused.""" + stream_chunks = [ + ModelResponseStream( + choices=[ + StreamingChoices( + finish_reason=None, + delta=Delta( + role="assistant", + content="Looking that up.", + tool_calls=[ + ChatCompletionDeltaToolCall( + type="function", + id="call_789", + function=Function( + name="test_function", + arguments=arguments, + ), + index=0, + ) + ], + ), + ) + ] + ), + ModelResponseStream( + choices=[StreamingChoices(finish_reason="tool_calls", delta=Delta())] + ), + ] + mock_completion.return_value = iter(stream_chunks) + + responses = [ + response + async for response in lite_llm_instance.generate_content_async( + LLM_REQUEST_WITH_FUNCTION_DECLARATION, stream=True + ) + ] + + final_response = responses[-1] + assert final_response.error_code == types.FinishReason.MALFORMED_FUNCTION_CALL + # The stream path refuses the call like any other unparseable arguments. + assert final_response.content is None + + @pytest.mark.asyncio async def test_streaming_tool_call_non_object_json_arguments_with_length_reports_max_tokens( mock_completion, lite_llm_instance @@ -13944,6 +14087,14 @@ def test_valid_and_repaired_arguments(self, arguments, expected): 'I will call the tool with {"path": "/x"}', 'Here is the result: ```json\n{"a": 1}\n```', "```json" + "\n" * 10000, + *_UNUSABLE_TOOL_CALL_ARGUMENTS, + pytest.param("{a: " + _DEEPLY_NESTED + "}", id="unquoted_deep"), + # ast.literal_eval raises MemoryError and RecursionError for these. + pytest.param("-" * 100_000 + "1", id="literal_eval_memory_error"), + pytest.param("1" + "+1" * 100_000, id="literal_eval_recursion_error"), + pytest.param( + "```json\n" + _DEEPLY_NESTED + "\n```", id="fenced_deep" + ), ], ) def test_ambiguous_and_malformed_arguments_raise(self, arguments): @@ -13951,6 +14102,13 @@ def test_ambiguous_and_malformed_arguments_raise(self, arguments): with pytest.raises(json.JSONDecodeError): _parse_tool_call_arguments(arguments) + def test_self_referencing_arguments_raise(self): + """A dict that contains itself is reported, not walked forever.""" + arguments = {} + arguments["a"] = arguments + with pytest.raises(json.JSONDecodeError): + _parse_tool_call_arguments(arguments) + def test_repaired_arguments_log_warning_without_raw_payload(self, caplog): """Repaired non-strict JSON arguments emit a warning without raw payload.""" with caplog.at_level(logging.WARNING, logger="google_adk"): diff --git a/tests/unittests/utils/test_streaming_utils.py b/tests/unittests/utils/test_streaming_utils.py index bfd2c08ec36..6fb7d3376c0 100644 --- a/tests/unittests/utils/test_streaming_utils.py +++ b/tests/unittests/utils/test_streaming_utils.py @@ -1961,6 +1961,29 @@ def test_set_value_by_json_path(self): class TestJsonPathTracker: + def test_tracker_huge_integer_returns_no_diffs(self): + """An integer over the int max str digits limit gives no partial args.""" + tracker = streaming_utils._JsonPathTracker() + + assert tracker.handle_chunk('{"a": ' + "1" * 5000 + "}") == [] + + def test_tracker_integer_too_large_for_a_float_has_no_value(self): + """An integer past the float range gives a valueless partial arg.""" + tracker = streaming_utils._JsonPathTracker() + + diffs = tracker.handle_chunk('{"a": 1' + "0" * 400 + "}") + + assert len(diffs) == 1 + assert diffs[0].json_path == "$.a" + assert diffs[0].number_value is None + + def test_tracker_deep_nesting_returns_no_diffs(self): + """Nesting too deep to diff recursively gives no partial args.""" + tracker = streaming_utils._JsonPathTracker() + depth = 1200 + + assert tracker.handle_chunk('{"a":' * depth + "1" + "}" * depth) == [] + def test_tracker_flat_object(self): tracker = streaming_utils._JsonPathTracker()