-
Notifications
You must be signed in to change notification settings - Fork 718
FEAT add TargetConfiguration & pieces #1573
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
hannahwestra25
merged 14 commits into
microsoft:main
from
hannahwestra25:hawestra/add_target_config_pieces
Apr 8, 2026
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
c9b4b2d
add capability policy and necessary subclasses plus tests
hannahwestra25 40b012e
add normalization pipeline
hannahwestra25 761166d
add target configuration and clean up
hannahwestra25 9518a06
add tests and fix missing capabilities
hannahwestra25 c3a89a8
precommit
hannahwestra25 6d719a6
merge
hannahwestra25 3a3b430
remove unnormalizable capabilities from policy and update tests
hannahwestra25 0ded2db
Merge branch 'main' of https://github.com/microsoft/PyRIT into hawest…
hannahwestra25 a9575f0
update naming and pre-commit
hannahwestra25 0ad8df0
PR comments
hannahwestra25 a663080
Merge branch 'main' of https://github.com/microsoft/PyRIT into hawest…
hannahwestra25 66e9f56
pre-commit and catch
hannahwestra25 65af82c
Merge branch 'main' into hawestra/add_target_config_pieces
hannahwestra25 06e48ff
Merge branch 'main' into hawestra/add_target_config_pieces
hannahwestra25 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| # Copyright (c) Microsoft Corporation. | ||
| # Licensed under the MIT license. | ||
|
|
||
| from pyrit.message_normalizer.message_normalizer import MessageListNormalizer | ||
| from pyrit.models import Message | ||
|
|
||
|
|
||
| class HistorySquashNormalizer(MessageListNormalizer[Message]): | ||
| """ | ||
| Squashes a multi-turn conversation into a single user message. | ||
|
|
||
| Previous turns are formatted as labeled context and prepended to the | ||
| latest message. Used by the normalization pipeline to adapt prompts | ||
| for targets that do not support multi-turn conversations. | ||
| """ | ||
|
|
||
| async def normalize_async(self, messages: list[Message]) -> list[Message]: | ||
| """ | ||
| Combine all messages into a single user message. | ||
|
|
||
| When there is only one message it is returned unchanged. Otherwise | ||
| all prior turns are formatted as ``Role: content`` lines under a | ||
| ``[Conversation History]`` header and the last message's content | ||
| appears under a ``[Current Message]`` header. | ||
|
|
||
| Args: | ||
| messages: The conversation messages to squash. | ||
|
|
||
| Returns: | ||
| list[Message]: A single-element list containing the squashed message. | ||
|
|
||
| Raises: | ||
| ValueError: If the messages list is empty. | ||
| """ | ||
| if not messages: | ||
| raise ValueError("Messages list cannot be empty") | ||
|
|
||
| if len(messages) == 1: | ||
| return list(messages) | ||
|
|
||
| history_lines = self._format_history(messages=messages[:-1]) | ||
| current_parts = [piece.converted_value for piece in messages[-1].message_pieces] | ||
|
|
||
| combined = ( | ||
| "[Conversation History]\n" + "\n".join(history_lines) + "\n\n[Current Message]\n" + "\n".join(current_parts) | ||
| ) | ||
|
|
||
| return [Message.from_prompt(prompt=combined, role="user")] | ||
|
|
||
| def _format_history(self, *, messages: list[Message]) -> list[str]: | ||
| """ | ||
| Format prior messages as ``Role: content`` lines. | ||
|
|
||
| Args: | ||
| messages: The history messages to format. | ||
|
|
||
| Returns: | ||
| list[str]: One line per message piece. | ||
| """ | ||
| lines: list[str] = [] | ||
| for msg in messages: | ||
| lines.extend(f"{piece.api_role.capitalize()}: {piece.converted_value}" for piece in msg.message_pieces) | ||
| return lines |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
134 changes: 134 additions & 0 deletions
134
pyrit/prompt_target/common/conversation_normalization_pipeline.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,134 @@ | ||
| # Copyright (c) Microsoft Corporation. | ||
| # Licensed under the MIT license. | ||
|
|
||
| import logging | ||
|
|
||
| from pyrit.message_normalizer import ( | ||
| GenericSystemSquashNormalizer, | ||
| HistorySquashNormalizer, | ||
| MessageListNormalizer, | ||
| ) | ||
| from pyrit.models import Message | ||
| from pyrit.prompt_target.common.target_capabilities import ( | ||
| CapabilityHandlingPolicy, | ||
| CapabilityName, | ||
| TargetCapabilities, | ||
| UnsupportedCapabilityBehavior, | ||
| ) | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| # --------------------------------------------------------------------------- | ||
| # Single registry: add new normalizable capabilities here and nowhere else. | ||
| # Order in the list determines pipeline execution order. | ||
| # --------------------------------------------------------------------------- | ||
| _NORMALIZER_REGISTRY: list[tuple[CapabilityName, MessageListNormalizer[Message]]] = [ | ||
| (CapabilityName.SYSTEM_PROMPT, GenericSystemSquashNormalizer()), | ||
| (CapabilityName.MULTI_TURN, HistorySquashNormalizer()), | ||
| ] | ||
|
|
||
| # Derived constant — no manual maintenance required. | ||
| NORMALIZABLE_CAPABILITIES: frozenset[CapabilityName] = frozenset(cap for cap, _ in _NORMALIZER_REGISTRY) | ||
|
|
||
|
|
||
| class ConversationNormalizationPipeline: | ||
| """ | ||
| Ordered sequence of message normalizers that adapt conversations when | ||
| the target lacks certain capabilities. | ||
|
|
||
| The pipeline is constructed via ``from_capabilities``, which resolves | ||
| capabilities and policy into a concrete, ordered tuple of normalizers. | ||
| ``normalize_async`` then simply executes that tuple in order. | ||
|
|
||
| To add a new normalizable capability, add a single entry to | ||
| ``_NORMALIZER_REGISTRY``. ``NORMALIZABLE_CAPABILITIES``, | ||
| pipeline ordering, and default normalizers are all derived from it. | ||
| """ | ||
|
|
||
| def __init__(self, normalizers: tuple[MessageListNormalizer[Message], ...] = ()) -> None: | ||
| """ | ||
| Initialize the normalization pipeline with an ordered sequence of normalizers. | ||
|
|
||
| Args: | ||
| normalizers (tuple[MessageListNormalizer[Message], ...]): | ||
| Ordered normalizers to apply during ``normalize_async``. | ||
| Defaults to an empty tuple (pass-through). | ||
| """ | ||
| self._normalizers = normalizers | ||
|
|
||
| @classmethod | ||
| def from_capabilities( | ||
| cls, | ||
| *, | ||
| capabilities: TargetCapabilities, | ||
| policy: CapabilityHandlingPolicy, | ||
| normalizer_overrides: dict[CapabilityName, MessageListNormalizer[Message]] | None = None, | ||
| ) -> "ConversationNormalizationPipeline": | ||
| """ | ||
| Resolve capabilities and policy into a concrete pipeline of normalizers. | ||
|
|
||
| For each capability in ``_NORMALIZER_REGISTRY`` (in order): | ||
|
|
||
| * If the target already supports the capability, no normalizer is added. | ||
| * If the capability is missing and the policy is ``ADAPT``, the | ||
| corresponding normalizer (from overrides or defaults) is added. | ||
| * If the capability is missing and the policy is ``RAISE``, a | ||
| ``ValueError`` is raised immediately. | ||
|
|
||
| Args: | ||
| capabilities (TargetCapabilities): The target's declared capabilities. | ||
| policy (CapabilityHandlingPolicy): How to handle each missing capability. | ||
| normalizer_overrides (dict[CapabilityName, MessageListNormalizer[Message]] | None): | ||
| Optional overrides for specific capability normalizers. | ||
| Falls back to the defaults from ``_NORMALIZER_REGISTRY``. | ||
|
|
||
| Returns: | ||
| ConversationNormalizationPipeline: A pipeline with the resolved | ||
| ordered tuple of normalizers. | ||
|
|
||
| Raises: | ||
| ValueError: If a required capability is missing and the policy is RAISE. | ||
| """ | ||
| overrides = normalizer_overrides or {} | ||
| normalizers: list[MessageListNormalizer[Message]] = [] | ||
|
|
||
| for capability, default_normalizer in _NORMALIZER_REGISTRY: | ||
| if capabilities.includes(capability=capability): | ||
| continue | ||
|
|
||
| behavior = policy.get_behavior(capability=capability) | ||
|
|
||
| if behavior == UnsupportedCapabilityBehavior.RAISE: | ||
| raise ValueError(f"Target does not support '{capability.value}' and the handling policy is RAISE.") | ||
|
|
||
| normalizer = overrides.get(capability, default_normalizer) | ||
|
|
||
| normalizers.append(normalizer) | ||
|
|
||
| return cls(normalizers=tuple(normalizers)) | ||
|
|
||
| async def normalize_async(self, *, messages: list[Message]) -> list[Message]: | ||
| """ | ||
| Run the pre-resolved normalizer sequence over the messages. | ||
|
|
||
| Args: | ||
| messages (list[Message]): The full conversation to normalize. | ||
|
|
||
| Returns: | ||
| list[Message]: The (possibly adapted) message list. | ||
| """ | ||
| result = list(messages) | ||
| for normalizer in self._normalizers: | ||
| result = await normalizer.normalize_async(result) | ||
| return result | ||
|
|
||
| @property | ||
| def normalizers(self) -> tuple[MessageListNormalizer[Message], ...]: | ||
| """ | ||
| The ordered normalizers in this pipeline. | ||
|
|
||
| Returns: | ||
| tuple[MessageListNormalizer[Message], ...]: The normalizer sequence. | ||
| """ | ||
| return self._normalizers | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.