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
24 changes: 22 additions & 2 deletions doc/code/scoring/5_tool_call_scorer.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -423,8 +423,8 @@
"not count either.\n",
"\n",
"Stored messages are partial evidence. Hosted tools, several response section\n",
"types, and targets that execute tools themselves leave no output pieces, so the\n",
"scorer returns true or undetermined and never false. `OpenAIResponseTarget`\n",
"types, and targets that execute tools themselves leave no output pieces. For\n",
"subset conditions, the scorer returns true or undetermined and never false. `OpenAIResponseTarget`\n",
"records these pieces when it runs `custom_functions`. Combine it with\n",
"`OtelToolCallScorer` under `TrueFalseScoreAggregator.OR` when trace evidence is\n",
"also available."
Expand All @@ -435,6 +435,26 @@
"id": "15",
"metadata": {},
"source": [
"## Require that nothing else ran\n",
"\n",
"`ToolsCalled` is a subset match: a run that calls the required tools and three\n",
"others satisfies it. Set `exhaustive=True` to ask for an exact match instead, so\n",
"the required tools ran and no other tool did. With no tools, an exhaustive\n",
"condition asks that no tool ran at all, which suits confirmation gates.\n",
"\n",
"The two halves need different evidence. One observed execution of an unnamed\n",
"tool disproves the match, even when acquisition reports `Acquisition.PARTIAL`\n",
"or `Acquisition.ERROR`, provided the event was retained. Confirming it needs\n",
"complete evidence, because only that rules out every other tool. So\n",
"`OtelToolCallScorer` returns true only for complete, fully correlated traces,\n",
"and `MessageToolCallScorer` returns false for a stored execution of an unnamed\n",
"tool and is otherwise undetermined. Use `OtelToolCallScorer` when an exhaustive\n",
"check needs to be able to pass.\n",
"\n",
"```python\n",
"ToolsCalled(tools=(ToolCallRequirement(name=\"read_file\"),), exhaustive=True)\n",
"```\n",
"\n",
"## Require arguments\n",
"\n",
"A `ToolCallRequirement` can also constrain the arguments of the call. Each\n",
Expand Down
24 changes: 22 additions & 2 deletions doc/code/scoring/5_tool_call_scorer.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,13 +295,33 @@ async def local_agent_async(request: httpx.Request) -> httpx.Response:
# not count either.
#
# Stored messages are partial evidence. Hosted tools, several response section
# types, and targets that execute tools themselves leave no output pieces, so the
# scorer returns true or undetermined and never false. `OpenAIResponseTarget`
# types, and targets that execute tools themselves leave no output pieces. For
# subset conditions, the scorer returns true or undetermined and never false. `OpenAIResponseTarget`
# records these pieces when it runs `custom_functions`. Combine it with
# `OtelToolCallScorer` under `TrueFalseScoreAggregator.OR` when trace evidence is
# also available.

# %% [markdown]
# ## Require that nothing else ran
#
# `ToolsCalled` is a subset match: a run that calls the required tools and three
# others satisfies it. Set `exhaustive=True` to ask for an exact match instead, so
# the required tools ran and no other tool did. With no tools, an exhaustive
# condition asks that no tool ran at all, which suits confirmation gates.
#
# The two halves need different evidence. One observed execution of an unnamed
# tool disproves the match, even when acquisition reports `Acquisition.PARTIAL`
# or `Acquisition.ERROR`, provided the event was retained. Confirming it needs
# complete evidence, because only that rules out every other tool. So
# `OtelToolCallScorer` returns true only for complete, fully correlated traces,
# and `MessageToolCallScorer` returns false for a stored execution of an unnamed
# tool and is otherwise undetermined. Use `OtelToolCallScorer` when an exhaustive
# check needs to be able to pass.
#
# ```python
# ToolsCalled(tools=(ToolCallRequirement(name="read_file"),), exhaustive=True)
# ```
#
# ## Require arguments
#
# A `ToolCallRequirement` can also constrain the arguments of the call. Each
Expand Down
21 changes: 16 additions & 5 deletions pyrit/models/score/condition.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,24 +198,35 @@ class ToolCallRequirement(BaseModel):


class ToolsCalled(Condition):
"""Require every named tool to have an execution attempt, regardless of success."""
"""
Require every named tool to have an execution attempt, regardless of success.

By default this is a subset match: other tools may also have run. ``exhaustive`` asks for
an exact match instead, so the named tools ran and no other tool did. An exhaustive
condition with no tools asks that no tool ran at all.

An exhaustive match can be disproved by one observed execution of an unnamed tool, but
confirming it needs evidence complete enough to rule out every other tool.
"""

condition_type: Literal["tools_called"] = "tools_called"
tools: tuple[ToolCallRequirement, ...]
#: Left out of serialization while false, so subset conditions keep their stored form and fingerprint.
exhaustive: bool = Field(default=False, strict=True, exclude_if=lambda value: value is False)

@model_validator(mode="after")
def _validate_tools(self) -> ToolsCalled:
"""
Require a nonempty set of distinct exact names.
Require distinct exact names, and at least one unless the match is exhaustive.

Returns:
ToolsCalled: The validated condition.

Raises:
ValueError: If there are no tools or an exact name repeats.
ValueError: If a subset match names no tools or an exact name repeats.
"""
if not self.tools:
raise ValueError("ToolsCalled requires at least one tool.")
if not self.tools and not self.exhaustive:
raise ValueError("ToolsCalled requires at least one tool unless exhaustive is set.")
names = [tool.name for tool in self.tools]
if len(set(names)) != len(names):
raise ValueError("ToolsCalled requires each tool name once.")
Expand Down
43 changes: 41 additions & 2 deletions pyrit/score/true_false/message_tool_call_scorer.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,13 @@ class MessageToolCallScorer(TrueFalseScorer):
Score tool invocations recorded as function_call and function_call_output message pieces.

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.
when every required tool ran and undetermined otherwise; absence never makes it report false.
Compose it with ``OtelToolCallScorer`` under an OR aggregator when trace evidence is also
available.

An exhaustive condition reverses which verdict the stored messages can support: a stored
execution of a tool the condition does not name disproves it, but stored messages can never
rule out other tools, so it is otherwise undetermined and never true.

A requirement with argument constraints needs one execution whose requested arguments, as
stored in its function_call piece, satisfy every constraint.
Expand Down Expand Up @@ -159,6 +164,8 @@ async def _score_scorable_async(self, *, scorable: Scorable, expectation: Scorin
]
piece_id = self._piece_id_from_scorable(scorable)
names = ", ".join(describe_tool_requirement(tool) for tool in condition.tools)
if condition.exhaustive:
return [self._score_exhaustive(condition=condition, executed=set(calls), scorable=scorable)]
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]
Expand Down Expand Up @@ -190,3 +197,35 @@ async def _score_scorable_async(self, *, scorable: Scorable, expectation: Scorin
message_piece_id=piece_id,
)
]

