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
16 changes: 15 additions & 1 deletion doc/code/scoring/5_tool_call_scorer.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -642,11 +642,25 @@
"```\n",
"\n",
"`MessageToolCallScorer` reads the arguments from the stored `function_call`\n",
"piece of each execution. Trace events do not retain arguments, so\n",
"piece of each execution. `OtelTraceSource` keeps no arguments by default, 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.\n",
"\n",
"To match arguments from traces, name the arguments the source may keep:\n",
"\n",
"```python\n",
"OtelTraceSource(trace_client=client, kept_arguments=(\"to\",))\n",
"```\n",
"\n",
"The source reads each span's `gen_ai.tool.call.arguments` attribute, keeps the\n",
"named top-level arguments, and redacts the rest before the evidence is stored.\n",
"A redacted argument is unknown, not absent: a requirement on it can neither\n",
"confirm nor refute a call, so the score stays undetermined even when the trace\n",
"evidence is complete, and the rationale names the arguments the source did not\n",
"keep. A kept argument that the call lacks, or whose value does not match, still\n",
"refutes the call.\n",
"\n",
"## Let a scenario choose the tool-call scorer\n",
"\n",
"A scenario that takes a `CompatibleScorers` pool, such as `RapidResponse`, picks a scorer for\n",
Expand Down
16 changes: 15 additions & 1 deletion doc/code/scoring/5_tool_call_scorer.py
Original file line number Diff line number Diff line change
Expand Up @@ -467,11 +467,25 @@ def trace_backend(request: httpx.Request) -> httpx.Response:
# ```
#
# `MessageToolCallScorer` reads the arguments from the stored `function_call`
# piece of each execution. Trace events do not retain arguments, so
# piece of each execution. `OtelTraceSource` keeps no arguments by default, 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.
#
# To match arguments from traces, name the arguments the source may keep:
#
# ```python
# OtelTraceSource(trace_client=client, kept_arguments=("to",))
# ```
#
# The source reads each span's `gen_ai.tool.call.arguments` attribute, keeps the
# named top-level arguments, and redacts the rest before the evidence is stored.
# A redacted argument is unknown, not absent: a requirement on it can neither
# confirm nor refute a call, so the score stays undetermined even when the trace
# evidence is complete, and the rationale names the arguments the source did not
# keep. A kept argument that the call lacks, or whose value does not match, still
# refutes the call.
#
# ## Let a scenario choose the tool-call scorer
#
# A scenario that takes a `CompatibleScorers` pool, such as `RapidResponse`, picks a scorer for
Expand Down
18 changes: 15 additions & 3 deletions pyrit/models/score/observation.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,12 @@ def _validate_references(self) -> ConversationObservationPayload:


class ToolEventsObservationPayload(BaseModel):
"""An immutable allowlisted tool snapshot, with arguments and results not retained."""
"""
An immutable allowlisted tool snapshot, with raw arguments and results not retained.

``kept_arguments`` names the arguments the source kept at write time. Every other argument
was redacted, so a matcher treats it as unknown, never as absent.
"""

model_config = ConfigDict(frozen=True, extra="forbid")

Expand All @@ -317,6 +322,8 @@ class ToolEventsObservationPayload(BaseModel):
events: tuple[ToolExecution, ...] = ()
coverage: TraceCoverage = Field(default_factory=TraceCoverage)
arguments_retained: Literal[False] = False
#: Left out of serialization while empty, so name-only snapshots keep their stored form.
kept_arguments: tuple[str, ...] = Field(default=(), exclude_if=lambda value: not value)

@field_validator("arguments_retained", mode="before")
@classmethod
Expand All @@ -331,7 +338,7 @@ def _validate_arguments_retained(cls, value: object) -> Literal[False]:
ValueError: If the marker is not exactly false.
"""
if value is not False:
raise ValueError("Tool payload arguments_retained must be false; arguments are not captured.")
raise ValueError("Tool payload arguments_retained must be false; raw arguments are not captured.")
return False

@field_validator("schema_version", mode="before")
Expand Down Expand Up @@ -359,7 +366,7 @@ def _validate_scope_and_events(self) -> ToolEventsObservationPayload:
ToolEventsObservationPayload: The validated snapshot.

Raises:
ValueError: If identities, scope, or completeness are inconsistent.
ValueError: If identities, scope, completeness, or kept arguments are inconsistent.
"""
identities = [(event.trace_id, event.span_id) for event in self.events]
if len(set(identities)) != len(identities):
Expand All @@ -368,6 +375,11 @@ def _validate_scope_and_events(self) -> ToolEventsObservationPayload:
raise ValueError("Tool events must belong to the declared trace scope.")
if self.coverage.complete and any(event.end_time is None for event in self.events):
raise ValueError("Complete coverage cannot contain unfinished tool events.")
if any(not name for name in self.kept_arguments) or len(set(self.kept_arguments)) != len(self.kept_arguments):
raise ValueError("Kept tool arguments must be distinct, nonempty names.")
kept = set(self.kept_arguments)
if any(event.arguments is not None and (not kept or not set(event.arguments) <= kept) for event in self.events):
raise ValueError("Tool events can only retain the arguments the payload declares kept.")
return self


