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
2 changes: 1 addition & 1 deletion doc/code/framework.md
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ Core components are pluggable bricks. Each one can be swapped, combined, or repl
- Adapt messages to what the target supports with its `TargetConfiguration` and message normalizer.
- Return what the target produced. A response can hold several pieces or tool calls, or none.
- Return a content-filter block as a blocked response (`error="blocked"`), not an exception, so scorers can detect it.
- If the target runs tools itself, bound its tool loop. When the target's own tool infrastructure fails (`ToolInfrastructureError`), answer every pending call and end the turn with an error response that says why (`ToolLoopStop`), instead of asking the model to fix it.
- If the target runs tools itself, bound its tool loop with the shared `run_tool_loop_async` in `pyrit/prompt_target/common/tool_loop.py`, so a tool behaves the same on every target. When the target's own tool infrastructure fails (`ToolInfrastructureError`), answer every pending call and end the turn with an error response that says why (`ToolLoopStop`), instead of asking the model to fix it.
- Retry only transient target errors, such as rate limits.
- **Does not own**: what to send or what to do with the response. Converting (converters), scoring (scorers), conversation flow (attacks), and persistence (the prompt normalizer) belong elsewhere.

Expand Down
4 changes: 4 additions & 0 deletions doc/code/targets/0_prompt_targets.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,13 +101,17 @@ Here are some examples:
| Example | Chat-style target? | Notes |
|-------------------------------------|---------------------------------------------------|-------------------------------------------------------------------------------------------------|
| **OpenAIChatTarget** (e.g., GPT-4) | **Yes** (multi-turn + editable history) | Designed for conversational prompts (system messages, conversation history, etc.). |
| **ClaudeChatTarget** | **Yes** (multi-turn + editable history) | Native Anthropic Messages via LiteLLM, with text/images and bounded local tool execution. |
| **OpenAIImageTarget** | **No** | Used for image generation; does not manage conversation history. |
| **HTTPTarget** | **No** | Generic HTTP target. Some apps might allow conversation history, but this target doesn't handle it. |
| **A2ATarget** | **No** (multi-turn, but no editable history) | Text-only Agent-to-Agent endpoints through the official a2a-sdk (v0.3 / v1.0). |
| **AzureBlobStorageTarget** | **No** | Used primarily for storage; not for conversation-based AI. |

## OpenAI SDK compatibility

For Claude installation, authentication, capabilities, JSON output, and a harmless
async tool example, see [Claude chat target](claude_chat_target.md).

PyRIT supports OpenAI Python SDK 2.20 and later 2.x releases, and SDK 3.x.
The upper bound excludes SDK 4 until it has been evaluated. The compatibility
tests exercise both SDK lines with fabricated provider responses, including
Expand Down
122 changes: 122 additions & 0 deletions doc/code/targets/claude_chat_target.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
# Claude chat target

`ClaudeChatTarget` uses LiteLLM's native Anthropic Messages transport, not an
OpenAI-compatible proxy. Install `pip install "pyrit[litellm]"` (also included in
`pyrit[all]`). Production Docker installs include this extra. A basic PyRIT install
can still import the target; sending without LiteLLM raises an installation error.
LiteLLM 1.108.0 or later is required so tool-based JSON adaptation preserves user
calls alongside its internal formatting calls.

Set `ANTHROPIC_API_KEY`, or pass `api_key` explicitly. Sync and async callables
returning a current token are also accepted and resolved for each completion.
`endpoint` and `headers` are per-target overrides; no global environment is changed.
The target ignores generic `LITELLM_API_KEY` and `LITELLM_ENDPOINT` settings.
Operational OAuth login/refresh and Key Vault registration are outside this target.

Raw names such as `claude-sonnet-4-6` and `anthropic/claude-sonnet-4-6` resolve to
the same route and identity. Other provider prefixes are rejected. Known Claude
4.5/4.6 aliases declare multi-turn, system prompts, editable history, text/image
inputs, tool history, and JSON output. Unknown names use LiteLLM metadata with a
conservative fallback. Use `custom_configuration` for verified deployment-specific
capabilities; it takes precedence. The known profiles do **not** promise strict
native JSON-schema output.

## Harmless async tool

Run this in an async application or notebook after configuring credentials:

