Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Trace-backed tool-call scoring

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, 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". expects("my_tool_call") asks the scorer to find that exact tool name in the trace; "summarize" is a different tool name used to demonstrate a missing tool.

Supply trace IDs explicitly, or use stored message evidence from an attack. For messages, the scorer resolves request traces in the conversation through the scored response, without reading later turns.

The OpenTelemetry SDK is included with PyRIT. This walkthrough uses a real SDK provider, local capture, and PyRIT’s in-memory storage. It needs no model, service, credentials, or global provider changes.

Capture and score a real invocation

The caller gets the trace ID from its instrumented execution. The source selects only that trace and stores normalized evidence with the score.

Observed my_tool_call: True

Missing evidence is not a negative result

Capture starts incomplete. Observing a call proves invocation, but an absent tool is not false until coverage is explicitly complete.

This example disables span attribute string truncation, including limits set by environment variables. The exporter rejects finite or unknown length limits: shortened names cannot prove which tools ran, even with incomplete coverage.

This example has no background work and uses always-on sampling. Both spans have ended, so after checking export we can declare this controlled capture complete. A flush alone would not prove that an arbitrary remote trace is complete.

Missing tool before completion: undetermined
Missing tool after controlled completion: False

Re-match saved evidence with capture closed

Load the observation from PyRIT memory, stop capture, and change the expected name. Replay reads the same immutable snapshot; it does not call the trace client. Arguments and results are not retained. Scorer target response observations still have their stricter, original-expectation replay rules.

my_tool_call in saved evidence after capture is closed: True

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.

read_file before send_email: True
send_email before read_file: False
Overlapping spans: undetermined

Score a tool call through an attack

This local agent runs in the same process as PyRIT and uses a real SDK provider. No server, model, credentials, or global instrumentation is needed. A small custom target calls the agent. PromptTarget runs each call inside a fresh trace context when tracing is enabled and saves the same context on the request, so the agent’s spans join the request’s trace without any header handling. See Example: an in-process agent for a multi-turn version of this target.

Here, the prompt "my_tool_call" tells the local agent to call the my_tool_call() tool. The prompt and tool name are the same only to keep the example simple. The scorer matches the tool name recorded in the span, not the prompt text.

The caller owns capture completeness. This controlled agent has no background work, sampling is disabled, and it checks export after its spans end. Only then does it mark a request trace complete. A response alone would not prove this for an arbitrary agent.

my_tool_call: success
no tool: failure
pending: undetermined

A composite receives the same message reference in each child. The message scorer reads the response, and the tool scorer reads linked execution evidence. This deterministic message scorer keeps the example offline; a normal LLM objective scorer can use the same composite path.

Message and tool evidence: success
Saved attack tool evidence: True

Configure tracing

Custom targets disable tracing by default. For an agent in the same process, pass trace_config=TargetTraceConfig(enabled=True) to its PromptTarget constructor, as above. Pass TargetTraceConfig(tracer=provider.get_tracer(...)) instead to also record the target invocation as a span with a caller-owned provider. PyRIT does not install a global provider or exporter. LocalTraceCapture bundles such a provider, without span limits, with a span store and its trace_config(); see Judging with execution traces.

For a remote agent, use HTTPTarget or HTTPXAPITarget. They also disable tracing by default, because an arbitrary HTTP endpoint is not known to accept W3C trace context. Set trace_config=TargetTraceConfig(enabled=True) for an instrumented endpoint, and each request sends a fresh traceparent header. Keep tracing disabled if you supply manual traceparent or tracestate headers. The agent must accept W3C trace context and export its tool spans. Supply a TraceClient that can read those spans; sending a header does not create a trace-store connection.

LiteLLMChatTarget accepts the same trace_config and also disables tracing by default. When enabled, each request sends a fresh traceparent through LiteLLM’s extra_headers, and PyRIT saves the same context on the request. Enable it only when the provider or gateway accepts W3C trace context. While it is enabled, manual trace headers in headers, extra_headers or provider_specific_header are rejected. A model-call span is not tool evidence; the scorer still needs execution spans for the named tool.

Some providers and gateways do not continue W3C context, but they return their own id for each response. LiteLLMChatTarget stores that id on the request as a ProviderTraceReference, apart from any propagation format, with LiteLLM’s provider route (here openai). At scoring time a ProviderTraceResolver maps it to the trace that recorded it.

SpanAttributeTraceResolver finds the captured span that carries the response id as gen_ai.response.id, the attribute OpenTelemetry’s GenAI conventions use for a model response. Name other attributes if your framework records it elsewhere. MappingProviderTraceResolver takes the mapping from your own logs instead.