Expand Down
9 changes: 8 additions & 1 deletion pyrit/models/score/trace.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,12 +140,19 @@ def _validate_availability(self) -> TraceQueryResult:


class ToolExecution(_TraceInterval):
"""Safe immutable name-only execution evidence; arguments and results are not retained."""
"""
Safe immutable execution evidence; results and raw arguments are not retained.

``arguments`` holds only the arguments a source was configured to keep, redacting the rest
at write time. It is None when the source kept no arguments or could not read them.
"""

name: ToolName
parent_span_id: SpanId | None = None
call_id: str | None = Field(default=None, min_length=1)
status: TraceSpanStatus = TraceSpanStatus.UNSET
#: Left out of serialization while None, so name-only evidence keeps its stored form.
arguments: dict[str, JsonValue] | None = Field(default=None, exclude_if=lambda value: value is None)


class ExecutionStepKind(str, Enum):
Expand Down
85 changes: 79 additions & 6 deletions pyrit/score/observation/otel_trace_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from __future__ import annotations

import asyncio
import json
import logging
import math
from typing import TYPE_CHECKING
Expand All @@ -24,33 +25,103 @@
if TYPE_CHECKING:
from collections.abc import Sequence

from pydantic import JsonValue

from pyrit.models import TraceQueryResult, TraceScorable, TraceSpan
from pyrit.score.observation.trace_client import TraceClient

logger = logging.getLogger(__name__)

#: The GenAI semantic-convention attribute that carries a tool call's arguments.
_ARGUMENTS_ATTRIBUTE = "gen_ai.tool.call.arguments"


def _has_non_finite_number(value: JsonValue) -> bool:
"""
Find a NaN or infinite number anywhere in a JSON value.

Returns:
bool: Whether the value holds a number that is not finite.
"""
if isinstance(value, float):
return not math.isfinite(value)
if isinstance(value, dict):
return any(_has_non_finite_number(item) for item in value.values())
if isinstance(value, list):
return any(_has_non_finite_number(item) for item in value)
return False


def _keep_arguments(value: JsonValue | None, *, kept: tuple[str, ...]) -> dict[str, JsonValue] | None:
"""
Keep only the named top-level arguments of one call, redacting the rest.

A number that is not finite is not JSON, whether it arrives as a ``NaN`` or ``Infinity``
constant, as a literal too large to represent, or inside an already-parsed object.

Returns:
dict[str, JsonValue] | None: The kept arguments the call has, or None if its arguments
are missing, are not a JSON object, or hold a number that is not finite.
"""
if isinstance(value, str):
try:
value = json.loads(value)
except ValueError:
return None
if not isinstance(value, dict) or _has_non_finite_number(value):
return None
return {name: value[name] for name in kept if name in value}


class OtelTraceSource:
"""Normalize explicit GenAI/OpenInference execution spans into safe evidence."""
"""
Normalize explicit GenAI/OpenInference execution spans into safe evidence.

Tool arguments are redacted at write time. By default none are kept. ``kept_arguments`` opts in
to keeping the named top-level arguments from the span's ``gen_ai.tool.call.arguments``
attribute; every other argument, and the raw attribute, is discarded before the evidence is
stored. Spans that do not carry that attribute keep no arguments.
"""

