Skip to content
Open
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
42 changes: 39 additions & 3 deletions src/google/adk/evaluation/final_response_match_v1.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand All @@ -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:
Expand Down
84 changes: 57 additions & 27 deletions src/google/adk/models/anthropic_llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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,
Expand All @@ -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(
Expand Down
155 changes: 155 additions & 0 deletions tests/unittests/evaluation/test_final_response_match_v1.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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",
[
Expand Down Expand Up @@ -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)
Loading