A request with a W3C link resolves through that link, so set enabled=False for a provider that does not continue it. An id the resolver cannot find, or finds in more than one trace, leaves the request unlinked, and a verdict that rests on absence stays undetermined. So does a send whose tool loop runs a local tool, since one response id cannot name the tool’s run or later completions’ traces.

This cell stands a loopback gateway in for the provider. It ignores traceparent, runs the tool under its own trace, records its response id on the model span, and answers LiteLLM in the OpenAI format. It needs no model or credentials.

With a resolver, my_tool_call: success
With a resolver, no tool: failure
Without a resolver, my_tool_call: undetermined
Without a resolver, no tool: undetermined
Stored identifiers: ['provider', 'request_id']

Use another trace source

A caller can provide a TraceClient that returns neutral spans for the requested trace IDs and reports coverage honestly. OtelTraceSource handles supported GenAI/OpenInference execution spans; matching remains backend-neutral. A client reports TraceQueryResult(available=False) when it knows no evidence can be retrieved, such as after retention expires. This produces an unavailable observation and an undetermined score. Pending capture stays available with incomplete coverage; an empty result alone does not mean unavailable. Optional empty call IDs are omitted; they do not prevent name-only scoring.

ObservationSource[TraceScorable] is the source contract for this scorer. Other sources can use the same protocol with their own scorable types. The caller owns instrumentation and trace retrieval. Automatic request correlation does not install a remote collector or a backend adapter.

Read traces from a remote backend

OtlpJsonTraceClient fetches each trace by ID from an HTTP endpoint that returns OTLP/JSON, such as Grafana Tempo’s /api/traces/{trace_id}. Pass credentials in headers; the source identity records the endpoint without them, or its query. Pass your own httpx.AsyncClient to control proxies and certificates.

A remote backend cannot report when every span of a trace has arrived, so its coverage is never complete. A tool call it returns counts, and a missing one is undetermined, never false. A trace the backend does not have is unavailable. A failed request, an error status, or an unreadable response is an acquisition error, unless another requested trace was retrieved; then coverage is partial.

This cell stands an in-process transport in for the backend.

Remote tools: ['my_tool_call'], acquisition partial
Trace the backend does not have: unavailable

Score tool calls without traces

MessageToolCallScorer reads the same ToolsCalled condition from stored messages instead of spans. A tool counts only when a model-authored function_call piece is paired, by call ID, with a later function_call_output piece in the conversation through the scored response. OpenAIResponseTarget records ToolExecutionMetadata on each output piece. The scorer uses this dispatch status, not the returned payload: a tool-reported error still counts as an invocation, while a dispatch failure does not. Older outputs without metadata use a conservative fallback; payloads shaped like PyRIT dispatch errors cannot prove invocation and remain undetermined. Injected history in the simulated_assistant and simulated_tool roles does not count either.

Stored messages are usually partial evidence. Hosted tools, several response section types, and targets that execute tools themselves leave no output pieces, so a missing tool is undetermined rather than false. OpenAIResponseTarget records these pieces when it runs custom_functions, and records ToolCaptureCoverage on each model response. Coverage is complete when the target ran every function call itself and the provider ran no tool of its own; otherwise it names a gap such as hosted_tool_call. When every response through the scored message is complete and every request has a response, the stored messages rule out other calls and a missing tool is false. Combine it with OtelToolCallScorer under TrueFalseScoreAggregator.OR when trace evidence is also available.

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. MessageToolCallScorer returns false for a stored execution of an unnamed tool, decides the rest only from complete stored messages as described above, and is otherwise undetermined.

ToolsCalled(tools=(ToolCallRequirement(name="read_file"),), exhaustive=True)

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.

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.

Let a scenario choose the tool-call scorer

A scenario that takes a CompatibleScorers pool, such as RapidResponse, picks a scorer for each technique and dataset before it sends anything. A text judge does not evaluate ToolsCalled, so a dataset whose objectives carry that condition goes to the tool-call scorer, and a dataset of ordinary objectives keeps the text judge:

from pyrit.scenario.airt import RapidResponse
from pyrit.score import CompatibleScorers, MessageToolCallScorer

scorers = CompatibleScorers(candidates=[text_judge, MessageToolCallScorer()])
scenario = RapidResponse(objective_scorer=scorers)

One scorer must judge every objective in a dataset, so keep ToolsCalled objectives in their own dataset: a dataset that mixes them with ordinary objectives stops initialization. Judging Each Dataset With Its Own Scorer shows how selection works and when it fails.