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
3 changes: 1 addition & 2 deletions .azuredevops/adversarial-benchmark.yml
Original file line number Diff line number Diff line change
Expand Up @@ -260,8 +260,7 @@ jobs:
fi

echo "start-server" > "$artifact_dir/phase.txt"
uv run pyrit_scan \
--start-server \
uv run pyrit_scan start-server \
--config-file "$config_file" \
--log-level "$LOG_LEVEL_INPUT" \
--startup-timeout 180
Expand Down
6 changes: 3 additions & 3 deletions doc/code/scenarios/3_adaptive_scenarios.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -928,15 +928,15 @@
"\n",
"```bash\n",
"# Basic run with defaults\n",
"pyrit_scan --scenario TextAdaptive --target openai_chat\n",
"pyrit_scan run adaptive.text_adaptive --target openai_chat\n",
"\n",
"# Tune max attempts and restrict techniques\n",
"pyrit_scan --scenario TextAdaptive --target openai_chat \\\n",
"pyrit_scan run adaptive.text_adaptive --target openai_chat \\\n",
" --params max_attempts_per_objective=5 \\\n",
" --techniques single_turn\n",
"\n",
"# Use specific datasets and limit size\n",
"pyrit_scan --scenario TextAdaptive --target openai_chat \\\n",
"pyrit_scan run adaptive.text_adaptive --target openai_chat \\\n",
" --datasets airt_hate airt_violence \\\n",
" --max-total 10\n",
"```"
Expand Down
6 changes: 3 additions & 3 deletions doc/code/scenarios/3_adaptive_scenarios.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,15 +322,15 @@ def _technique_label(result) -> str:
#
# ```bash
# # Basic run with defaults
# pyrit_scan --scenario TextAdaptive --target openai_chat
# pyrit_scan run adaptive.text_adaptive --target openai_chat
#
# # Tune max attempts and restrict techniques
# pyrit_scan --scenario TextAdaptive --target openai_chat \
# pyrit_scan run adaptive.text_adaptive --target openai_chat \
# --params max_attempts_per_objective=5 \
# --techniques single_turn
#
# # Use specific datasets and limit size
# pyrit_scan --scenario TextAdaptive --target openai_chat \
# pyrit_scan run adaptive.text_adaptive --target openai_chat \
# --datasets airt_hate airt_violence \
# --max-total 10
# ```
2 changes: 1 addition & 1 deletion doc/scanner/airt.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -730,7 +730,7 @@
"sends each objective without translation and is included by default.\n",
"\n",
"```bash\n",
"pyrit_scan airt.multilingual \\\n",
"pyrit_scan run airt.multilingual \\\n",
" --initializers target \\\n",
" --target openai_chat \\\n",
" --datasets harmbench \\\n",
Expand Down
2 changes: 1 addition & 1 deletion doc/scanner/airt.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@
# sends each objective without translation and is included by default.
#
# ```bash
# pyrit_scan airt.multilingual \
# pyrit_scan run airt.multilingual \
# --initializers target \
# --target openai_chat \
# --datasets harmbench \
Expand Down
12 changes: 6 additions & 6 deletions doc/scanner/garak.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -458,8 +458,8 @@
"**CLI examples:**\n",
"\n",
"```bash\n",
"pyrit_scan garak.figstep --target openai_chat --datasets figstep --max-total 1\n",
"pyrit_scan garak.figstep --target openai_chat --datasets figstep_pro --max-total 1\n",
"pyrit_scan run garak.figstep --target openai_chat --datasets figstep --max-total 1\n",
"pyrit_scan run garak.figstep --target openai_chat --datasets figstep_pro --max-total 1\n",
"```\n",
"\n",
"> **Note:** The objective target must natively support multi-piece user messages and accept text\n",
Expand Down Expand Up @@ -1504,7 +1504,7 @@
"**CLI example:**\n",
"\n",
"```bash\n",
"pyrit_scan garak.system_prompt_extraction --target openai_chat --techniques direct_requests\n",
"pyrit_scan run garak.system_prompt_extraction --target openai_chat --techniques direct_requests\n",
"```\n",
"\n",
"**Available techniques** (9 categories): DirectRequests, RolePlayingAttacks, EncodingBasedAttacks,\n",
Expand Down Expand Up @@ -1681,10 +1681,10 @@
"\n",
"```bash\n",
"# Run the default Rust technique.\n",
"pyrit_scan garak.package_hallucination --target openai_chat\n",
"pyrit_scan run garak.package_hallucination --target openai_chat\n",
"\n",
"# Select another supported language.\n",
"pyrit_scan garak.package_hallucination --target openai_chat --techniques dart\n",
"pyrit_scan run garak.package_hallucination --target openai_chat --techniques dart\n",
"```\n",
"\n",
"**Available techniques** (7 languages): Python, JavaScript, Ruby, Rust, Dart, Perl, Raku.\n",
Expand Down Expand Up @@ -1842,7 +1842,7 @@
"**CLI example:**\n",
"\n",
"```bash\n",
"pyrit_scan garak.audio_achilles_heel --target azure_openai_realtime --max-total 2\n",
"pyrit_scan run garak.audio_achilles_heel --target azure_openai_realtime --max-total 2\n",
"```\n",
"\n",
"> **Note:** The objective target must accept `audio_path` input (i.e. be multimodal). The example\n",
Expand Down
12 changes: 6 additions & 6 deletions doc/scanner/garak.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,8 +181,8 @@
# **CLI examples:**
#
# ```bash
# pyrit_scan garak.figstep --target openai_chat --datasets figstep --max-total 1
# pyrit_scan garak.figstep --target openai_chat --datasets figstep_pro --max-total 1
# pyrit_scan run garak.figstep --target openai_chat --datasets figstep --max-total 1
# pyrit_scan run garak.figstep --target openai_chat --datasets figstep_pro --max-total 1
# ```
#
# > **Note:** The objective target must natively support multi-piece user messages and accept text
Expand Down Expand Up @@ -486,7 +486,7 @@
# **CLI example:**
#
# ```bash
# pyrit_scan garak.system_prompt_extraction --target openai_chat --techniques direct_requests
# pyrit_scan run garak.system_prompt_extraction --target openai_chat --techniques direct_requests
# ```
#
# **Available techniques** (9 categories): DirectRequests, RolePlayingAttacks, EncodingBasedAttacks,
Expand Down Expand Up @@ -530,10 +530,10 @@
#
# ```bash
# # Run the default Rust technique.
# pyrit_scan garak.package_hallucination --target openai_chat
# pyrit_scan run garak.package_hallucination --target openai_chat
#
# # Select another supported language.
# pyrit_scan garak.package_hallucination --target openai_chat --techniques dart
# pyrit_scan run garak.package_hallucination --target openai_chat --techniques dart
# ```
#
# **Available techniques** (7 languages): Python, JavaScript, Ruby, Rust, Dart, Perl, Raku.
Expand Down Expand Up @@ -572,7 +572,7 @@
# **CLI example:**
#
# ```bash
# pyrit_scan garak.audio_achilles_heel --target azure_openai_realtime --max-total 2
# pyrit_scan run garak.audio_achilles_heel --target azure_openai_realtime --max-total 2
# ```
#
# > **Note:** The objective target must accept `audio_path` input (i.e. be multimodal). The example
Expand Down
110 changes: 33 additions & 77 deletions pyrit/cli/pyrit_scan.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,9 +283,9 @@ def _build_global_parser() -> ArgumentParser:
"""
Union of every option group.

Used *only* by the legacy shim to strip options and locate a verb; it is never
attached to a command. Keeping it a union (rather than the per-command groups)
lets the shim reorder any option placed before a verb, regardless of which
Used *only* by ``_move_verb_to_front`` to strip options and locate a verb; it is
never attached to a command. Keeping it a union (rather than the per-command
groups) lets any option placed before a verb be reordered, regardless of which
command ultimately owns it.

Returns:
Expand Down Expand Up @@ -517,7 +517,7 @@ def _discover_verbs() -> frozenset[str]:
return frozenset[str]()


#: Every valid subcommand verb (used by the legacy-argv shim to detect new-style calls).
#: Every valid subcommand verb (used by ``_move_verb_to_front`` to find the verb).
#: Derived from _build_parser so adding/renaming a subcommand can't leave this stale.
_KNOWN_VERBS: frozenset[str] = _discover_verbs()

Expand Down Expand Up @@ -636,96 +636,42 @@ def _extract_scenario_args(*, parsed: Namespace) -> dict[str, Any]:
}


#: Legacy "mode flag" → new subcommand verb, used by the back-compat shim.
#: ``--start-server`` is intentionally absent: it stays a global modifier flag and
#: only maps to the ``start-server`` verb when it appears with no other command.
_LEGACY_COMMAND_FLAGS: dict[str, str] = {
"--list-scenarios": "list-scenarios",
"--list-initializers": "list-initializers",
"--list-targets": "list-targets",
"--list-converters": "list-converters",
"--list-datasets": "list-datasets",
"--add-initializer": "add-initializer",
"--stop-server": "stop-server",
}


def _warn_legacy(*, old: str, new: str) -> None:
"""Warn (visibly and via ``DeprecationWarning``) about a legacy ``pyrit_scan`` invocation."""
from pyrit.common import print_deprecation_message

print_deprecation_message(old_item=f"pyrit_scan {old}", new_item=f"pyrit_scan {new}", removed_in="1.3.0")
# DeprecationWarning is suppressed by default in a CLI, so also print a visible note.
print(f"Note: 'pyrit_scan {old}' is deprecated; use 'pyrit_scan {new}' instead.", file=sys.stderr)


def _translate_legacy_argv(argv: list[str]) -> list[str]:
def _move_verb_to_front(argv: list[str]) -> list[str]:
"""
Rewrite legacy flag-style invocations into the new subcommand form.
Move a verb that follows global options to the front of the argument list.

