Skip to content
Merged
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
23 changes: 22 additions & 1 deletion pyrit/analytics/text_matching.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"""

import math
from typing import Protocol
from typing import Any, Protocol


class TextMatching(Protocol):
Expand All @@ -18,6 +18,9 @@ class TextMatching(Protocol):

Classes implementing this protocol must provide an is_match method that
checks if a target string matches text according to some strategy.

Matchers may additionally expose ``get_identifier_params()`` with stable,
JSON-serializable behavioral parameters for use in scorer identifiers.
"""

def is_match(self, *, target: str, text: str) -> bool:
Expand Down Expand Up @@ -52,6 +55,15 @@ def __init__(self, *, case_sensitive: bool = False, ignore_whitespace: bool = Tr
self._case_sensitive = case_sensitive
self._ignore_whitespace = ignore_whitespace

def get_identifier_params(self) -> dict[str, Any]:
"""
Return the configuration that determines matching behavior.

Returns:
dict[str, Any]: Behavioral parameters for scorer identifiers.
"""
return {"case_sensitive": self._case_sensitive, "ignore_whitespace": self._ignore_whitespace}

def is_match(self, *, target: str, text: str) -> bool:
"""
Check if target string is present in text.
Expand Down Expand Up @@ -103,6 +115,15 @@ def __init__(self, *, threshold: float = 0.5, n: int = 3, case_sensitive: bool =
self._n = n
self._case_sensitive = case_sensitive

def get_identifier_params(self) -> dict[str, Any]:
"""
Return the configuration that determines matching behavior.

Returns:
dict[str, Any]: Behavioral parameters for scorer identifiers.
"""
return {"threshold": self._threshold, "n": self._n, "case_sensitive": self._case_sensitive}

def is_match(self, *, target: str, text: str) -> bool:
"""
Check if target approximately matches text using n-gram overlap.
Expand Down
2 changes: 2 additions & 0 deletions pyrit/score/true_false/substring_scorer.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,12 @@ def _build_identifier(self) -> ComponentIdentifier:
Returns:
ComponentIdentifier: The identifier for this scorer.
"""
get_matcher_params = getattr(self._text_matcher, "get_identifier_params", None)
return self._create_identifier(
params={
"substring": self._substring,
"text_matcher": self._text_matcher.__class__.__name__,
"text_matcher_params": get_matcher_params() if callable(get_matcher_params) else None,
},
score_aggregator=self._score_aggregator.__name__, # type: ignore[ty:unresolved-attribute]
)
Expand Down
69 changes: 68 additions & 1 deletion tests/unit/score/test_substring.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,80 @@
import pytest
from unit.mocks import get_image_message_piece, store_message_async

from pyrit.analytics import ApproximateTextMatching, ExactTextMatching
from pyrit.analytics import ApproximateTextMatching, ExactTextMatching, TextMatching
from pyrit.memory.central_memory import CentralMemory
from pyrit.memory.memory_interface import MemoryInterface
from pyrit.models import MatchesObjective, MessagePiece, ScoringExpectation
from pyrit.score import ContentScorable, MessageScorable, Scorer, SubStringScorer


@pytest.mark.parametrize(
"first,second,substring,text",
[
(ExactTextMatching(), ExactTextMatching(case_sensitive=True), "Hello", "hello"),
(ExactTextMatching(), ExactTextMatching(ignore_whitespace=False), " hello ", "hello"),
(ApproximateTextMatching(threshold=0.3), ApproximateTextMatching(threshold=0.5), "hello", "hallo"),
(ApproximateTextMatching(n=2), ApproximateTextMatching(n=3), "hello", "he lo"),
(ApproximateTextMatching(), ApproximateTextMatching(case_sensitive=True), "HELLO", "hello"),
],
)
async def test_substring_identifier_distinguishes_matcher_behavior(
patch_central_database: MemoryInterface, first: TextMatching, second: TextMatching, substring: str, text: str
) -> None:
first_scorer = SubStringScorer(substring=substring, text_matcher=first)
second_scorer = SubStringScorer(substring=substring, text_matcher=second)

first_scores = await first_scorer.score_text_async(text)
second_scores = await second_scorer.score_text_async(text)

assert first_scores[0].get_value() is not second_scores[0].get_value()
assert first_scorer.get_identifier().hash != second_scorer.get_identifier().hash
assert first_scorer.get_identifier().eval_hash != second_scorer.get_identifier().eval_hash


@pytest.mark.parametrize("matcher_class", [ExactTextMatching, ApproximateTextMatching])
def test_substring_identifier_stable_for_equivalent_matchers(
patch_central_database: MemoryInterface, matcher_class: type[ExactTextMatching] | type[ApproximateTextMatching]
) -> None:
first = SubStringScorer(substring="hello", text_matcher=matcher_class())
second = SubStringScorer(substring="hello", text_matcher=matcher_class())

assert first.get_identifier().hash == second.get_identifier().hash
assert first.get_identifier().eval_hash == second.get_identifier().eval_hash


async def test_substring_accepts_custom_matcher_without_identifier_hook(
patch_central_database: MemoryInterface,
) -> None:
class CustomMatcher:
def is_match(self, *, target: str, text: str) -> bool:
return target == text

scorer = SubStringScorer(substring="hello", text_matcher=CustomMatcher())
scores = await scorer.score_text_async("hello")

assert scores[0].get_value() is True
assert scorer.get_identifier().params["text_matcher"] == "CustomMatcher"


def test_substring_custom_matcher_can_supply_identifier_params(patch_central_database: MemoryInterface) -> None:
class CustomMatcher:
def __init__(self, *, case_sensitive: bool) -> None:
self.case_sensitive = case_sensitive

def is_match(self, *, target: str, text: str) -> bool:
return target == text if self.case_sensitive else target.lower() == text.lower()

def get_identifier_params(self) -> dict[str, bool]:
return {"case_sensitive": self.case_sensitive}

first = SubStringScorer(substring="hello", text_matcher=CustomMatcher(case_sensitive=True))
second = SubStringScorer(substring="hello", text_matcher=CustomMatcher(case_sensitive=False))

assert first.get_identifier().hash != second.get_identifier().hash
assert first.get_identifier().eval_hash != second.get_identifier().eval_hash


@pytest.fixture
def image_message_piece() -> MessagePiece:
return get_image_message_piece()
Expand Down
Loading