```python
from pyrit.models import JsonResponseConfig, MessagePiece
from pyrit.prompt_normalizer import PromptNormalizer
from pyrit.prompt_target import ClaudeChatTarget, tool
from pyrit.setup import IN_MEMORY, initialize_pyrit_async

await initialize_pyrit_async(memory_db_type=IN_MEMORY)


@tool
async def add_one_async(*, value: int) -> int:
"""Add one to a number."""
return value + 1


target = ClaudeChatTarget(
model_name="claude-sonnet-4-6",
tools=[add_one_async],
max_tool_rounds=2,
max_tokens=512,
)
normalizer = PromptNormalizer()
reply = await normalizer.send_prompt_async(
target=target,
conversation_id="claude-example",
message=MessagePiece(
role="user",
original_value="Use add_one_async for 7, then return a JSON object with the answer.",
prompt_metadata=JsonResponseConfig(enabled=True).to_metadata(),
).to_message(),
)
print(reply.get_value())

follow_up = await normalizer.send_prompt_async(
target=target,
conversation_id="claude-example",
message=MessagePiece(role="user", original_value="What was the result? Do not call tools again.").to_message(),
)
```

`tools` accepts typed `Tool` instances; `tool_providers` discovers tools within
each provider's execution scope. `@tool` derives a schema from the async
function's typed keyword parameters. Automatic execution requires `n=1`.
`execute_tools=False` advertises tools but returns assistant calls without
executing them. Declaring wire tools only through `extra_body_parameters` does
not install executable implementations.

Tools run through the same bounded loop as `OpenAIResponseTarget`, so a tool
behaves identically on both targets. The loop handles multiple calls per
completion and multiple rounds. `max_tool_rounds` defaults to 10; zero advertises tools without executing
a returned batch. Each round counts one completion with user-tool calls, not
each individual call or the terminal JSON formatter.

For unconstrained JSON-object requests, the target advertises a reserved internal
formatting tool, `pyrit_claude_json_output`, and converts its arguments to response
text, without validating it; parse the reply as you would any target's JSON.
It is never locally executed or counted against the tool budget. With user
tools present, Anthropic can choose those tools before formatting the final answer.
Explicit JSON schemas use the shared configuration/normalization path and
LiteLLM's Anthropic adaptation. Never register the reserved formatter as a user tool.

Unknown tools and malformed or invalid arguments produce tool-result error
payloads so the model can correct the call. Exceptions raised by a tool, an
unserializable result, and a failed continuation request propagate to the
caller, as with `OpenAIResponseTarget`. Reused/missing call IDs and truncated
calls stop execution with an explicit processing-error response. Calls beyond
the round budget receive unexecuted error results and a terminal processing
error. Every such early stop records its reason as `ToolLoopStop` metadata on
the error response. Tools can raise `ToolInfrastructureError` (exported from `pyrit.prompt_target`)
when their own infrastructure fails or the execution outcome is unknown.
This stops the turn without another model request. The failing call receives
an error result marked as invoked unless the tool explicitly reports
`ToolInfrastructureError(..., invoked=False)` because nothing ran; remaining calls receive uninvoked error
results, followed by a terminal processing-error response. Earlier successful
results remain in history. Argument errors still go back to the model so it
can recover.
Cancellation propagates and scoped provider resources are closed.

Targets return all interaction messages; `PromptNormalizer` persists them in
order and returns the last response. Later sends through the same conversation
replay stored user calls/results. Invalid/truncated calls marked as processing
errors are not replayed. Do not blindly resubmit a cancelled interaction whose
external effects may already have occurred.

## Opt-in integration coverage

The unit tests mock external HTTP only and exercise the actual LiteLLM Anthropic
adapter, including system/image requests, tools, JSON, and isolated-memory replay.
Live tests require both `RUN_ALL_TESTS=true` and `RUN_ANTHROPIC_TESTS=true`, plus
an explicitly authorized `ANTHROPIC_API_KEY`. These tests make billable API calls;
`ANTHROPIC_MODEL` can override the default `claude-sonnet-4-6`.

