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
26 changes: 11 additions & 15 deletions pyrit/backend/services/target_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
TargetTypeResponse,
UnregisteredTarget,
)
from pyrit.backend.services.component_lifecycle import construct_component_async, release_component_async
from pyrit.backend.services.component_lifecycle import release_component_async
from pyrit.common import AUTH_MODES, REQUIRED_VALUE, AuthMode, default_values
from pyrit.models import Parameter, PromptDataType, TargetCapabilities, TargetIdentifier
from pyrit.models.catalog import (
Expand Down Expand Up @@ -141,7 +141,7 @@ def capabilities_scope(

async def detect_capabilities_async(self, *, target_registry_name: str, expected_hash: str) -> TargetInstance:
"""
Probe private targets and apply a completed result to the selected source.
Probe a live target and apply a completed result to it.

Round-robin detection probes each child independently and combines their
results. Only the selected parent is updated; live children are not changed.
Expand Down Expand Up @@ -207,23 +207,19 @@ async def detect_capabilities_async(self, *, target_registry_name: str, expected

async def _probe_capabilities_async(self, target: PromptTarget) -> TargetCapabilities:
"""
Check one private target and release its resources.
Check one live target without changing it.

Probes see their permissive settings only in their own task, so concurrent
requests to the target are unaffected and any target type can be checked.

Returns:
TargetCapabilities: Completed capability results.
"""
probe = await construct_component_async(self._registry.recreate_instance, source=target, params={})
try:
probe.apply_capabilities(capabilities=target.capabilities)
modalities: set[frozenset[PromptDataType]] = {frozenset({"text"})}
for modality in DEFAULT_TEST_ASSETS:
modalities.update({frozenset({modality}), frozenset({"text", modality})})
modalities.update(TOOL_CALL_INPUT_MODALITIES)
return await discover_target_capabilities_async(
target=probe, test_modalities=modalities, raise_on_error=True
)
finally:
await release_component_async(probe)
modalities: set[frozenset[PromptDataType]] = {frozenset({"text"})}
for modality in DEFAULT_TEST_ASSETS:
modalities.update({frozenset({modality}), frozenset({"text", modality})})
modalities.update(TOOL_CALL_INPUT_MODALITIES)
return await discover_target_capabilities_async(target=target, test_modalities=modalities, raise_on_error=True)

def _build_instance_from_entry(
self, entry: RegistryEntry[PromptTarget], *, origin: RegistryEntryOrigin | None = None
Expand Down
86 changes: 49 additions & 37 deletions pyrit/prompt_target/common/discover_target_capabilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,10 @@
import logging
import uuid
from collections.abc import Awaitable, Callable, Generator, Iterable, Mapping
from contextlib import ExitStack, contextmanager
from contextlib import contextmanager
from contextvars import ContextVar
from pathlib import Path
from typing import Any

from pyrit.common.attack_result_scope import get_current_attack_result_id
from pyrit.common.path import DATASETS_PATH
Expand Down Expand Up @@ -148,15 +149,17 @@ def _permissive_configuration(
extra_input_modalities: Iterable[frozenset[PromptDataType]] | None = None,
) -> Generator[None, None, None]:
"""
Temporarily replace ``target``'s configuration with one that declares every
boolean capability as natively supported.
For this task only, give ``target`` a configuration that declares every
boolean capability as natively supported, and keep configured tools out of
probe requests.

This bypasses ``PromptTarget._validate_request``, which would otherwise
short-circuit probes for capabilities the target declares as unsupported
before any API call is made. The original configuration is restored on exit.
before any API call is made. The target itself is never modified, so
probes can run on a live target while other tasks use it.

Args:
target (PromptTarget): The target whose configuration is temporarily replaced.
target (PromptTarget): The target to probe.
extra_input_modalities (Iterable[frozenset[PromptDataType]] | None):
Additional modality combinations to include in ``input_modalities``
during the override. Used by modality probes so that
Expand Down Expand Up @@ -184,40 +187,34 @@ def _permissive_configuration(
# probes bypass preflight validation without inheriting ADAPT policy or
# custom normalizer overrides from the target's runtime configuration.
probe_configuration = TargetConfiguration(capabilities=permissive_caps)
target._configuration = probe_configuration
try:
with _disable_probe_tools(target=target):
yield
finally:
target._configuration = original
# Both overrides apply to this task only, so other requests to a live target are unaffected.
with target._probe_scope(configuration=probe_configuration, attributes=_probe_tool_settings(target=target)):
yield


@contextmanager
def _disable_probe_tools(*, target: PromptTarget) -> Generator[None, None, None]:
"""Disable configured tools during probes and restore all settings on exit."""
def _probe_tool_settings(*, target: PromptTarget) -> dict[str, Any]:
"""
Return task-local settings that keep configured tools out of probe requests.

Returns:
dict[str, Any]: Attribute values for ``PromptTarget._probe_scope``.
"""
from pyrit.prompt_target.litellm_chat_target import LiteLLMChatTarget
from pyrit.prompt_target.openai.openai_chat_target import OpenAIChatTarget
from pyrit.prompt_target.openai.openai_response_target import OpenAIResponseTarget

with ExitStack() as stack:
if isinstance(target, (OpenAIChatTarget, OpenAIResponseTarget, LiteLLMChatTarget)):
original_body = target._extra_body_parameters
stack.callback(setattr, target, "_extra_body_parameters", original_body)
tool_settings = {"tools", "tool_choice", "parallel_tool_calls", "functions", "function_call"}
target._extra_body_parameters = {
key: value for key, value in (original_body or {}).items() if key not in tool_settings
}
extra_body = target._extra_body_parameters.get("extra_body")
if isinstance(extra_body, Mapping):
target._extra_body_parameters["extra_body"] = {
key: value for key, value in extra_body.items() if key not in tool_settings
}
if isinstance(target, (OpenAIResponseTarget, LiteLLMChatTarget)):
stack.callback(setattr, target, "_execute_tools", target._execute_tools)
stack.callback(setattr, target, "_suppress_tools", target._suppress_tools)
target._execute_tools = False
target._suppress_tools = True
yield
settings: dict[str, Any] = {}
if isinstance(target, (OpenAIChatTarget, OpenAIResponseTarget, LiteLLMChatTarget)):
tool_settings = {"tools", "tool_choice", "parallel_tool_calls", "functions", "function_call"}
body = {key: value for key, value in (target._extra_body_parameters or {}).items() if key not in tool_settings}
extra_body = body.get("extra_body")
if isinstance(extra_body, Mapping):
body["extra_body"] = {key: value for key, value in extra_body.items() if key not in tool_settings}
settings["_extra_body_parameters"] = body
if isinstance(target, (OpenAIResponseTarget, LiteLLMChatTarget)):
settings["_execute_tools"] = False
settings["_suppress_tools"] = True
return settings


def _new_conversation_id() -> str:
Expand Down Expand Up @@ -682,10 +679,13 @@ def _supports_chat_probes(target: PromptTarget) -> bool:
bool: Whether chat features can be sent by this adapter.
"""
from pyrit.prompt_target.litellm_chat_target import LiteLLMChatTarget
from pyrit.prompt_target.litellm_decision_target import LiteLLMDecisionTarget
from pyrit.prompt_target.openai.openai_chat_target import OpenAIChatTarget
from pyrit.prompt_target.openai.openai_response_target import OpenAIResponseTarget

return isinstance(target, (OpenAIChatTarget, OpenAIResponseTarget, LiteLLMChatTarget))
return isinstance(target, (OpenAIChatTarget, OpenAIResponseTarget, LiteLLMChatTarget)) and not isinstance(
target, LiteLLMDecisionTarget
)


async def _discover_capability_flags_async(
Expand Down Expand Up @@ -849,7 +849,12 @@ async def _discover_input_modalities_async(
queried.add(combination)
continue
try:
message = await asyncio.to_thread(_create_test_message, modalities=combination, test_assets=assets)
message = await asyncio.to_thread(
_create_test_message,
modalities=combination,
test_assets=assets,
text=target.capability_probe_text,
)
except FileNotFoundError as exc:
# Skip combinations we cannot construct a valid probe payload for.
logger.info("Skipping modality %s: %s", combination, exc)
Expand Down Expand Up @@ -897,7 +902,12 @@ async def _check_control_request_async(
with _permissive_configuration(target=target):
for combination in combinations:
try:
message = await asyncio.to_thread(_create_test_message, modalities=combination, test_assets=assets)
message = await asyncio.to_thread(
_create_test_message,
modalities=combination,
test_assets=assets,
text=target.capability_probe_text,
)
except (FileNotFoundError, ValueError) as exc:
logger.info("Cannot prepare control input %s: %s", sorted(combination), exc)
continue
Expand Down Expand Up @@ -1077,6 +1087,7 @@ def _create_test_message(
*,
modalities: frozenset[PromptDataType],
test_assets: dict[PromptDataType, str],
text: str = "test",
) -> Message:
"""
Build a minimal ``Message`` that exercises ``modalities``.
Expand All @@ -1085,6 +1096,7 @@ def _create_test_message(
modalities (frozenset[PromptDataType]): The modalities to include.
test_assets (dict[PromptDataType, str]): Mapping from non-text
modality to a file path used for the probe.
text (str): The text piece's value. Defaults to ``"test"``.

Returns:
Message: A message containing one piece per modality.
Expand All @@ -1101,7 +1113,7 @@ def _create_test_message(
pieces.append(
MessagePiece(
role="user",
original_value="test",
original_value=text,
original_value_data_type="text",
conversation_id=conversation_id,
prompt_metadata=_probe_metadata(),
Expand Down
67 changes: 67 additions & 0 deletions pyrit/prompt_target/common/prompt_target.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,35 @@ def _is_credential_rejection(error: BaseException) -> bool:
# compatibility); it is canonically defined in ``pyrit.common.auth_mode`` so
# ``pyrit.auth`` resolvers can consume it without depending on the target layer.

_ATTRIBUTE_SCOPES: ContextVar[tuple[tuple["PromptTarget", Mapping[str, Any]], ...]] = ContextVar(
"target_attribute_scopes", default=()
)


class _TaskLocalAttribute:
"""
An instance attribute that ``PromptTarget._probe_scope`` can override for one task.

Every other task, including a concurrent send on the same target, reads the stored value.
"""

def __set_name__(self, owner: type, name: str) -> None: # pyrit-keyword-only-exempt descriptor protocol
self._name = name

def __get__(self, instance: object, owner: type | None = None) -> Any: # pyrit-keyword-only-exempt descriptor
if instance is None:
return self
for target, overrides in reversed(_ATTRIBUTE_SCOPES.get()):
if target is instance and self._name in overrides:
return overrides[self._name]
try:
return instance.__dict__[self._name]
except KeyError:
raise AttributeError(self._name) from None

def __set__(self, instance: object, value: Any) -> None: # pyrit-keyword-only-exempt descriptor protocol
instance.__dict__[self._name] = value


class PromptTarget(Identifiable):
"""
Expand Down Expand Up @@ -124,6 +153,10 @@ class PromptTarget(Identifiable):
_CONFIGURATION_SCOPES: ClassVar[ContextVar[tuple[tuple["PromptTarget", TargetConfiguration], ...]]] = ContextVar(
"target_configuration_scopes", default=()
)
# Tool settings that capability probes turn off for their own task only (see ``_probe_scope``).
_extra_body_parameters = _TaskLocalAttribute()
_execute_tools = _TaskLocalAttribute()
_suppress_tools = _TaskLocalAttribute()

# Declarative auth facts consumed by the create-target service and catalog.
# Kept off ``TargetCapabilities`` (auth is a construction/credential axis, not
Expand Down Expand Up @@ -196,6 +229,10 @@ class PromptTarget(Identifiable):
# with the endpoint it was configured for.
COPY_LOCKED_PARAMETER_NAMES: ClassVar[frozenset[str]] = frozenset()

# Text capability discovery sends to check a text input. A target that accepts only structured text
# overrides it with a valid request.
capability_probe_text: ClassVar[str] = "test"

def __init_subclass__(cls, **kwargs: object) -> None:
"""
Validate that subclasses follow the keyword-only ``__init__`` contract.
Expand Down Expand Up @@ -1076,6 +1113,36 @@ def capabilities_scope(self, capabilities: TargetCapabilities) -> Generator[None
finally:
self._CONFIGURATION_SCOPES.reset(token)

@contextmanager
def _probe_scope(
self, *, configuration: TargetConfiguration, attributes: Mapping[str, Any]
) -> Generator[None, None, None]:
"""
Use a configuration and tool settings for this task only, so probes can run on a live target.

Unlike ``capabilities_scope``, the configuration is used as given, without masking.

Args:
configuration: The configuration this task sees.
attributes: Values for this target's task-local attributes, such as ``_execute_tools``.

Yields:
None: The task-local scope, restored even on cancellation.

Raises:
ValueError: If an attribute is not task-local, so setting it would change every task.
"""
for name in attributes:
if not isinstance(getattr(type(self), name, None), _TaskLocalAttribute):
raise ValueError(f"{type(self).__name__}.{name} cannot be overridden for one task.")
configuration_token = self._CONFIGURATION_SCOPES.set((*self._CONFIGURATION_SCOPES.get(), (self, configuration)))
attribute_token = _ATTRIBUTE_SCOPES.set((*_ATTRIBUTE_SCOPES.get(), (self, dict(attributes))))
try:
yield
finally:
_ATTRIBUTE_SCOPES.reset(attribute_token)
self._CONFIGURATION_SCOPES.reset(configuration_token)

@property
def capabilities(self) -> TargetCapabilities:
"""
Expand Down
16 changes: 15 additions & 1 deletion pyrit/prompt_target/litellm_decision_target.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import json
import math
from collections.abc import Awaitable, Callable
from typing import TYPE_CHECKING, Any, TypedDict, cast
from typing import TYPE_CHECKING, Any, ClassVar, TypedDict, cast

from pyrit.exceptions import pyrit_target_retry
from pyrit.models import (
Expand Down Expand Up @@ -44,6 +44,20 @@ class LiteLLMDecisionTarget(LiteLLMChatTarget):
_SUPPORTS_TOOL_CALL_HISTORY = False
_DEFAULT_CONFIGURATION = TargetConfiguration(capabilities=TargetCapabilities())

# Capability detection's text probe must be a valid decision request, like DecisionScorer's.
capability_probe_text: ClassVar[str] = json.dumps(
{
"state": "test",
"questions": {
"probe": {
"type": "noul",
"instructions": "Is the state the word test?",
"criteria": {"true": "It is.", "false": "It is not."},
}
},
}
)

def __init__(
self,
*,
Expand Down
Loading
Loading