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
136 changes: 116 additions & 20 deletions doc/code/scoring/5_tool_call_scorer.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@
"`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. For argument matching, use\n",
"`MessageToolCallScorer` (see \"Require arguments\" below).\n",
"check tool success, arguments, or call count. `OtelToolCallOrderScorer`, shown\n",
"below, checks the order of tool calls from the same evidence. For argument\n",
"matching, use `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",
Expand Down Expand Up @@ -207,6 +208,101 @@
"cell_type": "markdown",
"id": "8",
"metadata": {},
"source": [
"## Check the order of tool calls\n",
"\n",
"`OtelToolCallOrderScorer` matches a `ToolsCalledInOrder` condition against the\n",
"same trace evidence. Each listed tool needs an execution span that ended before\n",
"a span of the next listed tool started. Other tools may run in between.\n",
"\n",
"Order comes from span timestamps. Overlapping or unfinished spans give no order,\n",
"so they produce an undetermined score rather than false. A negative still needs\n",
"complete capture. When spans come from different clocks, pass\n",
"`clock_skew_tolerance` to treat spans that are closer than that as unordered.\n",
"\n",
"This example records spans with explicit timestamps so the result does not depend\n",
"on clock resolution."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"read_file before send_email: True\n",
"send_email before read_file: False\n",
"Overlapping spans: undetermined\n"
]
}
],
"source": [
"import time\n",
"\n",
"from pyrit.models import ToolsCalledInOrder\n",
"from pyrit.score import OtelToolCallOrderScorer\n",
"\n",
"client = InMemoryTraceClient()\n",
"provider = TracerProvider(sampler=ALWAYS_ON, span_limits=SpanLimits(max_span_attribute_length=SpanLimits.UNSET))\n",
"provider.add_span_processor(SimpleSpanProcessor(InMemoryTraceExporter(trace_client=client)))\n",
"tracer = provider.get_tracer(\"pyrit-tool-order-example\")\n",
"order_scorer = OtelToolCallOrderScorer(source=OtelTraceSource(trace_client=client))\n",
"\n",
"\n",
"def expects_order(*names: str) -> ScoringExpectation:\n",
" \"\"\"Build an ordering condition over exact tool names.\"\"\"\n",
" return ScoringExpectation(\n",
" conditions=(ToolsCalledInOrder(tools=tuple(ToolCallRequirement(name=name) for name in names)),)\n",
" )\n",
"\n",
"\n",
"def record_agent_run(*spans: tuple[str, int, int]) -> TraceScorable:\n",
" \"\"\"Record one agent trace whose tool spans have explicit start and end offsets in milliseconds.\"\"\"\n",
" base = time.time_ns()\n",
" with tracer.start_as_current_span(\"agent\", context=Context()) as root:\n",
" for name, start_ms, end_ms in spans:\n",
" span = tracer.start_span(\n",
" name,\n",
" start_time=base + start_ms * 1_000_000,\n",
" attributes={\"gen_ai.operation.name\": \"execute_tool\", \"gen_ai.tool.name\": name},\n",
" )\n",
" span.end(end_time=base + end_ms * 1_000_000)\n",
" trace_id = f\"{root.get_span_context().trace_id:032x}\"\n",
" return TraceScorable(trace_ids=(trace_id,))\n",
"\n",
"\n",
"sequential = record_agent_run((\"read_file\", 0, 1), (\"send_email\", 2, 3))\n",
"concurrent = record_agent_run((\"read_file\", 0, 2), (\"send_email\", 1, 3))\n",
"assert await asyncio.to_thread(provider.force_flush) # type: ignore\n",
"client.mark_complete(trace_ids=(*sequential.trace_ids, *concurrent.trace_ids))\n",
"\n",
"in_order = (\n",
" await order_scorer.score_async(scorable=sequential, expectation=expects_order(\"read_file\", \"send_email\")) # type: ignore\n",
")[0]\n",
"reversed_order = (\n",
" await order_scorer.score_async(scorable=sequential, expectation=expects_order(\"send_email\", \"read_file\")) # type: ignore\n",
")[0]\n",
"overlapping = (\n",
" await order_scorer.score_async(scorable=concurrent, expectation=expects_order(\"read_file\", \"send_email\")) # type: ignore\n",
")[0]\n",
"assert in_order.get_value() is True\n",
"assert reversed_order.get_value() is False\n",
"assert overlapping.status is ScoreStatus.UNDETERMINED\n",
"print(f\"read_file before send_email: {in_order.get_value()}\")\n",
"print(f\"send_email before read_file: {reversed_order.get_value()}\")\n",
"print(f\"Overlapping spans: {overlapping.status.value}\")\n",
"await asyncio.to_thread(provider.shutdown) # type: ignore\n",
"client.close()"
]
},
{
"cell_type": "markdown",
"id": "10",
"metadata": {},
"source": [
"## Score a tool call through an attack\n",
"\n",
Expand All @@ -229,21 +325,14 @@
{
"cell_type": "code",
"execution_count": null,
"id": "9",
"id": "11",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"my_tool_call: success"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"my_tool_call: success\n",
"no tool: failure\n",
"pending: undetermined\n"
]
Expand Down Expand Up @@ -302,7 +391,7 @@
},
{
"cell_type": "markdown",
"id": "10",
"id": "12",
"metadata": {},
"source": [
"A composite receives the same message reference in each child. The message\n",
Expand All @@ -314,14 +403,20 @@
{
"cell_type": "code",
"execution_count": null,
"id": "11",
"id": "13",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Message and tool evidence: success\n",
"Message and tool evidence: success\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Saved attack tool evidence: True\n"
]
}
Expand Down Expand Up @@ -354,7 +449,7 @@
},
{
"cell_type": "markdown",
"id": "12",
"id": "14",
"metadata": {},
"source": [
"## Configure tracing\n",
Expand Down Expand Up @@ -383,7 +478,7 @@
},
{
"cell_type": "markdown",
"id": "13",
"id": "15",
"metadata": {},
"source": [
"## Use another trace source\n",
Expand All @@ -405,7 +500,7 @@
},
{
"cell_type": "markdown",
"id": "14",
"id": "16",
"metadata": {},
"source": [
"## Score tool calls without traces\n",
Expand All @@ -432,7 +527,7 @@
},
{
"cell_type": "markdown",
"id": "15",
"id": "17",
"metadata": {},
"source": [
"## Require that nothing else ran\n",
Expand Down Expand Up @@ -483,7 +578,8 @@
],
"metadata": {
"jupytext": {
"cell_metadata_filter": "-all"
"cell_metadata_filter": "-all",
"main_language": "python"
},
"language_info": {
"codemirror_mode": {
Expand All @@ -495,7 +591,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.12"
"version": "3.13.17"
}
},
"nbformat": 4,
Expand Down
78 changes: 76 additions & 2 deletions doc/code/scoring/5_tool_call_scorer.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@
# `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. For argument matching, use
# `MessageToolCallScorer` (see "Require arguments" below).
# check tool success, arguments, or call count. `OtelToolCallOrderScorer`, shown
# below, checks the order of tool calls from the same evidence. 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"`.
Expand Down Expand Up @@ -139,6 +140,79 @@ def my_tool_call() -> str:
].model_dump_json() == before_replay
print(f"my_tool_call in saved evidence after capture is closed: {replayed.get_value()}")

# %% [markdown]
# ## Check the order of tool calls
#
# `OtelToolCallOrderScorer` matches a `ToolsCalledInOrder` condition against the
# same trace evidence. Each listed tool needs an execution span that ended before
# a span of the next listed tool started. Other tools may run in between.
#
# Order comes from span timestamps. Overlapping or unfinished spans give no order,
# so they produce an undetermined score rather than false. A negative still needs
# complete capture. When spans come from different clocks, pass
# `clock_skew_tolerance` to treat spans that are closer than that as unordered.
#
# This example records spans with explicit timestamps so the result does not depend
# on clock resolution.

# %%
import time

from pyrit.models import ToolsCalledInOrder
from pyrit.score import OtelToolCallOrderScorer

client = InMemoryTraceClient()
provider = TracerProvider(sampler=ALWAYS_ON, span_limits=SpanLimits(max_span_attribute_length=SpanLimits.UNSET))
provider.add_span_processor(SimpleSpanProcessor(InMemoryTraceExporter(trace_client=client)))
tracer = provider.get_tracer("pyrit-tool-order-example")
order_scorer = OtelToolCallOrderScorer(source=OtelTraceSource(trace_client=client))


def expects_order(*names: str) -> ScoringExpectation:
"""Build an ordering condition over exact tool names."""
return ScoringExpectation(
conditions=(ToolsCalledInOrder(tools=tuple(ToolCallRequirement(name=name) for name in names)),)
)


def record_agent_run(*spans: tuple[str, int, int]) -> TraceScorable:
"""Record one agent trace whose tool spans have explicit start and end offsets in milliseconds."""
base = time.time_ns()
with tracer.start_as_current_span("agent", context=Context()) as root:
for name, start_ms, end_ms in spans:
span = tracer.start_span(
name,
start_time=base + start_ms * 1_000_000,
attributes={"gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": name},
)
span.end(end_time=base + end_ms * 1_000_000)
trace_id = f"{root.get_span_context().trace_id:032x}"
return TraceScorable(trace_ids=(trace_id,))


sequential = record_agent_run(("read_file", 0, 1), ("send_email", 2, 3))
concurrent = record_agent_run(("read_file", 0, 2), ("send_email", 1, 3))
assert await asyncio.to_thread(provider.force_flush) # type: ignore
client.mark_complete(trace_ids=(*sequential.trace_ids, *concurrent.trace_ids))

in_order = (
await order_scorer.score_async(scorable=sequential, expectation=expects_order("read_file", "send_email")) # type: ignore
)[0]
reversed_order = (
await order_scorer.score_async(scorable=sequential, expectation=expects_order("send_email", "read_file")) # type: ignore
)[0]
overlapping = (
await order_scorer.score_async(scorable=concurrent, expectation=expects_order("read_file", "send_email")) # type: ignore
)[0]
assert in_order.get_value() is True
assert reversed_order.get_value() is False
assert overlapping.status is ScoreStatus.UNDETERMINED
print(f"read_file before send_email: {in_order.get_value()}")
print(f"send_email before read_file: {reversed_order.get_value()}")
print(f"Overlapping spans: {overlapping.status.value}")
await asyncio.to_thread(provider.shutdown) # type: ignore
client.close()

# %% [markdown]
# ## Score a tool call through an attack
#
Expand Down
2 changes: 2 additions & 0 deletions pyrit/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,7 @@
ToolEventsObservationPayload,
ToolExecution,
ToolsCalled,
ToolsCalledInOrder,
TraceCoverage,
TraceQuery,
TraceQueryResult,
Expand Down Expand Up @@ -568,6 +569,7 @@
"ToolEventsObservationPayload": "pyrit.models.score",
"ToolExecution": "pyrit.models.score",
"ToolsCalled": "pyrit.models.score",
"ToolsCalledInOrder": "pyrit.models.score",
"TraceCoverage": "pyrit.models.score",
"TraceQuery": "pyrit.models.score",
"TraceQueryResult": "pyrit.models.score",
Expand Down
2 changes: 2 additions & 0 deletions pyrit/models/score/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
ToolArgumentRequirement,
ToolCallRequirement,
ToolsCalled,
ToolsCalledInOrder,
)
from pyrit.models.score.expectation import (
ScoringExpectation,
Expand Down Expand Up @@ -118,6 +119,7 @@
"ToolEventsObservationPayload": "pyrit.models.score.observation",
"ToolExecution": "pyrit.models.score.trace",
"ToolsCalled": "pyrit.models.score.condition",
"ToolsCalledInOrder": "pyrit.models.score.condition",
"TraceCoverage": "pyrit.models.score.trace",
"TraceQuery": "pyrit.models.score.trace",
"TraceQueryResult": "pyrit.models.score.trace",
Expand Down
36 changes: 36 additions & 0 deletions pyrit/models/score/condition.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,42 @@ def _validate_tools(self) -> ToolsCalled:
return self


class ToolsCalledInOrder(Condition):
"""
Require the named tools to have execution attempts in this relative order.

Each listed tool needs an execution attempt that finished before an execution attempt of
the next listed tool started. Other tools, and further attempts of the listed tools, may run
in between. Success is not required. Overlapping or unfinished attempts do not establish an
order in either direction.

Each tool may be named only once, so an order that returns to a tool (for example
``read_file`` then ``send_email`` then ``read_file`` again) is out of scope. Distinct names
keep each tool's attempts in a single pool, which keeps the match sound.
"""

condition_type: Literal["tools_called_in_order"] = "tools_called_in_order"
tools: tuple[ToolCallRequirement, ...]

@model_validator(mode="after")
def _validate_tools(self) -> ToolsCalledInOrder:
"""
Require at least two distinct exact names.

Returns:
ToolsCalledInOrder: The validated condition.

Raises:
ValueError: If fewer than two tools are named or an exact name repeats.
"""
if len(self.tools) < 2:
raise ValueError("ToolsCalledInOrder requires at least two tools; use ToolsCalled for one.")
names = [tool.name for tool in self.tools]
if len(set(names)) != len(names):
raise ValueError("ToolsCalledInOrder requires each tool name once.")
Comment thread
romanlutz marked this conversation as resolved.
Resolved
return self


class OutputMatches(Condition):
"""The output satisfies the supplied text matcher."""

Expand Down
Loading
Loading