diff --git a/src/google/adk/evaluation/final_response_match_v1.py b/src/google/adk/evaluation/final_response_match_v1.py index 2f81615e3cc..39b3c9e698e 100644 --- a/src/google/adk/evaluation/final_response_match_v1.py +++ b/src/google/adk/evaluation/final_response_match_v1.py @@ -117,6 +117,19 @@ def _is_non_spaced_script(char: str) -> bool: ) +def _is_script_separator(char: str) -> bool: + """Checks if a character is punctuation or a symbol inside a script block. + + The Thai, Lao, Khmer and Myanmar blocks also hold punctuation and symbols + (Khmer ។, Myanmar ။, Thai ฿). They separate words instead of being words + themselves, just like the punctuation of every other script, which this + tokenizer drops. + """ + if not _is_non_spaced_script(char): + return False + return unicodedata.category(char)[0] in ("P", "S") + + def _is_word_char(char: str) -> bool: # Combining marks (e.g. Thai vowel signs, Devanagari matras) are not # alphanumeric on their own but must stay attached to their base character. @@ -131,8 +144,10 @@ class _UnicodeAwareTokenizer: nothing and always scores 0. This tokenizer keeps Unicode word characters, normalizes Unicode variants (NFKC), splits non-spaced CJK characters at the character level, bundles non-spaced scripts by grapheme clusters (base - consonant + attached combining marks), and delegates ASCII tokens to the - default tokenizer. + consonant + attached combining marks), drops the punctuation and symbols of + those blocks, and delegates ASCII tokens to the default tokenizer. A cluster + is always closed before a following digit or Latin word, so the spacing + around such a word does not change the score. Note: Languages written without spaces (e.g. Thai, Chinese, Japanese) are @@ -148,20 +163,41 @@ def __init__(self, use_stemmer: bool = False): def tokenize(self, text: str) -> list[str]: text = unicodedata.normalize("NFKC", text).lower() processed_chars: list[str] = [] + # Whether the text emitted so far ends inside a grapheme cluster of a + # non-spaced script (a base consonant plus its combining marks). Such a + # cluster is opened with a leading space, so it also needs a boundary + # after it. + in_unspaced_cluster = False for char in text: if _is_cjk(char): processed_chars.extend([" ", char, " "]) + in_unspaced_cluster = False elif _is_non_spaced_script(char): - if unicodedata.category(char).startswith("M"): + if _is_script_separator(char): + # Punctuation and symbols of these blocks separate words instead of + # being words themselves (Khmer ទេ។ is the same answer as ទេ). + processed_chars.append(" ") + in_unspaced_cluster = False + elif unicodedata.category(char).startswith("M"): # Combining mark (vowel/tone mark): attach directly to previous base consonant! processed_chars.append(char) + in_unspaced_cluster = True else: # Base consonant: start a new grapheme cluster boundary by prepending a space! processed_chars.extend([" ", char]) + in_unspaced_cluster = True elif _is_word_char(char): + # A digit or a Latin word written right after the cluster (ราคา100) + # has to be a token of its own, exactly as it already is when a space + # separates it (ราคา 100). + is_combining_mark = unicodedata.category(char).startswith("M") + if in_unspaced_cluster and not is_combining_mark: + processed_chars.append(" ") + in_unspaced_cluster = False processed_chars.append(char) else: processed_chars.append(" ") + in_unspaced_cluster = False words = "".join(processed_chars).split() tokens: list[str] = [] for word in words: diff --git a/src/google/adk/models/anthropic_llm.py b/src/google/adk/models/anthropic_llm.py index 004fcbc3892..4bd9bc3f237 100644 --- a/src/google/adk/models/anthropic_llm.py +++ b/src/google/adk/models/anthropic_llm.py @@ -645,6 +645,12 @@ class _ToolUseIdSanitizer: Reuse one instance per conversation so a tool_use and its paired tool_result get matching unique outputs without collision across turns. + + Anthropic only accepts [a-zA-Z0-9_-]+, so a call whose ID is present but + invalid is as unusable as one whose ID is missing, and both are recorded as + pending. An ID-less result can therefore be paired with either form by tool + name. A fallback stops being pending as soon as a result answers it through + the call's own ID, so one call is never claimed by two results. """ def __init__(self) -> None: @@ -653,6 +659,19 @@ def __init__(self) -> None: self._unpaired_calls_list: list[str] = [] self._next_fallback: int = 0 + def _new_fallback(self) -> str: + assigned_id = f"toolu_fallback_{self._next_fallback}" + self._next_fallback += 1 + return assigned_id + + def _withdraw(self, assigned_id: str) -> None: + """Removes an already answered fallback from the pending registries.""" + if assigned_id in self._unpaired_calls_list: + self._unpaired_calls_list.remove(assigned_id) + for ids in self._unpaired_calls_by_name.values(): + if assigned_id in ids: + ids.remove(assigned_id) + def sanitize( self, tool_id: str | None, @@ -662,38 +681,49 @@ def sanitize( if tool_id and re.fullmatch(r"[a-zA-Z0-9_-]+", tool_id): return tool_id if tool_id and tool_id in self._mapping: - return self._mapping[tool_id] + assigned_id = self._mapping[tool_id] + if not is_call: + # The result answered this call through the call's own ID, so an + # ID-less result of the same tool must not claim the same fallback. + self._withdraw(assigned_id) + return assigned_id - if is_call or (tool_id and tool_id not in self._mapping): - assigned_id = f"toolu_fallback_{self._next_fallback}" - self._next_fallback += 1 + if is_call: + assigned_id = self._new_fallback() if tool_id: self._mapping[tool_id] = assigned_id - else: - if tool_name: - self._unpaired_calls_by_name.setdefault(tool_name, []).append( - assigned_id - ) - self._unpaired_calls_list.append(assigned_id) + # Registered for name-based pairing even when an invalid ID was present, + # because the paired result may arrive without any ID at all. + if tool_name: + self._unpaired_calls_by_name.setdefault(tool_name, []).append( + assigned_id + ) + self._unpaired_calls_list.append(assigned_id) + return assigned_id + + if tool_id: + # A result whose ID was never seen cannot be paired with a call, so it + # gets a fallback of its own and stays out of the pending registries: + # otherwise an ID-less result could later claim it as if it were a call. + assigned_id = self._new_fallback() + self._mapping[tool_id] = assigned_id + return assigned_id + + # Response with empty/None tool_id: pair with oldest pending call + if tool_name and self._unpaired_calls_by_name.get(tool_name): + assigned_id = self._unpaired_calls_by_name[tool_name].pop(0) + if assigned_id in self._unpaired_calls_list: + self._unpaired_calls_list.remove(assigned_id) + return assigned_id + elif self._unpaired_calls_list: + assigned_id = self._unpaired_calls_list.pop(0) + for ids in self._unpaired_calls_by_name.values(): + if assigned_id in ids: + ids.remove(assigned_id) + break return assigned_id else: - # Response with empty/None tool_id: pair with oldest pending call - if tool_name and self._unpaired_calls_by_name.get(tool_name): - assigned_id = self._unpaired_calls_by_name[tool_name].pop(0) - if assigned_id in self._unpaired_calls_list: - self._unpaired_calls_list.remove(assigned_id) - return assigned_id - elif self._unpaired_calls_list: - assigned_id = self._unpaired_calls_list.pop(0) - for ids in self._unpaired_calls_by_name.values(): - if assigned_id in ids: - ids.remove(assigned_id) - break - return assigned_id - else: - assigned_id = f"toolu_fallback_{self._next_fallback}" - self._next_fallback += 1 - return assigned_id + return self._new_fallback() def _part_to_message_block( diff --git a/tests/unittests/evaluation/test_final_response_match_v1.py b/tests/unittests/evaluation/test_final_response_match_v1.py index e772103f8c3..d094077f4e1 100644 --- a/tests/unittests/evaluation/test_final_response_match_v1.py +++ b/tests/unittests/evaluation/test_final_response_match_v1.py @@ -24,6 +24,7 @@ from google.adk.evaluation.final_response_match_v1 import _calculate_rouge_1_scores from google.adk.evaluation.final_response_match_v1 import _is_cjk from google.adk.evaluation.final_response_match_v1 import _is_non_spaced_script +from google.adk.evaluation.final_response_match_v1 import _is_script_separator from google.adk.evaluation.final_response_match_v1 import _is_word_char from google.adk.evaluation.final_response_match_v1 import _UnicodeAwareTokenizer from google.adk.evaluation.final_response_match_v1 import RougeEvaluator @@ -205,6 +206,102 @@ def test_unicode_aware_tokenizer_all_branches_coverage( assert tokenizer.tokenize(input_text) == expected_tokens +@pytest.mark.parametrize( + "unspaced, spaced", + [ + # A digit or a Latin word written right after the letters of a + # non-spaced script must tokenize like the same text with a space. + ("ราคา100", "ราคา 100"), + ("ซื้อiPhone", "ซื้อ iPhone"), + ("ລາຄາ100", "ລາຄາ 100"), + ("តម្លៃ100", "តម្លៃ 100"), + ("ဈေးနှုန်း100", "ဈေးနှုန်း 100"), + ("ดีabc", "ดี abc"), + # The reversed order already worked and has to keep working. + ("100บาท", "100 บาท"), + ("iPhoneซื้อ", "iPhone ซื้อ"), + ], +) +def test_unicode_aware_tokenizer_ignores_spacing_after_unspaced_script( + unspaced: str, spaced: str +): + """Digits and Latin words after a cluster are tokens of their own.""" + tokenizer = _UnicodeAwareTokenizer() + assert tokenizer.tokenize(unspaced) == tokenizer.tokenize(spaced) + + +def test_unicode_aware_tokenizer_splits_digits_after_thai_word(): + """ราคา100 tokenizes as ['ร', 'า', 'ค', 'า', '100'], not [..., 'า100'].""" + assert _UnicodeAwareTokenizer().tokenize("ราคา100") == [ + "ร", + "า", + "ค", + "า", + "100", + ] + + +def test_unicode_aware_tokenizer_splits_latin_word_after_thai_word(): + """ซื้อiPhone ends with the Latin word as its own token.""" + assert _UnicodeAwareTokenizer().tokenize("ซื้อiPhone") == [ + "ซื้", + "อ", + "iphone", + ] + + +@pytest.mark.parametrize( + "with_punctuation, without", + [ + # Khmer khan ends a sentence the way a full stop does. + ("ទេ។", "ទេ"), + # The Myanmar section sign plays the same role. + ("ဟုတ်ကဲ့။", "ဟုတ်ကဲ့"), + # The Thai baht sign is a currency symbol, not a word. + ("฿100", "100"), + # A separator after a space must not leave an empty token behind. + ("តម្លៃ 100 ។", "តម្លៃ 100"), + ], +) +def test_unicode_aware_tokenizer_drops_unspaced_script_punctuation( + with_punctuation: str, without: str +): + """Punctuation and symbols of these blocks separate words as elsewhere.""" + tokenizer = _UnicodeAwareTokenizer() + assert tokenizer.tokenize(with_punctuation) == tokenizer.tokenize(without) + + +def test_unicode_aware_tokenizer_drops_khmer_and_myanmar_full_stops(): + """The Khmer ។, Myanmar ။ and Thai ฿ characters are never tokens.""" + tokenizer = _UnicodeAwareTokenizer() + assert tokenizer.tokenize("ទេ។") == ["ទេ"] + assert tokenizer.tokenize("฿100") == ["100"] + assert "។" not in tokenizer.tokenize("តម្លៃ។") + assert "။" not in tokenizer.tokenize("ဟုတ်ကဲ့။") + + +@pytest.mark.parametrize( + "char, expected", + [ + ("។", True), # Khmer khan + ("៕", True), # Khmer camnuc pii kuuh + ("၊", True), # Myanmar comma + ("။", True), # Myanmar section sign + ("฿", True), # Thai baht sign + ("๏", True), # Thai fongman + ("ส", False), # Thai letter + ("ี", False), # Thai combining mark + ("๐", False), # Thai digit zero + ("ក", False), # Khmer letter + ("a", False), + ("!", False), # ASCII punctuation is not in these blocks + ], +) +def test_is_script_separator(char: str, expected: bool): + """Tests _is_script_separator for punctuation and symbols of these blocks.""" + assert _is_script_separator(char) == expected + + @pytest.mark.parametrize( "char, expected", [ @@ -424,3 +521,61 @@ def test_rouge_evaluator_ignores_thought_parts(): evaluation_result = rouge_evaluator.evaluate_invocations([actual], [expected]) assert evaluation_result.overall_score == pytest.approx(1.0) + + +@pytest.mark.parametrize( + "answer, reference", + [ + ("ราคา100", "ราคา 100"), + ("ซื้อiPhone", "ซื้อ iPhone"), + ("ລາຄາ100", "ລາຄາ 100"), + ("តម្លៃ100", "តម្លៃ 100"), + ("តម្លៃ 100 ។", "តម្លៃ 100"), + ("ဈေးနှုန်း100", "ဈေးနှုန်း 100"), + ("ទេ។", "ទេ"), + ("ဟုတ်ကဲ့။", "ဟုတ်ကဲ့"), + ("฿100", "100"), + ("价格100", "价格 100"), + ("$100.", "100"), + ], + ids=[ + "thai-digits", + "thai-latin-word", + "lao-digits", + "khmer-digits", + "khmer-trailing-full-stop", + "myanmar-digits", + "khmer-full-stop", + "myanmar-full-stop", + "thai-baht-sign", + "chinese-digits-control", + "ascii-sign-control", + ], +) +def test_rouge_evaluator_ignores_spacing_and_punctuation_of_script_words( + answer: str, reference: str +): + """The same answer written with or without a space or full stop scores 1.0. + + Regression test for issue #8299: ROUGE-1 with the default 0.8 pass mark + failed correct Thai, Lao, Khmer and Myanmar answers that differed from the + reference only in this spacing or in a final full stop. + """ + rouge_evaluator = _create_test_rouge_evaluator(threshold=0.8) + actual, expected = _create_test_invocations(answer, reference) + + evaluation_result = rouge_evaluator.evaluate_invocations([actual], [expected]) + + assert evaluation_result.overall_score == pytest.approx(1.0) + assert evaluation_result.overall_eval_status == EvalStatus.PASSED + + +def test_rouge_evaluator_still_compares_digits_after_script_letters(): + """Closing the cluster must not make different numbers look identical.""" + rouge_evaluator = _create_test_rouge_evaluator(threshold=0.8) + actual, expected = _create_test_invocations("ราคา100", "ราคา 200") + + evaluation_result = rouge_evaluator.evaluate_invocations([actual], [expected]) + + # Four of the five tokens are shared, so the digits are still compared. + assert evaluation_result.overall_score == pytest.approx(4 / 5) diff --git a/tests/unittests/models/test_anthropic_llm.py b/tests/unittests/models/test_anthropic_llm.py index c2aff4e3004..c905e7c7e7c 100644 --- a/tests/unittests/models/test_anthropic_llm.py +++ b/tests/unittests/models/test_anthropic_llm.py @@ -35,6 +35,7 @@ from google.adk.models import anthropic_llm from google.adk.models import AnthropicGenerateContentConfig from google.adk.models.anthropic_llm import _AnthropicRateLimitError +from google.adk.models.anthropic_llm import _ToolUseIdSanitizer from google.adk.models.anthropic_llm import AnthropicLlm from google.adk.models.anthropic_llm import Claude from google.adk.models.anthropic_llm import content_to_message_param @@ -4417,6 +4418,200 @@ async def test_generate_content_async_pairs_invalid_tool_ids( assert set(use_ids) == set(result_ids) +@pytest.mark.parametrize( + "call_id", + [ + pytest.param("call.hivemind:1", id="id-present-but-invalid"), + pytest.param(None, id="id-absent"), + pytest.param("", id="id-empty"), + ], +) +def test_tool_use_id_sanitizer_pairs_id_less_result_with_call( + call_id: str | None, +): + """An ID-less result pairs with a call whose ID was absent or invalid. + + Regression test for issue #8297: a call whose ID was present but invalid was + only recorded in the id mapping, so the paired result that arrived without + an ID got a brand-new fallback and the converted request contained a + tool_result referencing an unknown tool_use_id (HTTP 400). + """ + sanitizer = _ToolUseIdSanitizer() + + assigned_call_id = sanitizer.sanitize( + is_call=True, tool_id=call_id, tool_name="get_weather" + ) + assigned_result_id = sanitizer.sanitize( + is_call=False, tool_id="", tool_name="get_weather" + ) + + assert assigned_call_id == "toolu_fallback_0" + assert re.fullmatch(r"[a-zA-Z0-9_-]+", assigned_call_id) + assert assigned_result_id == assigned_call_id + + +def test_tool_use_id_sanitizer_pairs_multiple_invalid_id_calls_in_order(): + """Several invalid-ID calls pair with ID-less results in call order.""" + sanitizer = _ToolUseIdSanitizer() + call_ids = [ + sanitizer.sanitize(is_call=True, tool_id="bad:1", tool_name="t"), + sanitizer.sanitize(is_call=True, tool_id="bad:2", tool_name="t"), + ] + result_ids = [ + sanitizer.sanitize(is_call=False, tool_id="", tool_name="t"), + sanitizer.sanitize(is_call=False, tool_id="", tool_name="t"), + ] + + assert call_ids == ["toolu_fallback_0", "toolu_fallback_1"] + assert result_ids == call_ids + + +def test_tool_use_id_sanitizer_does_not_let_a_stray_result_be_claimed(): + """A result with an unknown invalid id never becomes a pairing target. + + Only calls are pending: a result whose id was never seen gets a fallback of + its own, so a later ID-less result cannot be paired with it. + """ + sanitizer = _ToolUseIdSanitizer() + stray_result_id = sanitizer.sanitize( + is_call=False, tool_id="bad:9", tool_name="t" + ) + call_id = sanitizer.sanitize(is_call=True, tool_id=None, tool_name="t") + id_less_result_id = sanitizer.sanitize( + is_call=False, tool_id="", tool_name="t" + ) + + assert id_less_result_id == call_id + assert id_less_result_id != stray_result_id + + +def test_tool_use_id_sanitizer_does_not_reclaim_an_answered_call(): + """A call answered through its own invalid ID is not claimed again.""" + sanitizer = _ToolUseIdSanitizer() + invalid_call_id = sanitizer.sanitize( + is_call=True, tool_id="bad:1", tool_name="t" + ) + id_less_call_id = sanitizer.sanitize( + is_call=True, tool_id=None, tool_name="t" + ) + + answered_id = sanitizer.sanitize( + is_call=False, tool_id="bad:1", tool_name="t" + ) + id_less_result_id = sanitizer.sanitize( + is_call=False, tool_id="", tool_name="t" + ) + + assert answered_id == invalid_call_id + assert id_less_result_id == id_less_call_id + assert id_less_result_id != invalid_call_id + + +@pytest.mark.parametrize( + "call_ids, response_ids, expected_unique", + [ + # The mixed form from issue #8297: invalid-but-present call id and a + # result that lost its id entirely. + pytest.param(["call.hivemind:1"], [""], 1, id="invalid-then-id-less"), + pytest.param( + ["bad:1", "bad:2"], + ["", ""], + 2, + id="two-invalid-two-id-less", + ), + pytest.param(["bad:1", None], ["", ""], 2, id="invalid-and-absent"), + pytest.param([None], [""], 1, id="absent-then-id-less-control"), + ], +) +@pytest.mark.asyncio +async def test_generate_content_async_pairs_id_less_results_with_invalid_calls( + call_ids, + response_ids, + expected_unique, + generate_content_response, + generate_llm_response, +): + """Converted requests keep every tool_result pointing at a tool_use.""" + llm = AnthropicLlm(model="") + contents = [ + Content(role="user", parts=[Part.from_text(text="Hi")]), + Content( + role="model", + parts=[ + _make_tool_call_part(f"tool_{i}", cid) + for i, cid in enumerate(call_ids) + ], + ), + Content( + role="user", + parts=[ + _make_tool_response_part(f"tool_{i}", rid) + for i, rid in enumerate(response_ids) + ], + ), + ] + + messages = await _capture_anthropic_messages( + llm, contents, generate_content_response, generate_llm_response + ) + + use_ids = [ + block["id"] + for block in messages[1]["content"] + if block["type"] == "tool_use" + ] + result_ids = [ + block["tool_use_id"] + for block in messages[2]["content"] + if block["type"] == "tool_result" + ] + assert len(set(use_ids)) == expected_unique + assert use_ids == result_ids + for tool_id in use_ids + result_ids: + assert re.fullmatch(r"[a-zA-Z0-9_-]+", tool_id) + + +@pytest.mark.asyncio +async def test_generate_content_async_pairs_id_less_result_across_turns( + generate_content_response, + generate_llm_response, +): + """An invalid call id in one turn pairs with its ID-less result later.""" + llm = AnthropicLlm(model="") + contents = [ + Content(role="user", parts=[Part.from_text(text="Question 1")]), + Content( + role="model", + parts=[_make_tool_call_part("get_weather", "call.hivemind:1")], + ), + Content( + role="user", + parts=[_make_tool_response_part("get_weather", "")], + ), + ] + + messages = await _capture_anthropic_messages( + llm, contents, generate_content_response, generate_llm_response + ) + + use_ids = [ + block["id"] + for message in messages + if message["role"] == "assistant" + for block in message["content"] + if block["type"] == "tool_use" + ] + result_ids = [ + block["tool_use_id"] + for message in messages + if message["role"] == "user" + for block in message["content"] + if block["type"] == "tool_result" + ] + assert len(use_ids) == 1 + assert use_ids == result_ids + + @pytest.mark.asyncio async def test_generate_content_async_multiturn_empty_tool_ids_unique( generate_content_response,