|
| 1 | +# Copyright (c) Microsoft Corporation. |
| 2 | +# Licensed under the MIT license. |
| 3 | + |
| 4 | +import logging |
| 5 | + |
| 6 | +from pyrit.message_normalizer import ( |
| 7 | + GenericSystemSquashNormalizer, |
| 8 | + HistorySquashNormalizer, |
| 9 | + MessageListNormalizer, |
| 10 | +) |
| 11 | +from pyrit.models import Message |
| 12 | +from pyrit.prompt_target.common.target_capabilities import ( |
| 13 | + CapabilityHandlingPolicy, |
| 14 | + CapabilityName, |
| 15 | + TargetCapabilities, |
| 16 | + UnsupportedCapabilityBehavior, |
| 17 | +) |
| 18 | + |
| 19 | +logger = logging.getLogger(__name__) |
| 20 | + |
| 21 | + |
| 22 | +# --------------------------------------------------------------------------- |
| 23 | +# Single registry: add new normalizable capabilities here and nowhere else. |
| 24 | +# Order in the list determines pipeline execution order. |
| 25 | +# --------------------------------------------------------------------------- |
| 26 | +_NORMALIZER_REGISTRY: list[tuple[CapabilityName, MessageListNormalizer[Message]]] = [ |
| 27 | + (CapabilityName.SYSTEM_PROMPT, GenericSystemSquashNormalizer()), |
| 28 | + (CapabilityName.MULTI_TURN, HistorySquashNormalizer()), |
| 29 | +] |
| 30 | + |
| 31 | +# Derived constant — no manual maintenance required. |
| 32 | +NORMALIZABLE_CAPABILITIES: frozenset[CapabilityName] = frozenset(cap for cap, _ in _NORMALIZER_REGISTRY) |
| 33 | + |
| 34 | + |
| 35 | +class ConversationNormalizationPipeline: |
| 36 | + """ |
| 37 | + Ordered sequence of message normalizers that adapt conversations when |
| 38 | + the target lacks certain capabilities. |
| 39 | +
|
| 40 | + The pipeline is constructed via ``from_capabilities``, which resolves |
| 41 | + capabilities and policy into a concrete, ordered tuple of normalizers. |
| 42 | + ``normalize_async`` then simply executes that tuple in order. |
| 43 | +
|
| 44 | + To add a new normalizable capability, add a single entry to |
| 45 | + ``_NORMALIZER_REGISTRY``. ``NORMALIZABLE_CAPABILITIES``, |
| 46 | + pipeline ordering, and default normalizers are all derived from it. |
| 47 | + """ |
| 48 | + |
| 49 | + def __init__(self, normalizers: tuple[MessageListNormalizer[Message], ...] = ()) -> None: |
| 50 | + """ |
| 51 | + Initialize the normalization pipeline with an ordered sequence of normalizers. |
| 52 | +
|
| 53 | + Args: |
| 54 | + normalizers (tuple[MessageListNormalizer[Message], ...]): |
| 55 | + Ordered normalizers to apply during ``normalize_async``. |
| 56 | + Defaults to an empty tuple (pass-through). |
| 57 | + """ |
| 58 | + self._normalizers = normalizers |
| 59 | + |
| 60 | + @classmethod |
| 61 | + def from_capabilities( |
| 62 | + cls, |
| 63 | + *, |
| 64 | + capabilities: TargetCapabilities, |
| 65 | + policy: CapabilityHandlingPolicy, |
| 66 | + normalizer_overrides: dict[CapabilityName, MessageListNormalizer[Message]] | None = None, |
| 67 | + ) -> "ConversationNormalizationPipeline": |
| 68 | + """ |
| 69 | + Resolve capabilities and policy into a concrete pipeline of normalizers. |
| 70 | +
|
| 71 | + For each capability in ``_NORMALIZER_REGISTRY`` (in order): |
| 72 | +
|
| 73 | + * If the target already supports the capability, no normalizer is added. |
| 74 | + * If the capability is missing and the policy is ``ADAPT``, the |
| 75 | + corresponding normalizer (from overrides or defaults) is added. |
| 76 | + * If the capability is missing and the policy is ``RAISE``, a |
| 77 | + ``ValueError`` is raised immediately. |
| 78 | +
|
| 79 | + Args: |
| 80 | + capabilities (TargetCapabilities): The target's declared capabilities. |
| 81 | + policy (CapabilityHandlingPolicy): How to handle each missing capability. |
| 82 | + normalizer_overrides (dict[CapabilityName, MessageListNormalizer[Message]] | None): |
| 83 | + Optional overrides for specific capability normalizers. |
| 84 | + Falls back to the defaults from ``_NORMALIZER_REGISTRY``. |
| 85 | +
|
| 86 | + Returns: |
| 87 | + ConversationNormalizationPipeline: A pipeline with the resolved |
| 88 | + ordered tuple of normalizers. |
| 89 | +
|
| 90 | + Raises: |
| 91 | + ValueError: If a required capability is missing and the policy is RAISE. |
| 92 | + """ |
| 93 | + overrides = normalizer_overrides or {} |
| 94 | + normalizers: list[MessageListNormalizer[Message]] = [] |
| 95 | + |
| 96 | + for capability, default_normalizer in _NORMALIZER_REGISTRY: |
| 97 | + if capabilities.includes(capability=capability): |
| 98 | + continue |
| 99 | + |
| 100 | + behavior = policy.get_behavior(capability=capability) |
| 101 | + |
| 102 | + if behavior == UnsupportedCapabilityBehavior.RAISE: |
| 103 | + raise ValueError(f"Target does not support '{capability.value}' and the handling policy is RAISE.") |
| 104 | + |
| 105 | + normalizer = overrides.get(capability, default_normalizer) |
| 106 | + |
| 107 | + normalizers.append(normalizer) |
| 108 | + |
| 109 | + return cls(normalizers=tuple(normalizers)) |
| 110 | + |
| 111 | + async def normalize_async(self, *, messages: list[Message]) -> list[Message]: |
| 112 | + """ |
| 113 | + Run the pre-resolved normalizer sequence over the messages. |
| 114 | +
|
| 115 | + Args: |
| 116 | + messages (list[Message]): The full conversation to normalize. |
| 117 | +
|
| 118 | + Returns: |
| 119 | + list[Message]: The (possibly adapted) message list. |
| 120 | + """ |
| 121 | + result = list(messages) |
| 122 | + for normalizer in self._normalizers: |
| 123 | + result = await normalizer.normalize_async(result) |
| 124 | + return result |
| 125 | + |
| 126 | + @property |
| 127 | + def normalizers(self) -> tuple[MessageListNormalizer[Message], ...]: |
| 128 | + """ |
| 129 | + The ordered normalizers in this pipeline. |
| 130 | +
|
| 131 | + Returns: |
| 132 | + tuple[MessageListNormalizer[Message], ...]: The normalizer sequence. |
| 133 | + """ |
| 134 | + return self._normalizers |
0 commit comments