Back-compat shim for one release. Maps ``--list-scenarios`` → ``list-scenarios``
etc., a bare ``<scenario>`` → ``run <scenario>`` (implicit run), and a standalone
``--start-server`` → the ``start-server`` verb, emitting a deprecation warning
for each. It also (without warning) moves a new-style verb to the front when it
was placed after global options (e.g. ``--server-url X list-scenarios``), so
globals work before or after the verb. New-style calls that already start with a
verb pass through untouched, as does the brand-new ``scenario-results`` surface
(no legacy form). Delete this function when the deprecation window closes.
Global options may be given before or after the verb (for example
``--server-url X list-scenarios``). The verb's sub-parser has to see them, so a
verb found after the global options is moved to the front. Anything else,
including top-level ``--help``, is returned unchanged for argparse to handle.

Args:
argv (list[str]): The raw argument list (already ``sys.argv[1:]``).

Returns:
list[str]: The possibly-rewritten argument list to feed to argparse.
list[str]: The argument list with the verb first, when one was found.
"""
if not argv or argv[0] in _KNOWN_VERBS or argv[0] in ("-h", "--help"):
return argv

# A legacy command flag anywhere in argv → prepend its verb, drop the flag.
for index, token in enumerate(argv):
verb = _LEGACY_COMMAND_FLAGS.get(token)
if verb is not None:
_warn_legacy(old=token, new=verb)
return [verb, *argv[:index], *argv[index + 1 :]]

# No legacy command flag. Strip global options with the global parser and
# inspect what remains.
# Strip global options with the global parser and see whether a verb follows.
_, leftover = _build_global_parser().parse_known_args(argv)
if leftover:
if leftover[0] in _KNOWN_VERBS:
# A new-style verb placed after global options (e.g.
# ``--server-url X list-scenarios``). Move the verb to the front so its
# sub-parser sees the globals. This is valid ordering, not a legacy
# form, so it does not warn.
verb = leftover[0]
index = argv.index(verb)
return [verb, *argv[:index], *argv[index + 1 :]]
if leftover[0] in ("-h", "--help"):
# Global options followed by top-level help (e.g. ``--server-url X --help``).
# Leave argv untouched so the root parser prints its own help instead of
# misreading ``--help`` as an implicit scenario name.
return argv
# Otherwise it is a bare scenario name (+ run flags) → implicit run.
_warn_legacy(old="<scenario> (implicit run)", new="run <scenario>")
return ["run", *argv]

# Only global options remained: a standalone --start-server means "just start".
if "--start-server" in argv:
_warn_legacy(old="--start-server", new="start-server")
return ["start-server", *[token for token in argv if token != "--start-server"]]

if leftover and leftover[0] in _KNOWN_VERBS:
verb = leftover[0]
index = argv.index(verb)
return [verb, *argv[:index], *argv[index + 1 :]]
return argv


def parse_args(args: list[str] | None = None) -> Namespace:
"""
Parse command-line arguments (pass 1 — tolerant of scenario-declared flags).