def _score_exhaustive(self, *, condition: ToolsCalled, executed: set[str], scorable: MessageScorable) -> Score:
"""
Disprove an exact match from a stored execution of an unnamed tool, or leave it open.

Returns:
Score: False when an unnamed tool ran, otherwise undetermined.
"""
piece_id = self._piece_id_from_scorable(scorable)
description = "Tool invocation; successful completion is not required."
extra = sorted(executed - {tool.name for tool in condition.tools})
if extra:
return Score(
score_value="false",
score_type="true_false",
score_rationale=(
"Stored function call outputs show execution of tools outside the required set: "
f"{', '.join(extra)}."
),
score_value_description=description,
scorer_class_identifier=self.get_identifier(),
scorable=scorable,
message_piece_id=piece_id,
)
names = ", ".join(tool.name for tool in condition.tools)
expected = f"exactly the required tools ({names}) ran" if names else "no tool ran"
return self._build_undetermined_score(
rationale=f"Stored messages cannot establish that {expected}. {_INCOMPLETE_EVIDENCE_REASON}",
description=description,
scorable=scorable,
message_piece_id=piece_id,
)
76 changes: 63 additions & 13 deletions pyrit/score/true_false/otel_tool_call_scorer.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,19 +55,62 @@ def match_tools_called(
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.
bool | None: True for observed calls, false for complete absence, otherwise None. An
exhaustive condition is also false when a tool it does not name was observed, and
true only when complete evidence rules out every other tool.
"""
return _match_tools_called(condition=condition, payload=payload, acquisition=acquisition)[0]


def _match_tools_called(
*, condition: ToolsCalled, payload: ToolEventsObservationPayload, acquisition: Acquisition
) -> tuple[bool | None, bool]:
"""
Match execution names and report whether the verdict rests on the absence of other calls.

A verdict that rests on absence is only as good as the evidence is complete, so a caller
that knows of uncorrelated requests must not keep it. A verdict from an observed call holds.

Returns:
tuple[bool | None, bool]: The verdict, and whether it depends on complete evidence.
"""
observed = {event.name for event in payload.events}
required = {tool.name for tool in condition.tools}
if condition.exhaustive and not observed <= required:
return False, False
if acquisition in (Acquisition.ERROR, Acquisition.UNAVAILABLE):
return None
return None, False
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
complete = acquisition is Acquisition.COMPLETE and payload.coverage.complete
return False if complete and any(verdict is False for verdict in verdicts) else None
if all(verdict is True for verdict in verdicts):
if not condition.exhaustive:
return True, False
return (True, True) if complete else (None, False)
return (False, True) if complete and any(verdict is False for verdict in verdicts) else (None, False)


def _rationale(*, condition: ToolsCalled, payload: ToolEventsObservationPayload, value: bool | None) -> str:
"""
Explain a tool-call verdict in terms of the evidence that decided it.

Returns:
str: The rationale.
"""
names = ", ".join(describe_tool_requirement(tool) for tool in condition.tools)
required = {tool.name for tool in condition.tools}
extra = sorted({event.name for event in payload.events} - required)
expected = f"exactly the required tools: {names}" if names else "no tool execution"
if value is True:
return f"Complete trace evidence shows {expected}."
if value is False and extra:
return f"Observed execution of tools outside the required set: {', '.join(extra)}."
if value is False:
return f"Complete trace evidence does not contain all required tools: {names}."
return f"Trace evidence cannot establish {expected}."


class OtelToolCallScorer(TrueFalseScorer):
Expand Down Expand Up @@ -110,10 +153,14 @@ async def _score_scorable_async(self, *, scorable: Scorable, expectation: Scorin
raise ValueError("Trace source returned incompatible evidence or scope.")
_collect_observation(observation)
scores = self._score_observation(observation=observation, evidence=observation.payload, expectation=expectation)
condition = self._get_required_condition(expectation=expectation, condition_type=ToolsCalled)
_, rests_on_absence = _match_tools_called(
condition=condition, payload=observation.payload, acquisition=observation.acquisition
)
for score in scores:
score.scorable = scorable
score.message_piece_id = self._piece_id_from_scorable(scorable)
if not correlation_complete and not score.is_undetermined and score.get_value() is False:
if not correlation_complete and rests_on_absence and not score.is_undetermined:
score.set_value(None)
score.score_rationale = f"{score.score_rationale} {_UNLINKED_REQUESTS_REASON}"
return scores
Expand All @@ -136,13 +183,16 @@ def _score_observation(
"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
else f"Complete trace evidence does not contain all required tools: {names}."
if value is False
else f"Trace evidence cannot establish invocation of all required tools: {names}."
)
if condition.exhaustive:
rationale = _rationale(condition=condition, payload=evidence, value=value)
else:
rationale = (
f"Observed execution of all required tools: {names}."
if value is True
else f"Complete trace evidence does not contain all required tools: {names}."
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 [
Expand Down
42 changes: 42 additions & 0 deletions tests/unit/models/test_condition.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,48 @@ def test_tools_called_requires_nonempty_unique_names(names: list[str]) -> None:
ToolsCalled(tools=tuple(ToolCallRequirement(name=name) for name in names))


def test_subset_tools_called_keeps_its_stored_form_and_fingerprint() -> None:
expectation = ScoringExpectation(
objective="x", conditions=(ToolsCalled(tools=(ToolCallRequirement(name="lookup"),)), MatchesObjective())
)

assert expectation.conditions[0].model_dump(mode="json") == {
"condition_type": "tools_called",
"tools": [{"name": "lookup"}],
}
# Computed on main before ``exhaustive`` existed: stored subset expectations must still match.
assert scoring_expectation_fingerprint(expectation) == (
"09c38ed6d8ab39e973e8ffa1c30690079eaee0acd4df463665eaf3f62d8d482c"
)


@pytest.mark.parametrize("names", [(), ("lookup",), ("lookup", "send")])
def test_exhaustive_tools_called_round_trips(names: tuple[str, ...]) -> None:
condition = ToolsCalled(tools=tuple(ToolCallRequirement(name=name) for name in names), exhaustive=True)
expectation = ScoringExpectation(conditions=(condition,))

assert condition.model_dump(mode="json")["exhaustive"] is True
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=(condition.model_copy(update={"exhaustive": False}),))
)


@pytest.mark.parametrize("value", [1, "true", "yes", None])
def test_exhaustive_flag_is_strict(value: object) -> None:
with pytest.raises(ValidationError):
ToolsCalled.model_validate({"tools": [{"name": "lookup"}], "exhaustive": value})


def test_explicit_false_exhaustive_flag_loads_as_a_subset_match() -> None:
condition = Condition.model_validate(
{"condition_type": "tools_called", "tools": [{"name": "lookup"}], "exhaustive": False}
)

assert condition == ToolsCalled(tools=(ToolCallRequirement(name="lookup"),))


@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"):
Expand Down
Loading
Loading