```text
uv run --frozen --extra litellm -m pytest tests/integration/targets/test_claude_chat_target_integration.py
```
1 change: 1 addition & 0 deletions doc/myst.yml
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ project:
- file: code/targets/use_huggingface_chat_target.ipynb
- file: code/targets/websocket_target.ipynb
- file: code/targets/round_robin_target.ipynb
- file: code/targets/claude_chat_target.md
- file: code/converters/0_converters.ipynb
children:
- file: code/converters/1_text_to_text_converters.ipynb
Expand Down
8 changes: 6 additions & 2 deletions docker/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,13 @@ COPY --chown=vscode:vscode doc/ /app/doc/
# Note: We use 'uv pip' because the devcontainer creates venv with uv (no pip by default)
RUN set -eu; if [ "$PYRIT_SOURCE" = "pypi" ]; then \
echo "Installing PyRIT from PyPI version: $PYRIT_VERSION"; \
uv pip install --python /opt/venv/bin/python pyrit[speech,opencv,fairness_bias,fastapi,playwright,github-copilot]==$PYRIT_VERSION; \
uv pip install --python /opt/venv/bin/python pyrit[speech,opencv,fairness_bias,fastapi,playwright,github-copilot,litellm]==$PYRIT_VERSION; \
echo "Removing local source so the installed PyPI package isn't shadowed"; \
rm -rf /app/pyrit /app/frontend /app/build_scripts /app/pyproject.toml /app/MANIFEST.in /app/README.md /app/LICENSE; \
elif [ "$PYRIT_SOURCE" = "local" ]; then \
echo "Installing PyRIT from local source"; \
export PYRIT_SOURCE_COMMIT="$GIT_COMMIT" PYRIT_SOURCE_DIRTY="$GIT_MODIFIED"; \
uv pip install --python /opt/venv/bin/python -e .[speech,opencv,fairness_bias,fastapi,playwright,github-copilot]; \
uv pip install --python /opt/venv/bin/python -e .[speech,opencv,fairness_bias,fastapi,playwright,github-copilot,litellm]; \
echo "Building frontend..."; \
if [ "$GIT_MODIFIED" = "true" ]; then \
/opt/venv/bin/python -m build_scripts.prepare_package --development; \
Expand All @@ -74,6 +74,10 @@ RUN set -eu; if [ "$PYRIT_SOURCE" = "pypi" ]; then \
echo "Invalid PYRIT_SOURCE"; exit 1; \
fi && \
cd /tmp && \
/opt/venv/bin/python -c "import litellm" && \
if [ "$PYRIT_SOURCE" = "local" ]; then \
/opt/venv/bin/python -c "from pyrit.prompt_target import ClaudeChatTarget"; \
fi && \
if ! /opt/venv/bin/python -c "from pyrit._compatibility import get_compatibility_id; print(get_compatibility_id())"; then \
if [ "$PYRIT_SOURCE" = "pypi" ]; then \
echo "ERROR: Selected PyPI release $PYRIT_VERSION lacks valid compatibility metadata." >&2; \
Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ speech = [
]

litellm = [
"litellm>=1.104.2",
"litellm>=1.108.0",
]

github-copilot = [
Expand All @@ -182,7 +182,7 @@ all = [
"github-copilot-sdk>=1.0.28",
"ipykernel>=6.29.5",
"jupyter>=1.1.1",
"litellm>=1.104.2",
"litellm>=1.108.0",
"ollama>=0.5.1",
"opencv-python>=4.11.0.86",
"playwright>=1.49.0",
Expand Down
1 change: 1 addition & 0 deletions pyrit/models/target/tool_execution_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ class ToolLoopStopReason(str, Enum):

MAX_TOOL_ROUNDS_EXHAUSTED = "max_tool_rounds_exhausted"
TOOL_INFRASTRUCTURE_ERROR = "tool_infrastructure_error"
INVALID_TOOL_CALLS = "invalid_tool_calls"


class ToolLoopStop(BaseModel):
Expand Down
2 changes: 2 additions & 0 deletions pyrit/prompt_target/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from pyrit.prompt_target.a2a_target import A2ATarget
from pyrit.prompt_target.azure_blob_storage_target import AzureBlobStorageTarget
from pyrit.prompt_target.azure_ml_chat_target import AzureMLChatTarget
from pyrit.prompt_target.claude_chat_target import ClaudeChatTarget
from pyrit.prompt_target.common.conversation_normalization_pipeline import ConversationNormalizationPipeline
from pyrit.prompt_target.common.discover_target_capabilities import discover_target_capabilities_async
from pyrit.prompt_target.common.mcp_tool_provider import (
Expand Down Expand Up @@ -83,6 +84,7 @@
"CapabilityName": "pyrit.prompt_target.common.target_capabilities",
"CapabilityHandlingPolicy": "pyrit.prompt_target.common.target_capabilities",
"CHAT_TARGET_REQUIREMENTS": "pyrit.prompt_target.common.target_requirements",
"ClaudeChatTarget": "pyrit.prompt_target.claude_chat_target",
"CopilotType": "pyrit.prompt_target.playwright_copilot_target",
"ConversationNormalizationPipeline": "pyrit.prompt_target.common.conversation_normalization_pipeline",
"FunctionTool": "pyrit.prompt_target.common.tool_provider",
Expand Down
Loading
Loading