The raw argv is first run through ``_translate_legacy_argv`` (the back-compat
shim). Pass 1 then uses ``parse_known_args`` so scenario-specific flags (e.g.
The raw argv is first run through ``_move_verb_to_front``, so global options
work before or after the verb. Pass 1 then uses ``parse_known_args`` so scenario-specific flags (e.g.
``--max-turns 7``) don't error before we've fetched the scenario's declared
parameters. Unknown leftovers are stashed on the Namespace as ``_unknown_args``,
and the translated argv as ``_translated_args``, for the ``run`` reparse.
and the reordered argv as ``_translated_args``, for the ``run`` reparse.

Args:
args: Argument list (``sys.argv[1:]`` when None).
Expand All @@ -734,7 +680,7 @@ def parse_args(args: list[str] | None = None) -> Namespace:
Namespace: Parsed command-line arguments.
"""
raw_args = list(args) if args is not None else list(sys.argv[1:])
translated = _translate_legacy_argv(raw_args)
translated = _move_verb_to_front(raw_args)
parser = _build_parser(add_help=True)
parsed, unknown = parser.parse_known_args(translated)
parsed._unknown_args = unknown
Expand Down Expand Up @@ -1531,10 +1477,20 @@ def main(args: list[str] | None = None) -> int:
except SystemExit as e:
return e.code if isinstance(e.code, int) else 1

# No verb at all: show the top-level help listing the subcommands.
# No verb at all: show the top-level help listing the subcommands. Arguments
# without a verb (such as a scenario name or a flag) are a usage error.
if getattr(parsed_args, "command", None) is None:
_build_parser().print_help()
return 0
parser = _build_parser()
if not parsed_args._translated_args:
parser.print_help()
return 0
parser.print_usage(sys.stderr)
print(
f"{parser.prog}: error: a command is required "
f"(got: {' '.join(parsed_args._translated_args)}); see '{parser.prog} --help'",
file=sys.stderr,
)
return 2
Comment thread
romanlutz marked this conversation as resolved.
Resolved

# Unknown flags are only expected for `run` (scenario-declared flags, resolved
# in the reparse). For any other verb they are genuinely unrecognized.
Expand Down
2 changes: 1 addition & 1 deletion pyrit/scenario/core/scenario.py
Original file line number Diff line number Diff line change
Expand Up @@ -587,7 +587,7 @@ def supported_parameters(cls) -> list[Parameter]:
common case). Override *this* method only to **remove or replace** a common input,
composing against ``super().supported_parameters()``.

Implemented as a classmethod so ``--list-scenarios`` can introspect without
Implemented as a classmethod so ``list-scenarios`` can introspect without
instantiating.

Returns:
Expand Down
2 changes: 1 addition & 1 deletion pyrit/setup/initializers/preload_scenario_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
Each registered ``Scenario`` is instantiated once so the registry can read the
strategy class, default strategy, and default dataset configuration off the
instance. The results are cached on ``Registry._metadata_cache``; the
first ``--list-scenarios`` / GUI call is then a cache hit. Per-scenario
first ``list-scenarios`` / GUI call is then a cache hit. Per-scenario
instantiation failures surface loudly here at startup rather than later.
"""

Expand Down
Loading
Loading