diff --git a/doc/code/scoring/5_tool_call_scorer.ipynb b/doc/code/scoring/5_tool_call_scorer.ipynb index 012ea178ae..35441880bb 100644 --- a/doc/code/scoring/5_tool_call_scorer.ipynb +++ b/doc/code/scoring/5_tool_call_scorer.ipynb @@ -10,7 +10,8 @@ "`OtelToolCallScorer` answers \"Did these tools run?\" It matches exact,\n", "case-sensitive names in execution spans, not claims in a response or\n", "model-proposed calls. A failed execution attempt counts; the scorer does not\n", - "check tool success, arguments, order, or call count.\n", + "check tool success, arguments, order, or call count. For argument matching, use\n", + "`MessageToolCallScorer` (see \"Require arguments\" below).\n", "\n", "The example tool is named **`my_tool_call`**, implemented by the `my_tool_call()` function\n", "below. Its span records `\"gen_ai.tool.name\": \"my_tool_call\"`.\n", @@ -428,6 +429,36 @@ "`OtelToolCallScorer` under `TrueFalseScoreAggregator.OR` when trace evidence is\n", "also available." ] + }, + { + "cell_type": "markdown", + "id": "15", + "metadata": {}, + "source": [ + "## Require arguments\n", + "\n", + "A `ToolCallRequirement` can also constrain the arguments of the call. Each\n", + "`ToolArgumentRequirement` names one top-level argument, exactly and\n", + "case-sensitively, and compares its value with the same text matchers other\n", + "conditions use: `Equals`, `Contains`, or `Regex`. A string value is compared as\n", + "it is; any other JSON value is compared as its compact JSON text. The match is\n", + "textual, so the string `\"3\"` and the number `3` both read as `3`, as do `\"true\"`\n", + "and `true`, and `\"null\"` and `null`. One execution of the tool must satisfy every\n", + "argument requirement.\n", + "\n", + "```python\n", + "ToolCallRequirement(\n", + " name=\"send_email\",\n", + " arguments=(ToolArgumentRequirement(name=\"to\", matcher=Equals(value=\"a@example.com\")),),\n", + ")\n", + "```\n", + "\n", + "`MessageToolCallScorer` reads the arguments from the stored `function_call`\n", + "piece of each execution. Trace events do not retain arguments, so\n", + "`OtelToolCallScorer` cannot confirm an argument requirement and leaves it\n", + "undetermined. Complete trace evidence with no execution of the tool still makes\n", + "it false, because no call means no matching call." + ] } ], "metadata": { diff --git a/doc/code/scoring/5_tool_call_scorer.py b/doc/code/scoring/5_tool_call_scorer.py index 298ab51dc3..bb33c73554 100644 --- a/doc/code/scoring/5_tool_call_scorer.py +++ b/doc/code/scoring/5_tool_call_scorer.py @@ -14,7 +14,8 @@ # `OtelToolCallScorer` answers "Did these tools run?" It matches exact, # case-sensitive names in execution spans, not claims in a response or # model-proposed calls. A failed execution attempt counts; the scorer does not -# check tool success, arguments, order, or call count. +# check tool success, arguments, order, or call count. For argument matching, use +# `MessageToolCallScorer` (see "Require arguments" below). # # The example tool is named **`my_tool_call`**, implemented by the `my_tool_call()` function # below. Its span records `"gen_ai.tool.name": "my_tool_call"`. @@ -299,3 +300,28 @@ async def local_agent_async(request: httpx.Request) -> httpx.Response: # records these pieces when it runs `custom_functions`. Combine it with # `OtelToolCallScorer` under `TrueFalseScoreAggregator.OR` when trace evidence is # also available. + +# %% [markdown] +# ## Require arguments +# +# A `ToolCallRequirement` can also constrain the arguments of the call. Each +# `ToolArgumentRequirement` names one top-level argument, exactly and +# case-sensitively, and compares its value with the same text matchers other +# conditions use: `Equals`, `Contains`, or `Regex`. A string value is compared as +# it is; any other JSON value is compared as its compact JSON text. The match is +# textual, so the string `"3"` and the number `3` both read as `3`, as do `"true"` +# and `true`, and `"null"` and `null`. One execution of the tool must satisfy every +# argument requirement. +# +# ```python +# ToolCallRequirement( +# name="send_email", +# arguments=(ToolArgumentRequirement(name="to", matcher=Equals(value="a@example.com")),), +# ) +# ``` +# +# `MessageToolCallScorer` reads the arguments from the stored `function_call` +# piece of each execution. Trace events do not retain arguments, so +# `OtelToolCallScorer` cannot confirm an argument requirement and leaves it +# undetermined. Complete trace evidence with no execution of the tool still makes +# it false, because no call means no matching call. diff --git a/pyrit/models/__init__.py b/pyrit/models/__init__.py index 0c5df9cb16..bb4d2d3e37 100644 --- a/pyrit/models/__init__.py +++ b/pyrit/models/__init__.py @@ -264,6 +264,7 @@ SurfaceObservationPayload, SurfaceScorable, TextMatcher, + ToolArgumentRequirement, ToolCallRequirement, ToolEventsObservationPayload, ToolExecution, @@ -562,6 +563,7 @@ "SurfaceMatch": "pyrit.models.score", "SurfaceObservationPayload": "pyrit.models.score", "SurfaceScorable": "pyrit.models.score", + "ToolArgumentRequirement": "pyrit.models.score", "ToolCallRequirement": "pyrit.models.score", "ToolEventsObservationPayload": "pyrit.models.score", "ToolExecution": "pyrit.models.score", diff --git a/pyrit/models/score/__init__.py b/pyrit/models/score/__init__.py index 57adda6077..393ccc81ad 100644 --- a/pyrit/models/score/__init__.py +++ b/pyrit/models/score/__init__.py @@ -25,6 +25,7 @@ ProgramBehaves, ProgramCase, ProgramResult, + ToolArgumentRequirement, ToolCallRequirement, ToolsCalled, ) @@ -112,6 +113,7 @@ "SurfaceMatch": "pyrit.models.score.surface", "SurfaceObservationPayload": "pyrit.models.score.observation", "SurfaceScorable": "pyrit.models.score.scorable", + "ToolArgumentRequirement": "pyrit.models.score.condition", "ToolCallRequirement": "pyrit.models.score.condition", "ToolEventsObservationPayload": "pyrit.models.score.observation", "ToolExecution": "pyrit.models.score.trace", diff --git a/pyrit/models/score/condition.py b/pyrit/models/score/condition.py index af92d35f7c..793a9418f1 100644 --- a/pyrit/models/score/condition.py +++ b/pyrit/models/score/condition.py @@ -166,12 +166,35 @@ class MatchesObjective(Condition): condition_type: Literal["matches_objective"] = "matches_objective" +class ToolArgumentRequirement(BaseModel): + """ + One argument a tool call must have been made with, compared by a text matcher. + + ``name`` is an exact, case-sensitive top-level argument key. A string value is compared + as it is; any other JSON value is compared as its compact JSON text, with sorted keys. + """ + + model_config = ConfigDict(frozen=True, extra="forbid") + + name: str = Field(min_length=1, strict=True) + matcher: TextMatcher + + class ToolCallRequirement(BaseModel): - """One exact, case-sensitive tool name required as execution evidence.""" + """ + One exact, case-sensitive tool name required as execution evidence. + + ``arguments`` optionally narrows the requirement to a call made with matching arguments: + one execution of the tool must satisfy every argument requirement. Evidence that does not + retain a call's arguments cannot show that it does, so it leaves the requirement + undetermined rather than satisfied. + """ model_config = ConfigDict(frozen=True, extra="forbid") name: ToolName + #: Left out of serialization while empty, so name-only requirements keep their stored form and fingerprint. + arguments: tuple[ToolArgumentRequirement, ...] = Field(default=(), exclude_if=lambda value: not value) class ToolsCalled(Condition): diff --git a/pyrit/score/tool_argument_matching.py b/pyrit/score/tool_argument_matching.py new file mode 100644 index 0000000000..4c221e7857 --- /dev/null +++ b/pyrit/score/tool_argument_matching.py @@ -0,0 +1,84 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""Pure evaluation of tool argument requirements against the arguments of one call.""" + +from __future__ import annotations + +import json +from typing import TYPE_CHECKING + +from pyrit.score.text_matching import match_text + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + + from pydantic import JsonValue + + from pyrit.models import ToolCallRequirement + + +def _argument_text(value: JsonValue) -> str: + """ + Render one argument value as the text a matcher compares. + + Returns: + str: The string itself, or the compact JSON text of any other value. + """ + if isinstance(value, str): + return value + return json.dumps(value, ensure_ascii=False, separators=(",", ":"), sort_keys=True) + + +def describe_tool_requirement(requirement: ToolCallRequirement) -> str: + """ + Name a requirement in a rationale, with the arguments it constrains. + + Returns: + str: The tool name, followed by its constrained argument names when there are any. + """ + if not requirement.arguments: + return requirement.name + return f"{requirement.name}({', '.join(argument.name for argument in requirement.arguments)})" + + +def match_tool_arguments(*, requirement: ToolCallRequirement, arguments: Mapping[str, JsonValue] | None) -> bool | None: + """ + Decide whether one call's arguments satisfy every argument requirement. + + A requirement without argument constraints is satisfied by any call. Arguments that were not + retained cannot show a match, so they leave the call undetermined. A missing argument, or one + that does not match, decides the call. + + Returns: + bool | None: True when every constraint matches, false when one fails, otherwise None. + """ + if not requirement.arguments: + return True + if arguments is None: + return None + for constraint in requirement.arguments: + if constraint.name not in arguments: + return False + if not match_text(matcher=constraint.matcher, text=_argument_text(arguments[constraint.name])): + return False + return True + + +def match_tool_requirement( + *, requirement: ToolCallRequirement, calls: Sequence[Mapping[str, JsonValue] | None] +) -> bool | None: + """ + Combine the calls of one tool into a verdict for its requirement. + + One matching call satisfies the requirement. It is refuted only when every call is refuted, + including when there are none; any undetermined call leaves it undetermined. The caller + decides whether its evidence is complete enough to keep a refutation. + + Returns: + bool | None: True when some call matches, false when every call is refuted, otherwise None. + """ + verdicts = [match_tool_arguments(requirement=requirement, arguments=arguments) for arguments in calls] + if True in verdicts: + return True + return None if None in verdicts else False diff --git a/pyrit/score/true_false/message_tool_call_scorer.py b/pyrit/score/true_false/message_tool_call_scorer.py index 8a5e3e5f51..cca0ac301c 100644 --- a/pyrit/score/true_false/message_tool_call_scorer.py +++ b/pyrit/score/true_false/message_tool_call_scorer.py @@ -13,10 +13,11 @@ from pyrit.models import MessageScorable, Score, ToolExecutionMetadata, ToolsCalled from pyrit.models.messages.tool_content import FunctionCallContent, FunctionOutputContent from pyrit.score.message_scorable_resolver import MessageScorableResolver +from pyrit.score.tool_argument_matching import describe_tool_requirement, match_tool_requirement from pyrit.score.true_false.true_false_scorer import TrueFalseScorer if TYPE_CHECKING: - from collections.abc import Iterable + from collections.abc import Iterable, Mapping from pyrit.models import ComponentIdentifier, MessagePiece, Scorable, ScoringExpectation @@ -41,21 +42,23 @@ def _json_object(value: str) -> dict[str, Any] | None: return parsed if isinstance(parsed, dict) else None -def _requested_call(piece: MessagePiece) -> tuple[str, str] | None: +def _requested_call(piece: MessagePiece) -> tuple[str, str, dict[str, Any] | None] | None: """ - Read the call id and function name from a model-authored function_call piece. + Read the call id, function name, and arguments from a model-authored function_call piece. Simulated history is skipped: an injected call is not a request this run made. Returns: - tuple[str, str] | None: The call id and name, or None if the piece is not a readable call. + tuple[str, str, dict[str, Any] | None] | None: The call id, name, and arguments, or None if + the piece is not a readable call. Arguments that are not a JSON object are None. """ if piece.role != "assistant" or piece.converted_value_data_type != "function_call": return None try: # The shared model reads both the Chat Completions and the Responses shapes. content = FunctionCallContent.model_validate_json(piece.converted_value) - return content.validated_call_id(), content.validated_function().name + function = content.validated_function() + return content.validated_call_id(), function.name, _json_object(function.arguments) except (ValidationError, ValueError): return None @@ -85,6 +88,25 @@ def _executed_call_id(piece: MessagePiece) -> str | None: return content.call_id +def _executed_message_tool_calls(*, pieces: Iterable[MessagePiece]) -> list[tuple[str, dict[str, Any] | None]]: + """ + Return each function call that ran, pairing each request with its output by call id. + + Returns: + list[tuple[str, dict[str, Any] | None]]: The name and requested arguments of each execution. + """ + requested: dict[str, tuple[str, dict[str, Any] | None]] = {} + executed: list[tuple[str, dict[str, Any] | None]] = [] + # Walking in sequence order means an output only pairs with a request made before it. + for piece in sorted(pieces, key=lambda piece: piece.sequence): + if (call := _requested_call(piece)) is not None: + call_id, name, arguments = call + requested.setdefault(call_id, (name, arguments)) + elif (call_id := _executed_call_id(piece)) is not None and call_id in requested: + executed.append(requested[call_id]) + return executed + + def match_message_tool_calls(*, pieces: Iterable[MessagePiece]) -> set[str]: """ Return the names of functions that ran, pairing each request with its output by call id. @@ -95,15 +117,7 @@ def match_message_tool_calls(*, pieces: Iterable[MessagePiece]) -> set[str]: Returns: set[str]: Names of functions with an execution attempt in the given pieces. """ - requested: dict[str, str] = {} - executed: set[str] = set() - # Walking in sequence order means an output only pairs with a request made before it. - for piece in sorted(pieces, key=lambda piece: piece.sequence): - if (call := _requested_call(piece)) is not None: - requested.setdefault(*call) - elif (call_id := _executed_call_id(piece)) is not None and call_id in requested: - executed.add(requested[call_id]) - return executed + return {name for name, _ in _executed_message_tool_calls(pieces=pieces)} class MessageToolCallScorer(TrueFalseScorer): @@ -113,6 +127,9 @@ class MessageToolCallScorer(TrueFalseScorer): This scorer needs no trace pipeline. Stored messages are partial evidence, so it reports true when every required tool ran and undetermined otherwise; it never reports false. Compose it with ``OtelToolCallScorer`` under an OR aggregator when trace evidence is also available. + + A requirement with argument constraints needs one execution whose requested arguments, as + stored in its function_call piece, satisfy every constraint. """ SUPPORTED_SCORABLE_TYPES = (MessageScorable,) @@ -130,16 +147,33 @@ async def _score_scorable_async(self, *, scorable: Scorable, expectation: Scorin if not piece.conversation_id or piece.sequence < 0: raise ValueError("Message tool-call scoring requires a stored conversation and message sequence.") conversation = await self._memory.get_message_pieces_async(conversation_id=piece.conversation_id) - executed = match_message_tool_calls(pieces=(p for p in conversation if p.sequence <= piece.sequence)) - missing = [tool.name for tool in condition.tools if tool.name not in executed] + calls: dict[str, list[Mapping[str, Any] | None]] = {} + for name, arguments in _executed_message_tool_calls( + pieces=(p for p in conversation if p.sequence <= piece.sequence) + ): + calls.setdefault(name, []).append(arguments) + unmet = [ + tool + for tool in condition.tools + if match_tool_requirement(requirement=tool, calls=calls.get(tool.name, [])) is not True + ] piece_id = self._piece_id_from_scorable(scorable) - names = ", ".join(tool.name for tool in condition.tools) - if missing: + names = ", ".join(describe_tool_requirement(tool) for tool in condition.tools) + if unmet: + # A tool that ran with other arguments did run, so say so rather than report no execution. + not_run = [describe_tool_requirement(tool) for tool in unmet if tool.name not in calls] + unmatched = [describe_tool_requirement(tool) for tool in unmet if tool.name in calls] + reasons = [] + if not_run: + reasons.append(f"Stored messages show no execution of: {', '.join(not_run)}.") + if unmatched: + reasons.append( + f"Stored messages show execution of {', '.join(unmatched)}, but no stored call matches " + "the required arguments." + ) return [ self._build_undetermined_score( - rationale=( - f"Stored messages show no execution of: {', '.join(missing)}. {_INCOMPLETE_EVIDENCE_REASON}" - ), + rationale=" ".join([*reasons, _INCOMPLETE_EVIDENCE_REASON]), description="Tool invocation; successful completion is not required.", scorable=scorable, message_piece_id=piece_id, diff --git a/pyrit/score/true_false/otel_tool_call_scorer.py b/pyrit/score/true_false/otel_tool_call_scorer.py index 72d2556eb3..43493e9ec2 100644 --- a/pyrit/score/true_false/otel_tool_call_scorer.py +++ b/pyrit/score/true_false/otel_tool_call_scorer.py @@ -5,6 +5,7 @@ from __future__ import annotations +import logging from typing import TYPE_CHECKING from pyrit.models import ( @@ -19,13 +20,25 @@ ) from pyrit.score.observation.execution import NonReplayableObservationError, _collect_observation from pyrit.score.observation.message_trace_resolver import resolve_message_trace_scope_async +from pyrit.score.tool_argument_matching import describe_tool_requirement, match_tool_requirement from pyrit.score.true_false.true_false_scorer import TrueFalseScorer if TYPE_CHECKING: + from collections.abc import Mapping + + from pydantic import JsonValue + from pyrit.models import ComponentIdentifier, Scorable, ScoringExpectation from pyrit.score.observation.execution import _ObservationEvidence from pyrit.score.observation.observation_source import ObservationSource +logger = logging.getLogger(__name__) + +_NO_TRACE_ARGUMENTS_REASON = ( + "Trace evidence does not retain tool arguments, so it cannot confirm an argument requirement; " + "use MessageToolCallScorer to match arguments." +) + _UNLINKED_REQUESTS_REASON = ( "One or more requests in this conversation carry no trace link, so tool calls outside the " "correlated traces cannot be ruled out." @@ -36,17 +49,25 @@ def match_tools_called( *, condition: ToolsCalled, payload: ToolEventsObservationPayload, acquisition: Acquisition ) -> bool | None: """ - Match execution names without I/O, preserving unknown absence. + Match executions without I/O, preserving unknown absence. + + A requirement with argument constraints needs an execution whose retained arguments match. + Its absence can still be refuted from complete evidence, because no call means no matching call. Returns: bool | None: True for observed calls, false for complete absence, otherwise None. """ if acquisition in (Acquisition.ERROR, Acquisition.UNAVAILABLE): return None - observed = {event.name for event in payload.events} - if all(tool.name in observed for tool in condition.tools): + calls: dict[str, list[Mapping[str, JsonValue] | None]] = {} + for event in payload.events: + # Trace events do not retain arguments, so they cannot confirm an argument requirement. + calls.setdefault(event.name, []).append(None) + verdicts = [match_tool_requirement(requirement=tool, calls=calls.get(tool.name, [])) for tool in condition.tools] + if all(verdict is True for verdict in verdicts): return True - return False if acquisition is Acquisition.COMPLETE and payload.coverage.complete else None + complete = acquisition is Acquisition.COMPLETE and payload.coverage.complete + return False if complete and any(verdict is False for verdict in verdicts) else None class OtelToolCallScorer(TrueFalseScorer): @@ -108,7 +129,13 @@ def _score_observation( raise NonReplayableObservationError("Tool-call scoring requires a stored tool-event observation.") condition = self._get_required_condition(expectation=expectation, condition_type=ToolsCalled) value = match_tools_called(condition=condition, payload=evidence, acquisition=observation.acquisition) - names = ", ".join(tool.name for tool in condition.tools) + names = ", ".join(describe_tool_requirement(tool) for tool in condition.tools) + constrains_arguments = any(tool.arguments for tool in condition.tools) + if constrains_arguments: + logger.warning( + "OtelToolCallScorer received a requirement with argument constraints, which trace evidence " + "cannot confirm. Use MessageToolCallScorer to match arguments." + ) rationale = ( f"Observed execution of all required tools: {names}." if value is True @@ -116,6 +143,8 @@ def _score_observation( if value is False else f"Trace evidence cannot establish invocation of all required tools: {names}." ) + if value is None and constrains_arguments: + rationale = f"{rationale} {_NO_TRACE_ARGUMENTS_REASON}" return [ Score( score_value=None if value is None else str(value).lower(), diff --git a/tests/unit/models/test_condition.py b/tests/unit/models/test_condition.py index e4683dbf91..3d66e32b17 100644 --- a/tests/unit/models/test_condition.py +++ b/tests/unit/models/test_condition.py @@ -8,9 +8,12 @@ from pyrit.models import ( Condition, + Contains, DivergesFromRepetition, + Equals, MatchesObjective, ScoringExpectation, + ToolArgumentRequirement, ToolCall, ToolCallRequirement, ToolsCalled, @@ -145,12 +148,104 @@ def test_tools_called_requires_nonempty_unique_names(names: list[str]) -> None: ToolsCalled(tools=tuple(ToolCallRequirement(name=name) for name in names)) -@pytest.mark.parametrize("field", ["arguments", "count", "order", "success"]) +@pytest.mark.parametrize("field", ["count", "order", "success"]) def test_tool_call_requirement_rejects_unsupported_matching_fields(field: str) -> None: with pytest.raises(ValidationError, match="Extra inputs"): ToolCallRequirement.model_validate({"name": "lookup", field: True}) +def test_name_only_tool_requirements_keep_their_stored_form_and_fingerprint() -> None: + expectation = ScoringExpectation( + conditions=(ToolsCalled(tools=(ToolCallRequirement(name="send_email"), ToolCallRequirement(name="lookup"))),) + ) + + assert expectation.conditions[0].model_dump(mode="json") == { + "condition_type": "tools_called", + "tools": [{"name": "send_email"}, {"name": "lookup"}], + } + # Computed on main before ``arguments`` existed: stored name-only expectations must still match. + assert scoring_expectation_fingerprint(expectation) == ( + "2f8d57c5e555a94728407772ef10e245c81902a4849d5576e7b0e9ddae4daab6" + ) + + +def test_explicit_empty_arguments_load_as_a_name_only_requirement() -> None: + condition = Condition.model_validate( + {"condition_type": "tools_called", "tools": [{"name": "lookup", "arguments": []}]} + ) + + assert condition == ToolsCalled(tools=(ToolCallRequirement(name="lookup"),)) + + +def test_argument_requirements_round_trip_through_persistence() -> None: + requirement = ToolCallRequirement( + name="send_email", + arguments=( + ToolArgumentRequirement(name="to", matcher=Equals(value="a@example.com")), + ToolArgumentRequirement(name="body", matcher=Contains(value="invoice", case_sensitive=True)), + ), + ) + condition = ToolsCalled(tools=(requirement,)) + expectation = ScoringExpectation(conditions=(condition,)) + + assert condition.model_dump(mode="json")["tools"][0]["arguments"] == [ + { + "name": "to", + "matcher": { + "value": "a@example.com", + "case_sensitive": False, + "ignore_whitespace": True, + "matcher_type": "equals", + }, + }, + { + "name": "body", + "matcher": { + "value": "invoice", + "case_sensitive": True, + "ignore_whitespace": True, + "matcher_type": "contains", + }, + }, + ] + assert Condition.model_validate(condition.model_dump(mode="json")) == condition + assert ScoringExpectation.model_validate_persisted(expectation.model_dump(mode="json")) == expectation + assert scoring_expectation_fingerprint(expectation) != scoring_expectation_fingerprint( + ScoringExpectation(conditions=(ToolsCalled(tools=(ToolCallRequirement(name="send_email"),)),)) + ) + + +@pytest.mark.parametrize( + "argument", + [ + {"name": "", "matcher": {"matcher_type": "equals", "value": "x"}}, + {"name": 3, "matcher": {"matcher_type": "equals", "value": "x"}}, + {"name": "to"}, + {"name": "to", "matcher": {"matcher_type": "glob", "value": "x"}}, + {"name": "to", "matcher": {"matcher_type": "equals", "value": "x"}, "redacted": True}, + ], +) +def test_tool_argument_requirement_rejects_invalid_input(argument: dict[str, object]) -> None: + with pytest.raises(ValidationError): + ToolCallRequirement.model_validate({"name": "send_email", "arguments": [argument]}) + + +@pytest.mark.parametrize("arguments", [True, "to", {"to": "a@example.com"}]) +def test_tool_call_requirement_rejects_unstructured_arguments(arguments: object) -> None: + with pytest.raises(ValidationError): + ToolCallRequirement.model_validate({"name": "lookup", "arguments": arguments}) + + +def test_tools_called_schema_describes_argument_requirements() -> None: + definitions = ScoringExpectation.model_json_schema()["$defs"] + + assert definitions["ToolCallRequirement"]["required"] == ["name"] + assert definitions["ToolCallRequirement"]["properties"]["arguments"]["items"] == { + "$ref": "#/$defs/ToolArgumentRequirement" + } + assert set(definitions["ToolArgumentRequirement"]["required"]) == {"name", "matcher"} + + def test_tool_conditions_are_immutable() -> None: requirement = ToolCallRequirement(name="lookup") condition = ToolsCalled(tools=(requirement,)) diff --git a/tests/unit/score/test_message_tool_call_scorer.py b/tests/unit/score/test_message_tool_call_scorer.py index 4986c75635..f45f5aacde 100644 --- a/tests/unit/score/test_message_tool_call_scorer.py +++ b/tests/unit/score/test_message_tool_call_scorer.py @@ -14,11 +14,13 @@ from pyrit.models import ( AttackOutcome, ContentScorable, + Equals, Message, MessagePiece, MessageScorable, ScoreStatus, ScoringExpectation, + ToolArgumentRequirement, ToolCallRequirement, ToolExecutionMetadata, ToolsCalled, @@ -281,6 +283,115 @@ async def test_every_required_tool_must_run_async(sqlite_instance: SQLiteMemory) assert (await _score(full, "lookup", "summarize")).get_value() is True +def _send_email(call_format, call_id: str, arguments: object) -> dict: + call = call_format(call_id, "send_email") + text = arguments if isinstance(arguments, str) else json.dumps(arguments) + if "function" in call: + call["function"]["arguments"] = text + else: + call["arguments"] = text + return call + + +def _argument_expectation(**matchers: str) -> ScoringExpectation: + arguments = tuple( + ToolArgumentRequirement(name=name, matcher=Equals(value=value)) for name, value in matchers.items() + ) + return ScoringExpectation( + conditions=(ToolsCalled(tools=(ToolCallRequirement(name="send_email", arguments=arguments),)),) + ) + + +async def _score_arguments(message: Message, **matchers: str): + scorer = MessageToolCallScorer() + scores = await scorer.score_async( + scorable=MessageScorable.from_message(message), expectation=_argument_expectation(**matchers) + ) + assert len(scores) == 1 + return scores[0] + + +@pytest.mark.parametrize("call_format", [_responses_call, _chat_completions_call]) +async def test_executed_call_with_matching_arguments_is_true_async(sqlite_instance: SQLiteMemory, call_format) -> None: + conversation = await _Conversation.create_async(memory=sqlite_instance) + await conversation.call_async(_send_email(call_format, "call_1", {"to": "a@example.com", "subject": "hi"})) + await conversation.output_async("call_1") + reply = await conversation.reply_async() + + score = await _score_arguments(reply, to="a@example.com") + + assert score.get_value() is True + assert "send_email(to)" in score.score_rationale + + +@pytest.mark.parametrize("call_format", [_responses_call, _chat_completions_call]) +@pytest.mark.parametrize("arguments", [{"to": "b@example.com"}, {"cc": "a@example.com"}, {}, "not json", "[1]"]) +async def test_executed_call_without_matching_arguments_is_undetermined_not_false_async( + sqlite_instance: SQLiteMemory, call_format, arguments: object +) -> None: + conversation = await _Conversation.create_async(memory=sqlite_instance) + await conversation.call_async(_send_email(call_format, "call_1", arguments)) + await conversation.output_async("call_1") + reply = await conversation.reply_async() + + score = await _score_arguments(reply, to="a@example.com") + + assert score.status == ScoreStatus.UNDETERMINED + assert score.score_value is None + assert "send_email(to)" in score.score_rationale + # The tool ran, so the rationale must not report that it did not. + assert "show execution of send_email(to), but no stored call matches the required arguments" in ( + score.score_rationale + ) + assert "no execution of" not in score.score_rationale + + +async def test_a_tool_that_never_ran_is_reported_as_not_executed_async(sqlite_instance: SQLiteMemory) -> None: + conversation = await _Conversation.create_async(memory=sqlite_instance) + reply = await conversation.reply_async() + + score = await _score_arguments(reply, to="a@example.com") + + assert score.status == ScoreStatus.UNDETERMINED + assert "Stored messages show no execution of: send_email(to)." in score.score_rationale + assert "required arguments" not in score.score_rationale + + +async def test_one_matching_execution_among_several_is_enough_async(sqlite_instance: SQLiteMemory) -> None: + conversation = await _Conversation.create_async(memory=sqlite_instance) + await conversation.call_async(_send_email(_responses_call, "call_1", {"to": "b@example.com"})) + await conversation.output_async("call_1") + await conversation.call_async(_send_email(_responses_call, "call_2", {"to": "a@example.com"})) + await conversation.output_async("call_2") + + assert (await _score_arguments(await conversation.reply_async(), to="a@example.com")).get_value() is True + + +async def test_argument_requirements_must_match_within_one_execution_async(sqlite_instance: SQLiteMemory) -> None: + conversation = await _Conversation.create_async(memory=sqlite_instance) + await conversation.call_async(_send_email(_responses_call, "call_1", {"to": "a@example.com", "subject": "no"})) + await conversation.output_async("call_1") + await conversation.call_async(_send_email(_responses_call, "call_2", {"to": "b@example.com", "subject": "hi"})) + await conversation.output_async("call_2") + reply = await conversation.reply_async() + + assert (await _score_arguments(reply, to="a@example.com", subject="hi")).status == ScoreStatus.UNDETERMINED + assert (await _score_arguments(reply, to="b@example.com", subject="hi")).get_value() is True + + +async def test_arguments_of_a_requested_call_that_did_not_run_are_not_evidence_async( + sqlite_instance: SQLiteMemory, +) -> None: + conversation = await _Conversation.create_async(memory=sqlite_instance) + await conversation.call_async(_send_email(_responses_call, "call_1", {"to": "a@example.com"})) + await conversation.call_async(_send_email(_responses_call, "call_2", {"to": "b@example.com"})) + await conversation.output_async("call_2") + reply = await conversation.reply_async() + + assert (await _score_arguments(reply, to="a@example.com")).status == ScoreStatus.UNDETERMINED + assert (await _score_arguments(reply, to="b@example.com")).get_value() is True + + async def test_tool_names_match_exactly_async(sqlite_instance: SQLiteMemory) -> None: conversation = await _Conversation.create_async(memory=sqlite_instance) await conversation.call_async(_responses_call("call_1", "Lookup")) diff --git a/tests/unit/score/test_otel_tool_call_scorer.py b/tests/unit/score/test_otel_tool_call_scorer.py index 86d53b37af..7538c6007e 100644 --- a/tests/unit/score/test_otel_tool_call_scorer.py +++ b/tests/unit/score/test_otel_tool_call_scorer.py @@ -21,9 +21,11 @@ Acquisition, ComponentIdentifier, ContentScorable, + Equals, MessageScorable, Score, ScoringExpectation, + ToolArgumentRequirement, ToolCallRequirement, ToolsCalled, TraceCoverage, @@ -198,6 +200,96 @@ async def test_name_matching_is_case_sensitive_and_requires_all_tools_async() -> ].get_value() is False +def _argument_expectation(*names: str, to: str = "a@example.com") -> ScoringExpectation: + tools = [ + ToolCallRequirement( + name="send_email", arguments=(ToolArgumentRequirement(name="to", matcher=Equals(value=to)),) + ), + *(ToolCallRequirement(name=name) for name in names), + ] + return ScoringExpectation(conditions=(ToolsCalled(tools=tuple(tools)),)) + + +async def test_name_only_requirement_gets_no_argument_note_or_warning_async(caplog: pytest.LogCaptureFixture) -> None: + client = InMemoryTraceClient() + client.add_span(_span(name="lookup")) + scorer = OtelToolCallScorer(source=OtelTraceSource(trace_client=client)) + + with caplog.at_level("WARNING"): + score = ( + await scorer.score_async(scorable=TraceScorable(trace_ids=("1" * 32,)), expectation=_expectation("other")) + )[0] + + assert score.is_undetermined + assert "retain tool arguments" not in score.score_rationale + assert "argument constraints" not in caplog.text + + +@pytest.mark.parametrize("complete", [False, True]) +async def test_name_only_trace_evidence_cannot_confirm_an_argument_requirement_async( + sqlite_instance: SQLiteMemory, complete: bool, caplog: pytest.LogCaptureFixture +) -> None: + client = InMemoryTraceClient() + span = _span(name="send_email") + span.attributes["gen_ai.tool.call.arguments"] = '{"to": "a@example.com"}' + client.add_span(span) + if complete: + client.mark_complete(trace_ids=(span.trace_id,)) + scorer = OtelToolCallScorer(source=OtelTraceSource(trace_client=client)) + + with caplog.at_level("WARNING"): + score = ( + await scorer.score_async( + scorable=TraceScorable(trace_ids=(span.trace_id,)), expectation=_argument_expectation() + ) + )[0] + + assert score.is_undetermined + assert "send_email(to)" in score.score_rationale + # The rationale says why, so a user is not left to guess that traces drop arguments. + assert "Trace evidence does not retain tool arguments" in score.score_rationale + assert "MessageToolCallScorer" in score.score_rationale + assert "argument constraints, which trace evidence cannot confirm" in caplog.text + observation = (await sqlite_instance.get_observations_async(observation_ids=score.observation_ids))[0] + assert "a@example.com" not in observation.model_dump_json() + client.close() + replay = (await scorer.score_observation_async(observation=observation, expectation=_argument_expectation()))[0] + assert replay.is_undetermined + + +@pytest.mark.parametrize(("complete", "expected"), [(False, None), (True, False)]) +async def test_complete_absence_still_refutes_an_argument_requirement_async( + complete: bool, expected: bool | None +) -> None: + client = InMemoryTraceClient() + client.add_span(_span(name="lookup")) + if complete: + client.mark_complete(trace_ids=("1" * 32,)) + scorer = OtelToolCallScorer(source=OtelTraceSource(trace_client=client)) + + score = ( + await scorer.score_async( + scorable=TraceScorable(trace_ids=("1" * 32,)), expectation=_argument_expectation("lookup") + ) + )[0] + + assert score.score_value == (None if expected is None else str(expected).lower()) + assert "send_email(to), lookup" in score.score_rationale + + +async def test_absent_name_only_tool_refutes_alongside_an_undetermined_argument_requirement_async() -> None: + client = InMemoryTraceClient() + client.add_span(_span(name="send_email")) + client.mark_complete(trace_ids=("1" * 32,)) + scorer = OtelToolCallScorer(source=OtelTraceSource(trace_client=client)) + scope = TraceScorable(trace_ids=("1" * 32,)) + + assert (await scorer.score_async(scorable=scope, expectation=_argument_expectation("lookup")))[ + 0 + ].get_value() is False + assert (await scorer.score_async(scorable=scope, expectation=_argument_expectation()))[0].is_undetermined + + @pytest.mark.parametrize( "scorable", [ContentScorable(value="I called lookup")], diff --git a/tests/unit/score/test_tool_argument_matching.py b/tests/unit/score/test_tool_argument_matching.py new file mode 100644 index 0000000000..24a05af07b --- /dev/null +++ b/tests/unit/score/test_tool_argument_matching.py @@ -0,0 +1,110 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import pytest +from pydantic import JsonValue + +from pyrit.models import Contains, Equals, Regex, TextMatcher, ToolArgumentRequirement, ToolCallRequirement +from pyrit.score.tool_argument_matching import ( + describe_tool_requirement, + match_tool_arguments, + match_tool_requirement, +) + + +def _requirement(**matchers: TextMatcher) -> ToolCallRequirement: + return ToolCallRequirement( + name="send_email", + arguments=tuple(ToolArgumentRequirement(name=name, matcher=matcher) for name, matcher in matchers.items()), + ) + + +@pytest.mark.parametrize("arguments", [None, {}, {"to": "a@example.com"}]) +def test_name_only_requirement_matches_any_call(arguments: dict[str, JsonValue] | None) -> None: + assert match_tool_arguments(requirement=ToolCallRequirement(name="send_email"), arguments=arguments) is True + + +def test_arguments_that_were_not_retained_cannot_decide_a_call() -> None: + assert match_tool_arguments(requirement=_requirement(to=Equals(value="a@example.com")), arguments=None) is None + + +@pytest.mark.parametrize( + ("arguments", "expected"), + [ + ({"to": "a@example.com", "body": "Your invoice"}, True), + ({"to": "A@Example.com ", "body": "invoice attached"}, True), + ({"to": "b@example.com", "body": "Your invoice"}, False), + ({"to": "a@example.com", "body": "hello"}, False), + ({"to": "a@example.com"}, False), + ({}, False), + ], +) +def test_every_argument_requirement_must_match_one_call(arguments: dict[str, JsonValue], expected: bool) -> None: + requirement = _requirement(to=Equals(value="a@example.com"), body=Contains(value="invoice")) + + assert match_tool_arguments(requirement=requirement, arguments=arguments) is expected + + +def test_argument_names_match_exactly() -> None: + requirement = _requirement(to=Equals(value="a@example.com")) + + assert match_tool_arguments(requirement=requirement, arguments={"To": "a@example.com"}) is False + assert match_tool_arguments(requirement=requirement, arguments={" to": "a@example.com"}) is False + + +@pytest.mark.parametrize( + ("value", "text"), + [ + (3, "3"), + (1.5, "1.5"), + (True, "true"), + (None, "null"), + (["a", "b"], '["a","b"]'), + ({"b": 1, "a": "\u00e9"}, '{"a":"\u00e9","b":1}'), + ], +) +def test_non_string_values_compare_as_compact_json(value: JsonValue, text: str) -> None: + requirement = _requirement(value=Equals(value=text, case_sensitive=True, ignore_whitespace=False)) + + assert match_tool_arguments(requirement=requirement, arguments={"value": value}) is True + + +def test_a_json_string_is_not_its_quoted_form() -> None: + requirement = _requirement(count=Equals(value='"3"')) + + assert match_tool_arguments(requirement=requirement, arguments={"count": "3"}) is False + assert match_tool_arguments(requirement=requirement, arguments={"count": 3}) is False + + +def test_regex_matcher_searches_the_argument_text() -> None: + requirement = _requirement(to=Regex(value=r"@example\.com$")) + + assert match_tool_arguments(requirement=requirement, arguments={"to": "x@example.com"}) is True + assert match_tool_arguments(requirement=requirement, arguments={"to": "x@example.org"}) is False + + +@pytest.mark.parametrize( + ("calls", "expected"), + [ + ([], False), + ([{"to": "b@example.com"}], False), + ([{"to": "b@example.com"}, {"to": "a@example.com"}], True), + ([None], None), + ([{"to": "b@example.com"}, None], None), + ([None, {"to": "a@example.com"}], True), + ], +) +def test_one_matching_call_satisfies_a_requirement( + calls: list[dict[str, JsonValue] | None], expected: bool | None +) -> None: + requirement = _requirement(to=Equals(value="a@example.com")) + + assert match_tool_requirement(requirement=requirement, calls=calls) is expected + + +def test_requirement_description_names_constrained_arguments() -> None: + assert describe_tool_requirement(ToolCallRequirement(name="lookup")) == "lookup" + assert ( + describe_tool_requirement(_requirement(to=Equals(value="x"), body=Contains(value="y"))) + == "send_email(to, body)" + )