def __init__(self, *, trace_client: TraceClient, max_spans: int = 10000, timeout_seconds: float = 30) -> None:
def __init__(
self,
*,
trace_client: TraceClient,
max_spans: int = 10000,
timeout_seconds: float = 30,
kept_arguments: Sequence[str] = (),
) -> None:
"""
Initialize bounded acquisition through a caller-owned client.

Raises:
ValueError: If the retrieval limit or timeout is not positive and finite.
ValueError: If the retrieval limit or timeout is not positive and finite, or the kept
argument names are not distinct and nonempty.
"""
if max_spans < 1 or not math.isfinite(timeout_seconds) or timeout_seconds <= 0:
raise ValueError("max_spans and timeout_seconds must be positive.")
if (
isinstance(kept_arguments, str)
or not all(isinstance(name, str) and name for name in kept_arguments)
or len(set(kept_arguments)) != len(kept_arguments)
):
raise ValueError("kept_arguments must be a sequence of distinct, nonempty argument names.")
self._client = trace_client
self._max_spans = max_spans
self._timeout_seconds = timeout_seconds
self._kept_arguments = tuple(kept_arguments)

def get_identifier(self) -> ComponentIdentifier:
"""Return parser version and source identity without serializing the client."""
return ComponentIdentifier.of(
self,
params={"normalization_version": 1, "max_spans": self._max_spans, "timeout_seconds": self._timeout_seconds},
params={
"normalization_version": 1,
"max_spans": self._max_spans,
"timeout_seconds": self._timeout_seconds,
# Omitted while empty, so a source that keeps no arguments keeps its identity.
"kept_arguments": list(self._kept_arguments) or None,
},
children={"trace_client": self._client.get_identifier()},
)

Expand All @@ -75,7 +146,7 @@ async def acquire_async(self, *, scorable: TraceScorable) -> Observation:
)

spans, reasons = _scoped_spans(result=result, scope=scorable, max_spans=self._max_spans)
events, normalization_reasons = self._normalize(spans=spans)
events, normalization_reasons = self._normalize(spans=spans, kept=self._kept_arguments)
reasons.extend(normalization_reasons)
acquisition = Acquisition.PARTIAL if reasons else Acquisition.COMPLETE
return self._observation(
Expand All @@ -101,11 +172,12 @@ def _observation(
scope=scorable,
events=events,
coverage=TraceCoverage(complete=acquisition is Acquisition.COMPLETE, reasons=reasons),
kept_arguments=self._kept_arguments,
),
)

@staticmethod
def _normalize(*, spans: Sequence[TraceSpan]) -> tuple[tuple[ToolExecution, ...], list[str]]:
def _normalize(*, spans: Sequence[TraceSpan], kept: tuple[str, ...]) -> tuple[tuple[ToolExecution, ...], list[str]]:
events: list[ToolExecution] = []
reasons: list[str] = []
for span in spans:
Expand All @@ -130,6 +202,7 @@ def _normalize(*, spans: Sequence[TraceSpan]) -> tuple[tuple[ToolExecution, ...]
start_time=span.start_time,
end_time=span.end_time,
status=span.status,
arguments=_keep_arguments(span.attributes.get(_ARGUMENTS_ATTRIBUTE), kept=kept) if kept else None,
)
)
events.sort(key=lambda event: (event.start_time, event.trace_id, event.span_id))
Expand Down
35 changes: 26 additions & 9 deletions pyrit/score/tool_argument_matching.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from pyrit.score.text_matching import match_text

if TYPE_CHECKING:
from collections.abc import Mapping, Sequence
from collections.abc import Collection, Mapping, Sequence

from pydantic import JsonValue

Expand Down Expand Up @@ -42,43 +42,60 @@ def describe_tool_requirement(requirement: ToolCallRequirement) -> str:
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:
def match_tool_arguments(
*,
requirement: ToolCallRequirement,
arguments: Mapping[str, JsonValue] | None,
kept: Collection[str] | None = 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.

``kept`` names the arguments the evidence kept when the rest were redacted at write time;
None means every argument was retained. A redacted argument is unknown, not absent: a
constraint on it can neither match nor fail, so the call is undetermined unless another,
kept argument refutes it.

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
verdict: bool | None = True
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])):
if kept is not None and constraint.name not in kept:
verdict = None
elif constraint.name not in arguments or not match_text(
matcher=constraint.matcher, text=_argument_text(arguments[constraint.name])
):
return False
return True
return verdict


def match_tool_requirement(
*, requirement: ToolCallRequirement, calls: Sequence[Mapping[str, JsonValue] | None]
*,
requirement: ToolCallRequirement,
calls: Sequence[Mapping[str, JsonValue] | None],
kept: Collection[str] | None = 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.
decides whether its evidence is complete enough to keep a refutation. ``kept`` is as for
``match_tool_arguments``.

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]
verdicts = [match_tool_arguments(requirement=requirement, arguments=arguments, kept=kept) for arguments in calls]
if True in verdicts:
return True
return None if None in verdicts else False
Loading
Loading