diff --git a/doc/code/framework.md b/doc/code/framework.md index b3b05a0614..1a27fe453c 100644 --- a/doc/code/framework.md +++ b/doc/code/framework.md @@ -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. diff --git a/doc/code/targets/0_prompt_targets.md b/doc/code/targets/0_prompt_targets.md index 3e7fb9d329..b4c15bb087 100644 --- a/doc/code/targets/0_prompt_targets.md +++ b/doc/code/targets/0_prompt_targets.md @@ -101,6 +101,7 @@ 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). | @@ -108,6 +109,9 @@ Here are some examples: ## 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 diff --git a/doc/code/targets/claude_chat_target.md b/doc/code/targets/claude_chat_target.md new file mode 100644 index 0000000000..60583fe256 --- /dev/null +++ b/doc/code/targets/claude_chat_target.md @@ -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 +``` diff --git a/doc/myst.yml b/doc/myst.yml index 5bdfc174db..07aab1088b 100644 --- a/doc/myst.yml +++ b/doc/myst.yml @@ -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 diff --git a/docker/Dockerfile b/docker/Dockerfile index d9e7cb3fda..b9bf817d6c 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -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; \ @@ -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; \ diff --git a/pyproject.toml b/pyproject.toml index b3f2fe6e1d..afda451ad0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -162,7 +162,7 @@ speech = [ ] litellm = [ - "litellm>=1.104.2", + "litellm>=1.108.0", ] github-copilot = [ @@ -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", diff --git a/pyrit/models/target/tool_execution_metadata.py b/pyrit/models/target/tool_execution_metadata.py index e505c0237c..1609f919c9 100644 --- a/pyrit/models/target/tool_execution_metadata.py +++ b/pyrit/models/target/tool_execution_metadata.py @@ -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): diff --git a/pyrit/prompt_target/__init__.py b/pyrit/prompt_target/__init__.py index 9cb84236c7..8e6d837c19 100644 --- a/pyrit/prompt_target/__init__.py +++ b/pyrit/prompt_target/__init__.py @@ -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 ( @@ -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", diff --git a/pyrit/prompt_target/claude_chat_target.py b/pyrit/prompt_target/claude_chat_target.py new file mode 100644 index 0000000000..21d6cce44f --- /dev/null +++ b/pyrit/prompt_target/claude_chat_target.py @@ -0,0 +1,154 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import re +from collections.abc import Awaitable, Callable, Sequence +from typing import Any + +from pyrit.common import forward_init_parameters +from pyrit.models import ComponentIdentifier, JsonResponseConfig, Message, MessagePiece, construct_response_from_request +from pyrit.models.messages.chat_message import FunctionCall +from pyrit.prompt_target.common.chat_completions_response_parser import capture_usage_and_finish_reason +from pyrit.prompt_target.common.target_configuration import TargetConfiguration +from pyrit.prompt_target.common.tool_call_history import parse_function_call +from pyrit.prompt_target.common.tool_provider import Tool +from pyrit.prompt_target.litellm_chat_target import LiteLLMChatTarget + + +class ClaudeChatTarget(LiteLLMChatTarget): + """Use Claude through LiteLLM's native Anthropic Messages adapter.""" + + _API_KEY_ENVIRONMENT_VARIABLE = "ANTHROPIC_API_KEY" + _ENDPOINT_ENVIRONMENT_VARIABLE = None + _JSON_OUTPUT_TOOL_NAME = "pyrit_claude_json_output" + + @forward_init_parameters + def __init__( + self, + *, + model_name: str, + api_key: str | Callable[[], str | Awaitable[str]] | None = None, + endpoint: str | None = None, + headers: dict[str, str] | None = None, + custom_configuration: TargetConfiguration | None = None, + **kwargs: Any, + ) -> None: + """ + Initialize the native Claude target. + + Args: + model_name: A Claude name, with or without the ``anthropic/`` prefix. + api_key: Explicit API key or sync/async token provider. Defaults to + ``ANTHROPIC_API_KEY``, never ``LITELLM_API_KEY``. + endpoint: Optional Anthropic API base URL; ignores ``LITELLM_ENDPOINT``. + headers: Additional request headers, copied at construction. + custom_configuration: Override model-specific capabilities and policy. + **kwargs: Forwarded LiteLLM generation, tool, and tracing parameters. + + Raises: + ValueError: If the model or passthrough parameters select another provider. + """ + raw_model = model_name.removeprefix("anthropic/") + if re.fullmatch(r"claude-[A-Za-z0-9][A-Za-z0-9._-]*", raw_model) is None: + raise ValueError("model_name must be a Claude name or an anthropic/claude-... route.") + routed_model = f"anthropic/{raw_model}" + underlying = kwargs.pop("underlying_model", raw_model) + if underlying not in (None, raw_model, routed_model): + raise ValueError("underlying_model must match the Claude model_name.") + extra = kwargs.get("extra_body_parameters") or {} + if ( + extra.get("model", routed_model) != routed_model + or extra.get("custom_llm_provider", "anthropic") != "anthropic" + ): + raise ValueError("ClaudeChatTarget requires the native anthropic provider route.") + if {"api_key", "api_base", "headers", "extra_headers", "provider_specific_header"} & extra.keys(): + raise ValueError("Configure Claude credentials, endpoint, and headers through constructor parameters.") + super().__init__( + model_name=routed_model, + underlying_model=raw_model, + api_key=api_key, + headers=dict(headers) if headers is not None else None, + endpoint=endpoint, + custom_configuration=custom_configuration, + **kwargs, + ) + + def _build_identifier(self) -> ComponentIdentifier: + return self._create_identifier( + params={**super()._build_identifier().params, "headers": self._identifier_headers()} + ) + + def _validate_tool_definitions(self, tools: Sequence[Tool]) -> None: + super()._validate_tool_definitions(tools) + names = {tool.name for tool in tools} | { + definition.get("function", {}).get("name") + for definition in (self._extra_body_parameters or {}).get("tools") or [] + } + if self._JSON_OUTPUT_TOOL_NAME in names: + raise ValueError(f"Tool name {self._JSON_OUTPUT_TOOL_NAME!r} is reserved for Claude JSON output.") + + def _construct_request_body( + self, + *, + messages: list[dict[str, Any]], + json_config: JsonResponseConfig, + api_key: str | None = None, + ) -> dict[str, Any]: + body = super()._construct_request_body(messages=messages, json_config=json_config, api_key=api_key) + if not json_config.enabled or json_config.json_schema is not None: + return body + # Anthropic's native schema output cannot represent an unconstrained JSON object, + # and LiteLLM's bare json_object hint does not install a formatting tool. + body.pop("response_format", None) + body["tools"] = [ + *body.get("tools", []), + { + "type": "function", + "function": { + "name": self._JSON_OUTPUT_TOOL_NAME, + "description": "Return the final answer as a JSON object.", + "parameters": {"type": "object", "additionalProperties": True}, + }, + }, + ] + has_user_tools = bool( + len(body["tools"]) > 1 or (not self._suppress_tools and (self._direct_tools or self._tool_providers)) + ) + body.setdefault( + "tool_choice", + "auto" if has_user_tools else {"type": "function", "function": {"name": self._JSON_OUTPUT_TOOL_NAME}}, + ) + return body + + async def _construct_message_from_response_async(self, *, response: Any, request: MessagePiece) -> Message: + message = await super()._construct_message_from_response_async(response=response, request=request) + if not self._get_json_response_config(message_piece=request).enabled or any( + piece.is_truncated or piece.response_error != "none" for piece in message.message_pieces + ): + return message + # The formatting call carries the JSON answer; return it as text, unvalidated, so the + # caller validates it as it does other targets' JSON replies. + formatting: list[MessagePiece] = [] + remaining: list[MessagePiece] = [] + for piece in message.message_pieces: + call = parse_function_call(piece) if piece.converted_value_data_type == "function_call" else None + if ( + call is not None + and isinstance(call.function, FunctionCall) + and call.function.name == self._JSON_OUTPUT_TOOL_NAME + ): + formatting.extend( + construct_response_from_request( + request=request, response_text_pieces=[call.function.arguments], response_type="text" + ).message_pieces + ) + else: + remaining.append(piece) + if not formatting: + return message + cost = message.message_pieces[0].prompt_metadata.get("token_usage_cost") + pieces = [*formatting, *remaining] + capture_usage_and_finish_reason(pieces=pieces, response=response) + if cost is not None: + pieces[0].prompt_metadata["token_usage_cost"] = cost + return Message(message_pieces=pieces) diff --git a/pyrit/prompt_target/common/discover_target_capabilities.py b/pyrit/prompt_target/common/discover_target_capabilities.py index ecc87a89b8..491543c063 100644 --- a/pyrit/prompt_target/common/discover_target_capabilities.py +++ b/pyrit/prompt_target/common/discover_target_capabilities.py @@ -125,10 +125,11 @@ def _json_enforcing_target_types() -> tuple[type[PromptTarget], ...]: Returns: tuple[type[PromptTarget], ...]: The target classes that enforce JSON hints. """ + 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 - return (OpenAIChatTarget, OpenAIResponseTarget) + return (OpenAIChatTarget, OpenAIResponseTarget, LiteLLMChatTarget) # Every text probe sends a text-only payload. Permissive overrides therefore @@ -211,7 +212,7 @@ def _disable_probe_tools(*, target: PromptTarget) -> Generator[None, None, None] 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): + 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 diff --git a/pyrit/prompt_target/common/target_capabilities.py b/pyrit/prompt_target/common/target_capabilities.py index 7c69f8e194..0bb95d92d2 100644 --- a/pyrit/prompt_target/common/target_capabilities.py +++ b/pyrit/prompt_target/common/target_capabilities.py @@ -134,6 +134,16 @@ def __post_init__(self) -> None: output_modalities=_TEXT_OUTPUT, ) +_CLAUDE_4 = TargetCapabilities( + supports_multi_turn=True, + supports_multi_message_pieces=True, + supports_system_prompt=True, + supports_json_output=True, + supports_editable_history=True, + input_modalities=_TEXT_IMAGE_INPUT | TOOL_CALL_INPUT_MODALITIES, + output_modalities=_TEXT_OUTPUT, +) + _GPT_REALTIME_1_5 = TargetCapabilities( supports_multi_turn=True, supports_multi_message_pieces=True, @@ -177,6 +187,11 @@ def __post_init__(self) -> None: "gpt-realtime-1.5": _GPT_REALTIME_1_5, "tts": _TTS, "sora-2": _SORA_2, + "claude-sonnet-4-6": _CLAUDE_4, + "claude-opus-4-6": _CLAUDE_4, + "claude-sonnet-4-5": _CLAUDE_4, + "claude-haiku-4-5": _CLAUDE_4, + "claude-opus-4-5": _CLAUDE_4, } diff --git a/pyrit/prompt_target/common/tool_loop.py b/pyrit/prompt_target/common/tool_loop.py new file mode 100644 index 0000000000..dd58145d36 --- /dev/null +++ b/pyrit/prompt_target/common/tool_loop.py @@ -0,0 +1,294 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""The bounded local tool loop shared by targets that execute tools themselves.""" + +import json +import logging +from collections.abc import Awaitable, Callable, Mapping, Sequence +from dataclasses import dataclass +from typing import Any + +from pyrit.models import ( + Message, + MessagePiece, + ToolExecutionMetadata, + ToolLoopStop, + ToolLoopStopReason, + construct_response_from_request, +) +from pyrit.prompt_target.common.tool_provider import Tool, ToolInfrastructureError + +logger = logging.getLogger(__name__) + +MAX_ERROR_MESSAGE_CHARS = 2_000 + +ToolFunction = Callable[[dict[str, Any]], Awaitable[Any]] +ResolveToolsAsync = Callable[[], Awaitable[tuple[Sequence[Tool], Mapping[str, ToolFunction]]]] + + +@dataclass(frozen=True) +class ToolDispatchResult: + """A tool call's output and whether the tool was invoked.""" + + output: object + invoked: bool + + +@dataclass(frozen=True) +class PendingToolCall: + """A function call from a model response that the loop must answer.""" + + call_id: str + name: str | None + arguments: Any + section: dict[str, Any] + + +class InvalidToolCallsError(Exception): + """A response's tool calls cannot be run, so the turn ends without running any of them.""" + + +async def dispatch_tool_call_async( + *, call: PendingToolCall, resolve_tools_async: ResolveToolsAsync, fail_on_missing_function: bool = False +) -> ToolDispatchResult: + """ + Run one function call with the matching tool. + + Args: + call: The function call. + resolve_tools_async: Returns the registered tools and custom functions. Called only once the + call's arguments parse. + fail_on_missing_function: Raise instead of returning an error payload for a call that cannot run. + + Returns: + The output payload and whether the tool was invoked. A call that cannot run returns an error + payload with invoked=False, so the model can correct it. + + Raises: + ValueError: If the call has no name or malformed arguments and ``fail_on_missing_function`` is set. + KeyError: If the function is not registered and ``fail_on_missing_function`` is set. + """ + name = call.name + if not name: + if fail_on_missing_function: + raise ValueError("Function call section missing 'name' field") + return ToolDispatchResult( + output={"error": "missing_function_name", "tool_call_section": call.section}, invoked=False + ) + + args_json = call.arguments + try: + args = json.loads(args_json) + except Exception: + if fail_on_missing_function: + raise ValueError(f"Malformed arguments for function '{name}': {args_json}") from None + logger.warning("Malformed arguments for function '%s': %s", name, args_json) + return ToolDispatchResult( + output={"error": "malformed_arguments", "function": name, "raw_arguments": args_json}, invoked=False + ) + tools, custom_functions = await resolve_tools_async() + configured_tool = next((tool for tool in tools if tool.name == name), None) + custom_function = custom_functions.get(name) + if (configured_tool is not None or custom_function is not None) and not isinstance(args, dict): + if fail_on_missing_function: + raise ValueError(f"Arguments for function '{name}' must be a JSON object") + return ToolDispatchResult( + output={"error": "malformed_arguments", "function": name, "raw_arguments": args_json}, invoked=False + ) + + if configured_tool is not None: + try: + configured_tool.validate_arguments(arguments=args) + except ValueError as exc: + if fail_on_missing_function: + raise + logger.warning("Invalid arguments for function '%s': %s", name, exc) + return ToolDispatchResult( + output={ + "error": "malformed_arguments", + "function": name, + "raw_arguments": args_json, + "message": str(exc)[:MAX_ERROR_MESSAGE_CHARS], + }, + invoked=False, + ) + return ToolDispatchResult(output=await configured_tool.execute_async(arguments=args), invoked=True) + + if custom_function is not None: + return ToolDispatchResult(output=await custom_function(args), invoked=True) + + if fail_on_missing_function: + raise KeyError(f"Function '{name}' is not registered") + available_functions = sorted({*(tool.name for tool in tools), *custom_functions}) + logger.warning("Function '%s' not registered. Available: %s", name, available_functions) + return ToolDispatchResult( + output={"error": "function_not_found", "missing_function": name, "available_functions": available_functions}, + invoked=False, + ) + + +def make_tool_result_piece(*, result: ToolDispatchResult, call_id: str, reference_piece: MessagePiece) -> MessagePiece: + """ + Create the function_call_output piece that answers a call. + + Args: + result: The dispatch result to record. + call_id: The call it answers. + reference_piece: A piece to copy conversation context from. + + Returns: + A tool piece recording the output and whether the tool was invoked. + """ + output = result.output + output_str = output if isinstance(output, str) else json.dumps(output, separators=(",", ":")) + return MessagePiece( + role="tool", + original_value=json.dumps( + {"type": "function_call_output", "call_id": call_id, "output": output_str}, separators=(",", ":") + ), + original_value_data_type="function_call_output", + conversation_id=reference_piece.conversation_id, + prompt_metadata=ToolExecutionMetadata(invoked=result.invoked).to_metadata(), + ) + + +def tool_loop_error(*, request_piece: MessagePiece, detail: str, reason: ToolLoopStopReason) -> Message: + """ + Build the error response that ends a turn whose tools could not continue. + + Args: + request_piece: The request the turn answers. + detail: Why the turn ended. + reason: The machine-readable reason, recorded in the response's metadata. + + Returns: + An error response, which history replay skips. + """ + logger.error(detail) + return construct_response_from_request( + request=request_piece, + response_text_pieces=[detail], + response_type="error", + prompt_metadata=ToolLoopStop(reason=reason).to_metadata(), + error="processing", + ) + + +async def run_tool_loop_async( + *, + conversation: Sequence[Message], + request_piece: MessagePiece, + send_async: Callable[[Sequence[Message]], Awaitable[Message]], + find_calls: Callable[[Message], list[PendingToolCall]], + dispatch_async: Callable[[PendingToolCall], Awaitable[ToolDispatchResult]], + max_tool_rounds: int, +) -> list[Message]: + """ + Send a conversation and run the model's tool calls until it answers or the loop stops. + + Send failures and tool exceptions other than ``ToolInfrastructureError`` propagate. Every early stop + answers the pending calls and ends with an error response carrying a ``ToolLoopStop`` reason. + + Args: + conversation: The conversation to send, ending with the request. + request_piece: The request the turn answers. + send_async: Sends the working conversation and returns the model's response. + find_calls: Returns a response's function calls in order, or raises ``InvalidToolCallsError``. + dispatch_async: Runs one call. + max_tool_rounds: How many rounds of calls may run before the loop stops. + + Returns: + Every response and tool result for the normalizer to persist, in order. + """ + working = list(conversation) + responses: list[Message] = [] + rounds = 0 + while True: + logger.info("Sending conversation with %d messages to the prompt target", len(working)) + result = await send_async(working) + working.append(result) + responses.append(result) + + try: + calls = find_calls(result) + except InvalidToolCallsError as error: + for piece in result.message_pieces: + piece.response_error = "processing" + stop = ToolLoopStopReason.INVALID_TOOL_CALLS + responses.append(tool_loop_error(request_piece=request_piece, detail=str(error), reason=stop)) + return responses + if not calls: + return responses + + if rounds >= max_tool_rounds: + responses.extend( + _answer_without_running( + calls=calls, output={"error": "max_tool_rounds_exhausted"}, reference_piece=request_piece + ) + ) + detail = f"max_tool_rounds={max_tool_rounds} exhausted." + stop = ToolLoopStopReason.MAX_TOOL_ROUNDS_EXHAUSTED + responses.append(tool_loop_error(request_piece=request_piece, detail=detail, reason=stop)) + return responses + rounds += 1 + + tool_messages, failure = await _execute_round_async( + calls=calls, dispatch_async=dispatch_async, reference_piece=request_piece + ) + working.extend(tool_messages) + responses.extend(tool_messages) + if failure is not None: + stop = ToolLoopStopReason.TOOL_INFRASTRUCTURE_ERROR + responses.append(tool_loop_error(request_piece=request_piece, detail=failure, reason=stop)) + return responses + + +async def _execute_round_async( + *, + calls: Sequence[PendingToolCall], + dispatch_async: Callable[[PendingToolCall], Awaitable[ToolDispatchResult]], + reference_piece: MessagePiece, +) -> tuple[list[Message], str | None]: + """ + Run one response's calls in order, stopping at a tool infrastructure failure. + + Returns: + One result message per call, and why the turn must end, or None to continue. After a + failure, the calls not yet run get error results, so every call is answered. + """ + messages: list[Message] = [] + for index, call in enumerate(calls): + try: + result = await dispatch_async(call) + except ToolInfrastructureError as error: + logger.error("Tool %r could not run; ending the turn: %s", call.name, error) + # The model sees this result again on later turns, so it gets no infrastructure details; + # they stay in the error response, which history replay skips. + failed = ToolDispatchResult( + output={"error": "tool_infrastructure_error", "message": "The tool's infrastructure failed."}, + invoked=error.invoked, + ) + messages.append(_tool_message(result=failed, call=call, reference_piece=reference_piece)) + messages.extend( + _answer_without_running( + calls=calls[index + 1 :], + output={"error": "tool_not_executed", "message": "An earlier tool call failed."}, + reference_piece=reference_piece, + ) + ) + return messages, f"Tool {call.name!r} could not run: {error}" + messages.append(_tool_message(result=result, call=call, reference_piece=reference_piece)) + return messages, None + + +def _answer_without_running( + *, calls: Sequence[PendingToolCall], output: dict[str, str], reference_piece: MessagePiece +) -> list[Message]: + result = ToolDispatchResult(output=output, invoked=False) + return [_tool_message(result=result, call=call, reference_piece=reference_piece) for call in calls] + + +def _tool_message(*, result: ToolDispatchResult, call: PendingToolCall, reference_piece: MessagePiece) -> Message: + piece = make_tool_result_piece(result=result, call_id=call.call_id, reference_piece=reference_piece) + return Message(message_pieces=[piece]) diff --git a/pyrit/prompt_target/litellm_chat_target.py b/pyrit/prompt_target/litellm_chat_target.py index cc74acc6ee..84a9455ff0 100644 --- a/pyrit/prompt_target/litellm_chat_target.py +++ b/pyrit/prompt_target/litellm_chat_target.py @@ -2,9 +2,11 @@ # Licensed under the MIT license. import itertools +import json import logging import os from collections.abc import Awaitable, Callable, Mapping, MutableSequence, Sequence +from contextlib import AsyncExitStack from types import MappingProxyType from typing import Any, ClassVar, NoReturn, cast @@ -23,6 +25,7 @@ MessagePiece, PromptDataType, ) +from pyrit.models.messages.chat_message import FunctionCall from pyrit.prompt_target.common.chat_completions_message_builder import ( build_multimodal_chat_messages_async, build_response_format, @@ -47,7 +50,20 @@ ) from pyrit.prompt_target.common.target_configuration import TargetConfiguration from pyrit.prompt_target.common.target_trace_config import TargetTraceConfig, request_trace_headers -from pyrit.prompt_target.common.tool_call_history import TOOL_CALL_INPUT_MODALITIES +from pyrit.prompt_target.common.tool_call_history import TOOL_CALL_INPUT_MODALITIES, parse_function_call +from pyrit.prompt_target.common.tool_loop import ( + InvalidToolCallsError, + PendingToolCall, + ToolFunction, + dispatch_tool_call_async, + run_tool_loop_async, +) +from pyrit.prompt_target.common.tool_provider import ( + Tool, + ToolProvider, + _ScopedToolProvider, + collect_tools_async, +) from pyrit.prompt_target.common.utils import ( build_empty_truncated_response, limit_requests_per_minute, @@ -202,10 +218,32 @@ class LiteLLMChatTarget(PromptTarget): provider or gateway is not known to accept W3C trace context. Pass ``TargetTraceConfig(enabled=True)`` for an instrumented endpoint; each request then sends a fresh ``traceparent`` in ``extra_headers``. + tools: Executable tools advertised to the model. + tool_providers: Providers discovered within each send's resource scope. + execute_tools: Execute configured tools locally, or return calls to the caller. + max_tool_rounds: Maximum completions containing locally dispatched calls per send. + Calls beyond the limit receive error results without execution. """ server_fallback_parameters: ClassVar[Mapping[str, str | None]] = MappingProxyType({"api_key": None}) + # Environment variables read when ``api_key`` or ``endpoint`` is omitted. Subclasses that pin a + # provider override these; None skips the lookup and leaves it to LiteLLM. + _API_KEY_ENVIRONMENT_VARIABLE: ClassVar[str | None] = "LITELLM_API_KEY" + _ENDPOINT_ENVIRONMENT_VARIABLE: ClassVar[str | None] = "LITELLM_ENDPOINT" + # Header names, compared case-insensitively, that identifiers never record. + _CREDENTIAL_HEADERS: ClassVar[frozenset[str]] = frozenset( + { + "authorization", + "proxy-authorization", + "x-api-key", + "api-key", + "ocp-apim-subscription-key", + "cookie", + "set-cookie", + } + ) + # Fallback only. The real per-instance configuration is normally derived from LiteLLM's # model metadata at construction time (see ``_derive_capabilities_from_litellm``). _SUPPORTS_TOOL_CALL_HISTORY = True @@ -242,6 +280,10 @@ def __init__( max_requests_per_minute: int | None = None, custom_configuration: TargetConfiguration | None = None, trace_config: TargetTraceConfig | None = None, + tools: Sequence[Tool] | None = None, + tool_providers: Sequence[ToolProvider] | None = None, + execute_tools: bool = True, + max_tool_rounds: int = 10, ) -> None: """ Initialize a LiteLLMChatTarget. @@ -258,6 +300,15 @@ def __init__( validate_top_p(top_p) validate_presence_penalty(presence_penalty) validate_frequency_penalty(frequency_penalty) + if isinstance(max_tool_rounds, bool) or not isinstance(max_tool_rounds, int) or max_tool_rounds < 0: + raise ValueError("max_tool_rounds must be a nonnegative integer.") + self._direct_tools = list(tools or []) + self._tool_providers = list(tool_providers or []) + self._execute_tools = execute_tools + self._max_tool_rounds = max_tool_rounds + self._suppress_tools = False + if execute_tools and (tools or tool_providers) and (extra_body_parameters or {}).get("n", n) not in (None, 1): + raise ValueError("Automatic tool execution requires n=1.") super().__init__( model_name=resolved_model, @@ -267,14 +318,15 @@ def __init__( trace_config=trace_config, ) - # Resolve api_key: explicit value/callable > LITELLM_API_KEY env var > None (LiteLLM + # Resolve api_key: explicit value/callable > _API_KEY_ENVIRONMENT_VARIABLE > None (LiteLLM # then reads provider-specific env vars itself). ``ensure_async_token_provider`` wraps a # sync token provider so we can uniformly await it at request time. - if api_key is None: - api_key = os.environ.get("LITELLM_API_KEY") + if api_key is None and self._API_KEY_ENVIRONMENT_VARIABLE: + api_key = os.environ.get(self._API_KEY_ENVIRONMENT_VARIABLE) self._api_key = ensure_async_token_provider(api_key) - self._endpoint = endpoint or os.environ.get("LITELLM_ENDPOINT") + endpoint_variable = self._ENDPOINT_ENVIRONMENT_VARIABLE + self._endpoint = endpoint or (os.environ.get(endpoint_variable) if endpoint_variable else None) self._headers = headers self._temperature = temperature self._top_p = top_p @@ -404,9 +456,24 @@ def _build_identifier(self) -> ComponentIdentifier: "n": self._n, "stop": self._stop, "extra_body_parameters": self._extra_body_parameters, + "tools": [self._tool_definition(tool) for tool in self._direct_tools] or None, + "tool_providers": [provider.identifier for provider in self._tool_providers] or None, + "execute_tools": None if self._execute_tools else False, + "max_tool_rounds": self._max_tool_rounds if self._direct_tools or self._tool_providers else None, }, ) + def _identifier_headers(self) -> dict[str, str] | None: + """ + Return the configured headers without credentials, for identifiers that record headers. + + Returns: + dict[str, str] | None: The non-credential headers, or None when there are none. + """ + return { + name: value for name, value in (self._headers or {}).items() if name.lower() not in self._CREDENTIAL_HEADERS + } or None + def is_json_response_supported(self) -> bool: """ Whether this target honors a JSON ``response_format`` request. @@ -418,19 +485,127 @@ def is_json_response_supported(self) -> bool: # Not decorated with ``pyrit_target_retry``: LiteLLM owns transient/rate-limit retry via # ``num_retries`` (see ``__init__``). Stacking both would multiply the retry count. - @limit_requests_per_minute async def _send_prompt_to_target_async(self, *, normalized_conversation: list[Message]) -> list[Message]: + async with AsyncExitStack() as stack: + for provider in () if self._suppress_tools else self._tool_providers: + if isinstance(provider, _ScopedToolProvider): + await stack.enter_async_context(provider.execution_scope_async()) + tools = ( + [] + if self._suppress_tools + else await collect_tools_async(tools=self._direct_tools, providers=self._tool_providers) + ) + self._validate_tool_definitions(tools) + request = normalized_conversation[-1] + if not tools or not self._execute_tools: + return await self._send_completion_async( + conversation=normalized_conversation, request=request, tools=tools + ) + + async def send_async(conversation: Sequence[Message]) -> Message: + [reply] = await self._send_completion_async( + conversation=list(conversation), request=request, tools=tools + ) + return reply + + async def resolve_tools_async() -> tuple[Sequence[Tool], Mapping[str, ToolFunction]]: + return tools, {} + + return await run_tool_loop_async( + conversation=normalized_conversation, + request_piece=request.message_pieces[0], + send_async=send_async, + find_calls=self._tool_call_finder(normalized_conversation), + dispatch_async=lambda call: dispatch_tool_call_async( + call=call, resolve_tools_async=resolve_tools_async + ), + max_tool_rounds=self._max_tool_rounds, + ) + + @staticmethod + def _tool_definition(tool: Tool) -> dict[str, Any]: + return { + "type": "function", + "function": { + "name": tool.name, + "description": tool.description, + "parameters": tool.parameters, + "strict": tool.strict, + }, + } + + def _validate_tool_definitions(self, tools: Sequence[Tool]) -> None: + declared = { + definition.get("function", {}).get("name") + for definition in (self._extra_body_parameters or {}).get("tools") or [] + } + conflicts = {tool.name for tool in tools} & declared + if conflicts: + raise ValueError(f"Tools conflict with extra_body_parameters declarations: {sorted(conflicts)}") + + @staticmethod + def _tool_call_finder(conversation: Sequence[Message]) -> Callable[[Message], list[PendingToolCall]]: + """ + Build the shared tool loop's call reader, rejecting calls whose IDs would corrupt history. + + Args: + conversation: The conversation being sent, whose call IDs cannot be reused. + + Returns: + A function returning a response's calls in order, or raising ``InvalidToolCallsError``. + """ + seen_ids = { + parse_function_call(piece).id + for message in conversation + for piece in message.message_pieces + if piece.converted_value_data_type == "function_call" + } + + def find_calls(reply: Message) -> list[PendingToolCall]: + call_pieces = [ + piece for piece in reply.message_pieces if piece.converted_value_data_type == "function_call" + ] + if not call_pieces: + return [] + if any(piece.is_truncated or piece.response_error != "none" for piece in reply.message_pieces): + raise InvalidToolCallsError("Truncated or failed tool calls were not executed.") + try: + calls = [parse_function_call(piece) for piece in call_pieces] + except ValueError as exc: + raise InvalidToolCallsError(f"Invalid tool calls: {exc}") from exc + ids = [call.id for call in calls] + if len(set(ids)) != len(ids) or seen_ids.intersection(ids): + raise InvalidToolCallsError("Invalid tool calls: Duplicate or reused tool call ID.") + seen_ids.update(ids) + return [ + PendingToolCall( + call_id=call.id, + name=call.function.name if isinstance(call.function, FunctionCall) else None, + arguments=call.function.arguments if isinstance(call.function, FunctionCall) else call.function, + section=json.loads(piece.converted_value), + ) + for call, piece in zip(calls, call_pieces, strict=True) + ] + + return find_calls + + @limit_requests_per_minute + async def _send_completion_async( + self, *, conversation: list[Message], request: Message, tools: Sequence[Tool] + ) -> list[Message]: litellm = self._import_litellm() - message = normalized_conversation[-1] + message = request request_piece: MessagePiece = message.message_pieces[0] logger.info(f"Sending prompt to LiteLLM target ({self._model_name}): {message}") json_config = self._get_json_response_config(message_piece=request_piece) - messages = await self._build_chat_messages_async(normalized_conversation) + messages = await self._build_chat_messages_async(conversation) api_key = await self._resolve_api_key_async() body = self._construct_request_body(messages=messages, json_config=json_config, api_key=api_key) + if tools: + body["tools"] = [*body.get("tools", []), *(self._tool_definition(tool) for tool in tools)] # Applied after the passthrough merge so ``extra_body_parameters`` cannot drop the context. # LiteLLM merges ``headers`` with ``extra_headers`` and then the provider-specific headers, # so all three are checked for manual values. diff --git a/pyrit/prompt_target/litellm_decision_target.py b/pyrit/prompt_target/litellm_decision_target.py index b53d654a3a..3f3d926cc7 100644 --- a/pyrit/prompt_target/litellm_decision_target.py +++ b/pyrit/prompt_target/litellm_decision_target.py @@ -43,17 +43,6 @@ class LiteLLMDecisionTarget(LiteLLMChatTarget): _SUPPORTS_TOOL_CALL_HISTORY = False _DEFAULT_CONFIGURATION = TargetConfiguration(capabilities=TargetCapabilities()) - _CREDENTIAL_HEADERS = frozenset( - { - "authorization", - "proxy-authorization", - "x-api-key", - "api-key", - "ocp-apim-subscription-key", - "cookie", - "set-cookie", - } - ) def __init__( self, @@ -102,10 +91,7 @@ def _build_identifier(self) -> ComponentIdentifier: Returns: ComponentIdentifier: The target identity. """ - headers = { - key: value for key, value in (self._headers or {}).items() if key.lower() not in self._CREDENTIAL_HEADERS - } - return self._create_identifier(params={"endpoint": self._endpoint, "headers": headers or None}) + return self._create_identifier(params={"endpoint": self._endpoint, "headers": self._identifier_headers()}) @pyrit_target_retry @limit_requests_per_minute diff --git a/pyrit/prompt_target/openai/openai_response_target.py b/pyrit/prompt_target/openai/openai_response_target.py index 2dd2353d8a..5a734c38d9 100644 --- a/pyrit/prompt_target/openai/openai_response_target.py +++ b/pyrit/prompt_target/openai/openai_response_target.py @@ -36,20 +36,22 @@ MessagePiece, PromptDataType, PromptResponseError, - ToolExecutionMetadata, - ToolLoopStop, - ToolLoopStopReason, WebSearchConfig, WebSearchMode, - construct_response_from_request, ) from pyrit.models.messages.chat_message import FunctionCall from pyrit.prompt_target.common.target_capabilities import CapabilityName, TargetCapabilities from pyrit.prompt_target.common.target_configuration import TargetConfiguration from pyrit.prompt_target.common.tool_call_history import parse_function_call, parse_function_call_output +from pyrit.prompt_target.common.tool_loop import ( + PendingToolCall, + ToolDispatchResult, + dispatch_tool_call_async, + make_tool_result_piece, + run_tool_loop_async, +) from pyrit.prompt_target.common.tool_provider import ( Tool, - ToolInfrastructureError, ToolProvider, _ScopedToolProvider, collect_tools_async, @@ -80,12 +82,6 @@ class _SerializedPiece: placement: Literal["inline", "top_level"] -@dataclass(frozen=True) -class _ToolDispatchResult: - output: object - invoked: bool - - class MessagePieceType(str, Enum): """Enumeration of different types of message pieces.""" @@ -129,7 +125,6 @@ class OpenAIResponseTarget(OpenAITarget): _SUPPORTS_TOOL_CALL_HISTORY = True _SUPPORTED_GENERATION_CAPABILITIES: ClassVar[frozenset[CapabilityName]] = frozenset({CapabilityName.TEMPERATURE}) - _MAX_ERROR_MESSAGE_CHARS = 2_000 _WEB_SEARCH_TOOL_TYPES = frozenset({"web_search", "web_search_preview"}) _DEFAULT_CONFIGURATION: TargetConfiguration = TargetConfiguration( capabilities=TargetCapabilities( @@ -803,165 +798,39 @@ def _validate_web_search_response(*, config: WebSearchConfig, responses: Sequenc async def _run_tool_call_loop_async(self, *, normalized_conversation: list[Message]) -> list[Message]: message = normalized_conversation[-1] - message_piece: MessagePiece = message.message_pieces[0] last_piece = message.message_pieces[-1] json_config = self._get_json_response_config(message_piece=last_piece) web_search_config = self._get_web_search_config(message) - working_conversation: MutableSequence[Message] = list(normalized_conversation) - - # Track all responses generated during this interaction - responses_to_return: list[Message] = [] - rounds = 0 - - while True: - logger.info(f"Sending conversation with {len(working_conversation)} messages to the prompt target") - + async def send_async(conversation: Sequence[Message]) -> Message: body = await self._construct_request_body_async( - conversation=working_conversation, json_config=json_config, web_search_config=web_search_config - ) - - result = await self._send_model_request_async(body=body, request=message) - if not self._execute_tools: - return [result] - - # Add result to conversation and responses list - working_conversation.append(result) - responses_to_return.append(result) - - tool_call_sections = self._find_pending_tool_calls(result) - - if not tool_call_sections: - break - - if rounds >= self._max_tool_rounds: - responses_to_return.extend( - self._answer_calls_without_running( - sections=tool_call_sections, - output={"error": "max_tool_rounds_exhausted"}, - reference_piece=message_piece, - ) - ) - detail = f"max_tool_rounds={self._max_tool_rounds} exhausted." - stop = ToolLoopStopReason.MAX_TOOL_ROUNDS_EXHAUSTED - responses_to_return.append( - self._tool_loop_error(request_piece=message_piece, detail=detail, reason=stop) - ) - return responses_to_return - rounds += 1 - - tool_messages, failure = await self._execute_tool_round_async( - sections=tool_call_sections, reference_piece=message_piece + conversation=list(conversation), json_config=json_config, web_search_config=web_search_config ) - working_conversation.extend(tool_messages) - responses_to_return.extend(tool_messages) - if failure is not None: - stop = ToolLoopStopReason.TOOL_INFRASTRUCTURE_ERROR - responses_to_return.append( - self._tool_loop_error(request_piece=message_piece, detail=failure, reason=stop) + response: Message = await self._send_model_request_async(body=body, request=message) + return response + + if not self._execute_tools: + return [await send_async(normalized_conversation)] + + def find_calls(reply: Message) -> list[PendingToolCall]: + return [ + PendingToolCall( + call_id=section["call_id"], + name=section.get("name"), + arguments=section.get("arguments", "{}"), + section=section, ) - return responses_to_return - - # Return all responses (normalizer will persist all of them to memory) - return responses_to_return - - async def _execute_tool_round_async( - self, *, sections: list[dict[str, Any]], reference_piece: MessagePiece - ) -> tuple[list[Message], str | None]: - """ - Run one response's tool calls in order, stopping at a tool infrastructure failure. - - Args: - sections: The response's function calls. - reference_piece: A piece to copy conversation context from. - - Returns: - One result message per call, and why the turn must end, or None to continue. After a - failure, the calls not yet run get error results, so every call is answered. - """ - messages: list[Message] = [] - for index, section in enumerate(sections): - try: - result = await self._execute_call_section_async(section) - except ToolInfrastructureError as error: - logger.error("Tool %r could not run; ending the turn: %s", section.get("name"), error) - # The model sees this result again on later turns, so it gets no infrastructure details; - # they stay in the error response, which history replay skips. - failed = _ToolDispatchResult( - output={"error": "tool_infrastructure_error", "message": "The tool's infrastructure failed."}, - invoked=error.invoked, - ) - messages.append( - self._make_tool_message(result=failed, section=section, reference_piece=reference_piece) - ) - messages.extend( - self._answer_calls_without_running( - sections=sections[index + 1 :], - output={"error": "tool_not_executed", "message": "An earlier tool call failed."}, - reference_piece=reference_piece, - ) - ) - return messages, f"Tool {section.get('name')!r} could not run: {error}" - messages.append(self._make_tool_message(result=result, section=section, reference_piece=reference_piece)) - return messages, None - - def _answer_calls_without_running( - self, *, sections: Sequence[dict[str, Any]], output: dict[str, str], reference_piece: MessagePiece - ) -> list[Message]: - """ - Give calls that will not run an error result, so the history keeps every call answered. - - Args: - sections: The calls. - output: The error result each call gets. - reference_piece: A piece to copy conversation context from. - - Returns: - One result message per call, recorded as not invoked. - """ - result = _ToolDispatchResult(output=output, invoked=False) - return [ - self._make_tool_message(result=result, section=section, reference_piece=reference_piece) - for section in sections - ] - - def _make_tool_message( - self, *, result: _ToolDispatchResult, section: dict[str, Any], reference_piece: MessagePiece - ) -> Message: - """ - Wrap a call's result in a message. - - Args: - result: The dispatch result to record. - section: The function call it answers. - reference_piece: A piece to copy conversation context from. - - Returns: - A message with one function_call_output piece. - """ - piece = self._make_tool_piece(result=result, call_id=section["call_id"], reference_piece=reference_piece) - return Message(message_pieces=[piece]) - - @staticmethod - def _tool_loop_error(*, request_piece: MessagePiece, detail: str, reason: ToolLoopStopReason) -> Message: - """ - Build the error response that ends a turn whose tools could not continue. - - Args: - request_piece: The request the turn answers. - detail: Why the turn ended. - reason: The machine-readable reason, recorded in the response's metadata. - - Returns: - An error response, which history replay skips. - """ - logger.error(detail) - return construct_response_from_request( - request=request_piece, - response_text_pieces=[detail], - response_type="error", - prompt_metadata=ToolLoopStop(reason=reason).to_metadata(), - error="processing", + for section in self._find_pending_tool_calls(reply) + ] + + # The normalizer persists every response and tool result returned here. + return await run_tool_loop_async( + conversation=normalized_conversation, + request_piece=message.message_pieces[0], + send_async=send_async, + find_calls=find_calls, + dispatch_async=lambda call: self._execute_call_section_async(call.section), + max_tool_rounds=self._max_tool_rounds, ) @pyrit_target_retry @@ -1181,7 +1050,7 @@ def _find_pending_tool_calls(self, reply: Message) -> list[dict[str, Any]]: calls.append(cast("dict[str, Any]", section)) return calls - async def _execute_call_section_async(self, tool_call_section: dict[str, Any]) -> _ToolDispatchResult: + async def _execute_call_section_async(self, tool_call_section: dict[str, Any]) -> ToolDispatchResult: """ Execute a function call using the matching tool. @@ -1191,80 +1060,26 @@ async def _execute_call_section_async(self, tool_call_section: dict[str, Any]) - Returns: The output payload and whether the tool was invoked. Tolerant dispatch failures retain their error payload with invoked=False. - - Raises: - ValueError: If the function call section is missing a 'name' field. - ValueError: If the function arguments are malformed. - KeyError: If the function name is not registered. """ - name = tool_call_section.get("name") - if not name: - if self._fail_on_missing_function: - raise ValueError("Function call section missing 'name' field") - return _ToolDispatchResult( - output={"error": "missing_function_name", "tool_call_section": tool_call_section}, - invoked=False, - ) - args_json = tool_call_section.get("arguments", "{}") - try: - args = json.loads(args_json) - except Exception: - # If arguments are not valid JSON, surface a structured error (or raise) - if self._fail_on_missing_function: - raise ValueError(f"Malformed arguments for function '{name}': {args_json}") from None - logger.warning("Malformed arguments for function '%s': %s", name, args_json) - return _ToolDispatchResult( - output={"error": "malformed_arguments", "function": name, "raw_arguments": args_json}, - invoked=False, - ) - await self._initialize_tools_async() - configured_tool = next((tool for tool in self._tools if tool.name == name), None) - custom_function = self._custom_functions.get(name) - if (configured_tool is not None or custom_function is not None) and not isinstance(args, dict): - if self._fail_on_missing_function: - raise ValueError(f"Arguments for function '{name}' must be a JSON object") - return _ToolDispatchResult( - output={"error": "malformed_arguments", "function": name, "raw_arguments": args_json}, - invoked=False, - ) + async def resolve_tools_async() -> tuple[Sequence[Tool], dict[str, ToolExecutor]]: + await self._initialize_tools_async() + return self._tools, self._custom_functions - if configured_tool is not None: - try: - configured_tool.validate_arguments(arguments=args) - except ValueError as exc: - if self._fail_on_missing_function: - raise - logger.warning("Invalid arguments for function '%s': %s", name, exc) - return _ToolDispatchResult( - output={ - "error": "malformed_arguments", - "function": name, - "raw_arguments": args_json, - "message": str(exc)[: self._MAX_ERROR_MESSAGE_CHARS], - }, - invoked=False, - ) - return _ToolDispatchResult(output=await configured_tool.execute_async(arguments=args), invoked=True) - - if custom_function is not None: - return _ToolDispatchResult(output=await custom_function(args), invoked=True) - - if self._fail_on_missing_function: - raise KeyError(f"Function '{name}' is not registered") - available_functions = sorted({*(tool.name for tool in self._tools), *self._custom_functions}) - logger.warning("Function '%s' not registered. Available: %s", name, available_functions) - return _ToolDispatchResult( - output={ - "error": "function_not_found", - "missing_function": name, - "available_functions": available_functions, - }, - invoked=False, + call = PendingToolCall( + call_id=str(tool_call_section.get("call_id", "")), + name=tool_call_section.get("name"), + arguments=tool_call_section.get("arguments", "{}"), + section=tool_call_section, + ) + return await dispatch_tool_call_async( + call=call, + resolve_tools_async=resolve_tools_async, + fail_on_missing_function=self._fail_on_missing_function, ) def _make_tool_piece( - self, *, result: _ToolDispatchResult, call_id: str, reference_piece: MessagePiece + self, *, result: ToolDispatchResult, call_id: str, reference_piece: MessagePiece ) -> MessagePiece: """ Create a function_call_output MessagePiece. @@ -1277,15 +1092,4 @@ def _make_tool_piece( Returns: A MessagePiece containing the function call output. """ - output = result.output - output_str = output if isinstance(output, str) else json.dumps(output, separators=(",", ":")) - return MessagePiece( - role="tool", - original_value=json.dumps( - {"type": "function_call_output", "call_id": call_id, "output": output_str}, - separators=(",", ":"), - ), - original_value_data_type="function_call_output", - conversation_id=reference_piece.conversation_id, - prompt_metadata=ToolExecutionMetadata(invoked=result.invoked).to_metadata(), - ) + return make_tool_result_piece(result=result, call_id=call_id, reference_piece=reference_piece) diff --git a/tests/integration/targets/test_claude_chat_target_integration.py b/tests/integration/targets/test_claude_chat_target_integration.py new file mode 100644 index 0000000000..49124ae9b3 --- /dev/null +++ b/tests/integration/targets/test_claude_chat_target_integration.py @@ -0,0 +1,84 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import json +import os +import uuid + +import pytest + +from pyrit.memory import SQLiteMemory +from pyrit.models import JsonResponseConfig, MessagePiece +from pyrit.prompt_normalizer import PromptNormalizer +from pyrit.prompt_target import ClaudeChatTarget, tool + + +@pytest.mark.run_only_if_all_tests +@pytest.mark.parametrize("json_output", [False, True]) +async def test_claude_tool_continuation_and_replay_async(*, sqlite_instance: SQLiteMemory, json_output: bool) -> None: + if os.environ.get("RUN_ANTHROPIC_TESTS", "").lower() != "true": + pytest.skip("Set RUN_ANTHROPIC_TESTS=true to authorize billable Anthropic calls.") + if not os.environ.get("ANTHROPIC_API_KEY"): + pytest.skip("ANTHROPIC_API_KEY is required for Anthropic integration tests.") + pytest.importorskip("litellm") + executions: list[int] = [] + + @tool + async def add_one_async(*, value: int) -> int: + """Add one to a number.""" + executions.append(value) + return value + 1 + + target = ClaudeChatTarget( + model_name=os.environ.get("ANTHROPIC_MODEL", "claude-sonnet-4-6"), + tools=[add_one_async], + max_tokens=512, + max_tool_rounds=2, + ) + normalizer = PromptNormalizer() + conversation_id = str(uuid.uuid4()) + request = MessagePiece( + role="user", + original_value="Call add_one_async with value=7 exactly once. Return the result" + + (" as a JSON object with key 'answer'." if json_output else " in one short sentence."), + prompt_metadata=JsonResponseConfig(enabled=json_output).to_metadata(), + ) + reply = await normalizer.send_prompt_async( + target=target, message=request.to_message(), conversation_id=conversation_id + ) + assert reply.get_piece().response_error == "none" + assert executions == [7] + if json_output: + assert json.loads(reply.get_value())["answer"] == 8 + else: + assert "8" in reply.get_value() + history = await sqlite_instance.get_conversation_messages_async(conversation_id=conversation_id) + assert any(message.api_role == "tool" for message in history) + target.validate_tool_history(history) + second = await normalizer.send_prompt_async( + target=target, + message=MessagePiece(role="user", original_value="What was that result? Do not call tools again.").to_message(), + conversation_id=conversation_id, + ) + assert second.get_piece().response_error == "none" + assert "8" in second.get_value() + assert executions == [7] + + +@pytest.mark.run_only_if_all_tests +async def test_claude_json_without_executable_tools_async(sqlite_instance: SQLiteMemory) -> None: + if os.environ.get("RUN_ANTHROPIC_TESTS", "").lower() != "true": + pytest.skip("Set RUN_ANTHROPIC_TESTS=true to authorize billable Anthropic calls.") + if not os.environ.get("ANTHROPIC_API_KEY"): + pytest.skip("ANTHROPIC_API_KEY is required for Anthropic integration tests.") + pytest.importorskip("litellm") + target = ClaudeChatTarget(model_name=os.environ.get("ANTHROPIC_MODEL", "claude-sonnet-4-6"), max_tokens=256) + responses = await target.send_prompt_async( + message=MessagePiece( + role="user", + original_value="Return a JSON object with answer equal to 8.", + prompt_metadata=JsonResponseConfig(enabled=True).to_metadata(), + ).to_message() + ) + assert responses[-1].get_piece().response_error == "none" + assert json.loads(responses[-1].get_value())["answer"] == 8 diff --git a/tests/unit/infra/test_code_deployment.py b/tests/unit/infra/test_code_deployment.py index 7b4bda5dc2..9f93742e5d 100644 --- a/tests/unit/infra/test_code_deployment.py +++ b/tests/unit/infra/test_code_deployment.py @@ -201,6 +201,7 @@ def test_pypi_compatibility_validation_fails_closed_with_a_release_diagnostic(se for state in ("legacy", "missing-stamp", "malformed-stamp", "stamped"): with self.subTest(state=state), tempfile.TemporaryDirectory() as directory: root = Path(directory) + (root / "litellm.py").write_text("", encoding="utf-8") package = root / "pyrit" package.mkdir() (package / "__init__.py").write_text("from ._version import __version__\n", encoding="utf-8") diff --git a/tests/unit/infra/test_docker_ci.py b/tests/unit/infra/test_docker_ci.py index 4879643803..59d63fc784 100644 --- a/tests/unit/infra/test_docker_ci.py +++ b/tests/unit/infra/test_docker_ci.py @@ -25,6 +25,14 @@ } +def test_production_installs_litellm_and_checks_final_interpreter() -> None: + dockerfile = (REPO_ROOT / "docker" / "Dockerfile").read_text(encoding="utf-8") + installs = [line for line in dockerfile.splitlines() if "uv pip install" in line and "github-copilot" in line] + assert len(installs) == 2 + assert all(",litellm]" in line for line in installs) + assert 'cd /tmp && \\\n /opt/venv/bin/python -c "import litellm' in dockerfile + + @pytest.fixture(scope="module") def workflow() -> dict[str, Any]: # BaseLoader preserves the Actions "on" key instead of treating it as a YAML 1.1 boolean. @@ -59,6 +67,38 @@ def _run_bash(*, bash_path: str, script: str, environment: dict[str, str | None] ) +@pytest.mark.parametrize( + ("source", "has_claude", "expected_exit"), + [("local", "true", 0), ("local", "false", 1), ("pypi", "false", 0)], +) +def test_production_target_smoke_check_respects_installed_source( + *, bash_path: str, source: str, has_claude: str, expected_exit: int +) -> None: + dockerfile = (REPO_ROOT / "docker" / "Dockerfile").read_text(encoding="utf-8") + smoke = dockerfile.split(" cd /tmp && \\\n", 1)[1].split(" if ! ", 1)[0] + smoke = smoke.replace("\\\n", "\n").rstrip().removesuffix(" &&") + smoke = smoke.replace("/opt/venv/bin/python", "python_smoke") + script = ( + """ +python_smoke() { + printf '%s\\n' "$*" + if [[ "$*" == *"ClaudeChatTarget"* && "$HAS_CLAUDE" == "false" ]]; then + return 1 + fi +} +""" + + smoke + ) + result = _run_bash( + bash_path=bash_path, + script=script, + environment={"PYRIT_SOURCE": source, "HAS_CLAUDE": has_claude}, + ) + assert result.returncode == expected_exit, result.stderr + assert "import litellm" in result.stdout + assert ("ClaudeChatTarget" in result.stdout) == (source == "local") + + @pytest.mark.parametrize("gate_id", ["local-checks", *PYPI_GATES]) @pytest.mark.parametrize("job_result", ["success", "failure", "cancelled", "skipped", "", None]) @pytest.mark.parametrize("stage_result", ["success", "failure", "cancelled", "skipped", "", None]) diff --git a/tests/unit/prompt_target/target/test_claude_chat_target.py b/tests/unit/prompt_target/target/test_claude_chat_target.py new file mode 100644 index 0000000000..ee373489e2 --- /dev/null +++ b/tests/unit/prompt_target/target/test_claude_chat_target.py @@ -0,0 +1,381 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import json +import sys +from collections.abc import Generator +from typing import Any +from unittest.mock import AsyncMock, patch + +import httpx +import pytest +from unit.prompt_target.target.test_litellm_chat_target import _make_litellm_stub, _mock_response, _user_message + +from pyrit.models import JsonResponseConfig, Message, MessagePiece +from pyrit.prompt_target import ClaudeChatTarget, TargetCapabilities, TargetConfiguration, tool +from pyrit.registry import TargetRegistry + + +@pytest.fixture +def claude_sdk() -> Generator[Any, None, None]: + sdk, exceptions = _make_litellm_stub() + with patch.dict(sys.modules, {"litellm": sdk, "litellm.exceptions": exceptions}): + yield sdk + + +@pytest.mark.usefixtures("patch_central_database") +class TestClaudeChatTarget: + @pytest.mark.parametrize("model", ["claude-sonnet-4-6", "anthropic/claude-sonnet-4-6"]) + async def test_native_route_and_identity_async(self, *, claude_sdk: Any, model: str) -> None: + target = ClaudeChatTarget(model_name=model) + claude_sdk.acompletion.return_value = _mock_response() + await target.send_prompt_async(message=_user_message()) + assert claude_sdk.acompletion.call_args.kwargs["model"] == "anthropic/claude-sonnet-4-6" + assert target.get_identifier().params["model_name"] == "anthropic/claude-sonnet-4-6" + assert target.get_identifier().params["underlying_model_name"] == "claude-sonnet-4-6" + assert target.get_identifier() == ClaudeChatTarget(model_name="claude-sonnet-4-6").get_identifier() + + @pytest.mark.parametrize( + "model", + ["", "claude-", "claude- a", "gpt-4o", "openai/claude-sonnet-4-6", "bedrock/claude", "claude-a/b", "claude-a "], + ) + def test_invalid_route(self, model: str) -> None: + with pytest.raises(ValueError, match="Claude name"): + ClaudeChatTarget(model_name=model) + + @pytest.mark.parametrize( + "extra", [{"model": "openai/gpt-4o"}, {"custom_llm_provider": "openai"}, {"api_key": "secret"}] + ) + def test_conflicting_passthrough(self, extra: dict[str, str]) -> None: + with pytest.raises(ValueError): + ClaudeChatTarget(model_name="claude-sonnet-4-6", extra_body_parameters=extra) + + def test_capabilities_work_without_metadata(self, claude_sdk: Any) -> None: + claude_sdk.supports_vision.return_value = False + target = ClaudeChatTarget(model_name="claude-sonnet-4-6") + assert target.capabilities.supports_multi_turn + assert target.capabilities.supports_system_prompt + assert target.capabilities.supports_editable_history + assert {"text", "image_path", "function_call", "function_call_output"} <= set( + target.capabilities.supported_input_modalities + ) + assert target.capabilities.supports_json_output + assert not target.capabilities.supports_json_schema + + def test_unknown_model_and_custom_configuration(self, claude_sdk: Any) -> None: + claude_sdk.supports_vision.return_value = False + claude_sdk.supports_function_calling.return_value = False + claude_sdk.get_supported_openai_params.return_value = [] + unknown = ClaudeChatTarget(model_name="claude-future") + assert set(unknown.capabilities.supported_input_modalities) == {"text"} + assert not unknown.capabilities.supports_json_output + configuration = TargetConfiguration(capabilities=TargetCapabilities()) + target = ClaudeChatTarget(model_name="claude-sonnet-4-6", custom_configuration=configuration) + assert target.configuration is configuration + + async def test_credentials_and_endpoint_ignore_generic_environment_async(self, claude_sdk: Any) -> None: + with patch.dict( + "os.environ", + { + "ANTHROPIC_API_KEY": "anthropic-test", + "LITELLM_API_KEY": "wrong-key", + "LITELLM_ENDPOINT": "https://wrong.invalid", + }, + ): + target = ClaudeChatTarget(model_name="claude-sonnet-4-6") + claude_sdk.acompletion.return_value = _mock_response() + await target.send_prompt_async(message=_user_message()) + body = claude_sdk.acompletion.call_args.kwargs + assert body["api_key"] == "anthropic-test" + assert "api_base" not in body + + @pytest.mark.parametrize("async_provider", [False, True]) + async def test_explicit_token_providers_and_headers_async(self, *, claude_sdk: Any, async_provider: bool) -> None: + provider = AsyncMock(return_value="token") if async_provider else lambda: "token" + headers = {"X-Route": "test", "Authorization": "private"} + target = ClaudeChatTarget( + model_name="claude-sonnet-4-6", api_key=provider, endpoint="https://anthropic.invalid", headers=headers + ) + headers["X-Route"] = "changed" + claude_sdk.acompletion.return_value = _mock_response() + await target.send_prompt_async(message=_user_message()) + assert claude_sdk.acompletion.call_args.kwargs["api_key"] == "token" + assert claude_sdk.acompletion.call_args.kwargs["api_base"] == "https://anthropic.invalid" + assert claude_sdk.acompletion.call_args.kwargs["extra_headers"]["X-Route"] == "test" + assert target.get_identifier().params["headers"] == {"X-Route": "test"} + assert "private" not in str(target.get_identifier()) + + @pytest.mark.parametrize("header", ["Ocp-Apim-Subscription-Key", "oCp-ApIm-SuBsCrIpTiOn-KeY"]) + async def test_gateway_key_is_not_persisted_async( + self, *, claude_sdk: Any, sqlite_instance: Any, header: str + ) -> None: + from pyrit.prompt_normalizer import PromptNormalizer + + target = ClaudeChatTarget( + model_name="claude-sonnet-4-6", headers={header: "private-gateway-key", "X-Route": "gateway"} + ) + claude_sdk.acompletion.return_value = _mock_response() + await PromptNormalizer().send_prompt_async( + target=target, message=_user_message(), conversation_id="gateway-credentials" + ) + assert claude_sdk.acompletion.call_args.kwargs["extra_headers"][header] == "private-gateway-key" + identifiers = await sqlite_instance.get_target_identifiers_async( + identifier_hashes=[target.get_identifier().hash] + ) + assert len(identifiers) == 1 + assert identifiers[0].params["headers"] == {"X-Route": "gateway"} + assert "private-gateway-key" not in str(identifiers[0]) + + def test_discovery_and_forwarded_constructor(self, claude_sdk: Any) -> None: + registry = TargetRegistry() + assert registry.get_class("ClaudeChatTarget") is ClaudeChatTarget + target = registry.create_instance("ClaudeChatTarget", model_name="claude-sonnet-4-6", max_tokens=256) + assert isinstance(target, ClaudeChatTarget) + assert target._max_tokens == 256 + + async def test_optional_import_error_is_actionable_async(self) -> None: + with patch.dict(sys.modules, {"litellm": None}): + target = ClaudeChatTarget(model_name="claude-sonnet-4-6") + with pytest.raises(ImportError, match=r"pip install pyrit\[litellm\]"): + await target.send_prompt_async(message=_user_message()) + + @pytest.mark.parametrize("json_output", [False, True]) + async def test_real_anthropic_adapter_system_image_tools_and_replay_async( + self, *, sqlite_instance: Any, json_output: bool + ) -> None: + pytest.importorskip("litellm") + from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler + + @tool + async def add_async(*, value: int) -> int: + return value + 1 + + target = ClaudeChatTarget(model_name="claude-sonnet-4-6", api_key="test-key", tools=[add_async], max_tokens=256) + from pyrit.prompt_normalizer import PromptNormalizer + + normalizer = PromptNormalizer() + await target.set_system_prompt_async(system_prompt="Be concise.", conversation_id="native") + content = [ + [ + {"type": "text", "text": "Checking."}, + {"type": "tool_use", "id": "use_1", "name": "add_async", "input": {"value": 2}}, + ], + [ + { + "type": "tool_use", + "id": "format_1", + "name": ClaudeChatTarget._JSON_OUTPUT_TOOL_NAME, + "input": {"answer": 3}, + } + ] + if json_output + else [{"type": "text", "text": "3"}], + [{"type": "text", "text": "Again."}], + ] + if json_output: + content[0].append( + { + "type": "tool_use", + "id": "format_preview", + "name": ClaudeChatTarget._JSON_OUTPUT_TOOL_NAME, + "input": {"pending": True}, + } + ) + replies = [ + httpx.Response( + 200, + request=httpx.Request("POST", "https://api.anthropic.com/v1/messages"), + json={ + "id": f"msg_{i}", + "type": "message", + "role": "assistant", + "model": "claude-sonnet-4-6", + "content": blocks, + "stop_reason": "tool_use" if i == 0 else "end_turn", + "stop_sequence": None, + "usage": {"input_tokens": 12, "output_tokens": 8}, + }, + ) + for i, blocks in enumerate(content) + ] + from pyrit.common.path import HOME_PATH + + image = MessagePiece( + role="user", + original_value=str(HOME_PATH / "assets" / "pyrit_architecture.png"), + original_value_data_type="image_path", + ) + text = MessagePiece( + role="user", + original_value="Use add_async for 2.", + prompt_metadata=JsonResponseConfig(enabled=json_output).to_metadata(), + ) + with patch.object(AsyncHTTPHandler, "post", new_callable=AsyncMock, side_effect=replies) as post: + result = await normalizer.send_prompt_async( + target=target, message=Message(message_pieces=[text, image]), conversation_id="native" + ) + if json_output: + assert json.loads(result.get_value()) == {"answer": 3} + else: + assert result.get_value() == "3" + await normalizer.send_prompt_async(target=target, message=_user_message("Again"), conversation_id="native") + assert post.await_count == 3 + assert all(call.args[0] == "https://api.anthropic.com/v1/messages" for call in post.call_args_list) + bodies = [call.kwargs["json"] for call in post.call_args_list] + assert bodies[0]["model"] == "claude-sonnet-4-6" + assert bodies[0]["system"][0]["text"] == "Be concise." + assert bodies[0]["messages"][0]["content"][1]["type"] == "image" + assert any(definition["name"] == "add_async" for definition in bodies[0]["tools"]) + assert bodies[1]["messages"][-1]["content"][0]["type"] == "tool_result" + assert bodies[1]["messages"][-1]["content"][0]["tool_use_id"] == "use_1" + assert any( + block.get("type") == "tool_result" for message in bodies[2]["messages"] for block in message["content"] + ) + persisted = await sqlite_instance.get_conversation_messages_async(conversation_id="native") + assert [message.api_role for message in persisted] == [ + "system", + "user", + "assistant", + "tool", + "assistant", + "user", + "assistant", + ] + if json_output: + assert any( + definition["name"] == ClaudeChatTarget._JSON_OUTPUT_TOOL_NAME for definition in bodies[0]["tools"] + ) + assert bodies[0]["tool_choice"]["type"] == "auto" + + @pytest.mark.parametrize("include_text", [False, True]) + async def test_real_tool_based_json_adapter_does_not_dispatch_formatting_tool_async( + self, include_text: bool + ) -> None: + pytest.importorskip("litellm") + from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler + + @tool + async def benign_async() -> str: + return "ok" + + target = ClaudeChatTarget(model_name="claude-sonnet-4-5", api_key="test-key", tools=[benign_async]) + response = httpx.Response( + 200, + request=httpx.Request("POST", "https://api.anthropic.com/v1/messages"), + json={ + "id": "msg_json", + "type": "message", + "role": "assistant", + "model": "claude-sonnet-4-5", + "content": [ + *([{"type": "text", "text": "Here is the result."}] if include_text else []), + { + "type": "tool_use", + "id": "json_1", + "name": ClaudeChatTarget._JSON_OUTPUT_TOOL_NAME, + "input": {"answer": "ok"}, + }, + ], + "stop_reason": "tool_use", + "usage": {"input_tokens": 1, "output_tokens": 2}, + }, + ) + with ( + patch.object(AsyncHTTPHandler, "post", new_callable=AsyncMock, return_value=response) as post, + patch.object(target, "_extract_response_cost", return_value=0.25), + ): + replies = await target.send_prompt_async( + message=MessagePiece( + role="user", + original_value="Return JSON.", + prompt_metadata={ + **JsonResponseConfig(enabled=True).to_metadata(), + "token_usage_input_tokens": 999, + "token_usage_cost": "999", + "finish_reason": "stale", + "status": "stale", + "incomplete_reason": "stale", + "caller_tag": "keep", + }, + ).to_message() + ) + assert json.loads(replies[-1].get_value()) == {"answer": "ok"} + assert all(piece.converted_value_data_type == "text" for reply in replies for piece in reply.message_pieces) + pieces = replies[-1].message_pieces + assert len(pieces) == (2 if include_text else 1) + assert pieces[0].prompt_metadata["token_usage_input_tokens"] == 1 + assert pieces[0].prompt_metadata["token_usage_output_tokens"] == 2 + assert pieces[0].prompt_metadata["token_usage_cost"] == "0.25" + assert pieces[0].prompt_metadata["finish_reason"] == "tool_calls" + assert all(piece.prompt_metadata["caller_tag"] == "keep" for piece in pieces) + assert all( + "status" not in piece.prompt_metadata and "incomplete_reason" not in piece.prompt_metadata + for piece in pieces + ) + for piece in pieces[1:]: + assert piece.converted_value == "Here is the result." + assert not any(key.startswith("token_usage_") or key == "finish_reason" for key in piece.prompt_metadata) + assert post.await_count == 1 + + async def test_real_anthropic_explicit_schema_async(self) -> None: + pytest.importorskip("litellm") + from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler + + target = ClaudeChatTarget(model_name="claude-sonnet-4-6", api_key="test-key") + target.apply_capabilities(capabilities=target.capabilities.model_copy(update={"supports_json_schema": True})) + schema = { + "type": "object", + "properties": {"answer": {"type": "integer"}}, + "required": ["answer"], + "additionalProperties": False, + } + response = httpx.Response( + 200, + request=httpx.Request("POST", "https://api.anthropic.com/v1/messages"), + json={ + "id": "msg_schema", + "type": "message", + "role": "assistant", + "model": "claude-sonnet-4-6", + "content": [{"type": "text", "text": '{"answer":8}'}], + "stop_reason": "end_turn", + "usage": {"input_tokens": 1, "output_tokens": 2}, + }, + ) + with patch.object(AsyncHTTPHandler, "post", new_callable=AsyncMock, return_value=response) as post: + replies = await target.send_prompt_async( + message=MessagePiece( + role="user", + original_value="Return JSON.", + prompt_metadata=JsonResponseConfig(json_schema=schema).to_metadata(), + ).to_message() + ) + assert json.loads(replies[-1].get_value()) == {"answer": 8} + body = post.call_args.kwargs["json"] + assert body["output_format"]["schema"] == schema + assert "tools" not in body + + @pytest.mark.parametrize("value", ["not JSON", "[]"]) + async def test_json_final_response_is_returned_for_the_caller_to_validate_async( + self, *, claude_sdk: Any, value: str + ) -> None: + target = ClaudeChatTarget(model_name="claude-sonnet-4-6") + claude_sdk.acompletion.return_value = _mock_response(content=value) + replies = await target.send_prompt_async( + message=MessagePiece( + role="user", + original_value="Return JSON.", + prompt_metadata=JsonResponseConfig(enabled=True).to_metadata(), + ).to_message() + ) + assert replies[-1].get_value() == value + + def test_formatter_name_is_reserved(self) -> None: + @tool + async def benign_async() -> str: + return "ok" + + benign_async.name = ClaudeChatTarget._JSON_OUTPUT_TOOL_NAME + target = ClaudeChatTarget(model_name="claude-sonnet-4-6", tools=[benign_async]) + with pytest.raises(ValueError, match="reserved"): + target._validate_tool_definitions([benign_async]) diff --git a/tests/unit/prompt_target/target/test_litellm_chat_target.py b/tests/unit/prompt_target/target/test_litellm_chat_target.py index d9bde1c579..6f6ba4b333 100644 --- a/tests/unit/prompt_target/target/test_litellm_chat_target.py +++ b/tests/unit/prompt_target/target/test_litellm_chat_target.py @@ -6,7 +6,8 @@ import json import sys import types -from collections.abc import Callable +from collections.abc import AsyncGenerator, Callable +from contextlib import asynccontextmanager from typing import Any from unittest.mock import AsyncMock, MagicMock, patch @@ -36,17 +37,24 @@ RequestTraceContext, ScoringExpectation, ToolCallRequirement, + ToolExecutionMetadata, + ToolLoopStop, + ToolLoopStopReason, ToolsCalled, TraceScorable, ) from pyrit.prompt_normalizer import PromptNormalizer from pyrit.prompt_target import ( + ClaudeChatTarget, + FunctionTool, LiteLLMChatTarget, OpenAIChatAudioConfig, TargetCapabilities, TargetConfiguration, TargetTraceConfig, + ToolInfrastructureError, discover_target_capabilities_async, + tool, ) from pyrit.prompt_target.common.discover_target_capabilities import CapabilityDiscoveryError from pyrit.score import InMemoryTraceClient, InMemoryTraceExporter, OtelToolCallScorer, OtelTraceSource @@ -168,6 +176,396 @@ def _disabled_json_config() -> JsonResponseConfig: return JsonResponseConfig.from_metadata(metadata={}) +def _tool_response(*, calls: list[tuple[str, str, str]], finish_reason: str = "tool_calls") -> Any: + response = _mock_response(content="Checking.", finish_reason=finish_reason) + response.choices[0].message.tool_calls = [] + for call_id, name, arguments in calls: + call = MagicMock() + call.id = call_id + call.function.name = name + call.function.arguments = arguments + response.choices[0].message.tool_calls.append(call) + return response + + +@pytest.fixture +def weather_tool() -> tuple[FunctionTool, list[str]]: + executions: list[str] = [] + + @tool + async def weather_async(*, location: str) -> str: + executions.append(location) + return f"Sunny in {location}" + + return weather_async, executions + + +@pytest.mark.usefixtures("patch_central_database") +class TestLiteLLMToolLoop: + @pytest.mark.parametrize("target_class", [LiteLLMChatTarget, ClaudeChatTarget]) + @pytest.mark.parametrize("executable", [False, True]) + async def test_null_passthrough_tools_are_omitted_async( + self, + *, + litellm_stub: Any, + weather_tool: tuple[FunctionTool, list[str]], + target_class: type[LiteLLMChatTarget], + executable: bool, + ) -> None: + target = target_class( + model_name="anthropic/claude-sonnet-4-6", + tools=[weather_tool[0]] if executable else None, + extra_body_parameters={"tools": None}, + ) + litellm_stub.acompletion.return_value = _mock_response() + await target.send_prompt_async(message=_user_message()) + body = litellm_stub.acompletion.call_args.kwargs + if executable: + assert body["tools"][0]["function"]["name"] == "weather_async" + else: + assert "tools" not in body + assert weather_tool[1] == [] + + async def test_duplicate_registrations_fail_before_sending_async( + self, *, litellm_stub: Any, weather_tool: tuple[FunctionTool, list[str]] + ) -> None: + target = LiteLLMChatTarget(model_name="openai/gpt-4o", tools=[weather_tool[0], weather_tool[0]]) + with pytest.raises(ValueError, match="Duplicate tool name"): + await target.send_prompt_async(message=_user_message()) + litellm_stub.acompletion.assert_not_awaited() + + async def test_passthrough_tool_conflict_fails_before_sending_async( + self, *, litellm_stub: Any, weather_tool: tuple[FunctionTool, list[str]] + ) -> None: + target = LiteLLMChatTarget( + model_name="openai/gpt-4o", + tools=[weather_tool[0]], + extra_body_parameters={"tools": [{"type": "function", "function": {"name": "weather_async"}}]}, + ) + with pytest.raises(ValueError, match="conflict"): + await target.send_prompt_async(message=_user_message()) + litellm_stub.acompletion.assert_not_awaited() + + async def test_unserializable_result_propagates_after_execution_async(self, litellm_stub: Any) -> None: + executions: list[str] = [] + + @tool + async def unserializable_async() -> object: + executions.append("ran") + return object() + + target = LiteLLMChatTarget(model_name="openai/gpt-4o", tools=[unserializable_async]) + litellm_stub.acompletion.side_effect = [ + _tool_response(calls=[("a", "unserializable_async", "{}")]), + _mock_response("Recovered."), + ] + with pytest.raises(TypeError): + await target.send_prompt_async(message=_user_message()) + assert executions == ["ran"] + assert litellm_stub.acompletion.await_count == 1 + + async def test_arguments_are_validated_like_openai_response_target_async(self, litellm_stub: Any) -> None: + received: list[int] = [] + + @tool + async def count_async(*, value: int) -> str: + received.append(value) + return "counted" + + target = LiteLLMChatTarget(model_name="openai/gpt-4o", tools=[count_async]) + litellm_stub.acompletion.side_effect = [ + _tool_response(calls=[("a", "count_async", '{"value":"7"}')]), + _mock_response("Done."), + ] + replies = await target.send_prompt_async(message=_user_message()) + assert received == [7] + assert json.loads(replies[1].get_value())["output"] == "counted" + + @pytest.mark.parametrize("max_rounds", [-1, True, 1.5]) + def test_invalid_budget(self, max_rounds: Any) -> None: + with pytest.raises(ValueError, match="nonnegative integer"): + LiteLLMChatTarget(model_name="openai/gpt-4o", max_tool_rounds=max_rounds) + + @pytest.mark.parametrize("extra", [{}, {"n": 2}]) + def test_multiple_completions_rejected( + self, *, weather_tool: tuple[FunctionTool, list[str]], extra: dict[str, Any] + ) -> None: + with pytest.raises(ValueError, match="n=1"): + LiteLLMChatTarget(model_name="openai/gpt-4o", tools=[weather_tool[0]], n=2, extra_body_parameters=extra) + + async def test_multicall_multiround_and_persisted_replay_async( + self, *, litellm_stub: Any, sqlite_instance: SQLiteMemory, weather_tool: tuple[FunctionTool, list[str]] + ) -> None: + configured, executions = weather_tool + target = LiteLLMChatTarget( + model_name="openai/gpt-4o", underlying_model="gpt-4o", tools=[configured], max_tool_rounds=2 + ) + litellm_stub.acompletion.side_effect = [ + _tool_response( + calls=[("a", "weather_async", '{"location":"SF"}'), ("b", "weather_async", '{"location":"NY"}')] + ), + _tool_response(calls=[("c", "weather_async", '{"location":"LA"}')]), + _mock_response("Done."), + _mock_response("Second."), + ] + normalizer = PromptNormalizer() + result = await normalizer.send_prompt_async(target=target, message=_user_message(), conversation_id="loop") + assert result.get_value() == "Done." + history = await sqlite_instance.get_conversation_messages_async(conversation_id="loop") + assert [message.api_role for message in history] == [ + "user", + "assistant", + "tool", + "tool", + "assistant", + "tool", + "assistant", + ] + assert history[1].message_pieces[0].converted_value == "Checking." + assert executions == ["SF", "NY", "LA"] + target.validate_tool_history(history) + await normalizer.send_prompt_async(target=target, message=_user_message("Second"), conversation_id="loop") + messages = litellm_stub.acompletion.call_args.kwargs["messages"] + assert [message["role"] for message in messages] == [ + "user", + "assistant", + "tool", + "tool", + "assistant", + "tool", + "assistant", + "user", + ] + assert [message["tool_call_id"] for message in messages if message["role"] == "tool"] == ["a", "b", "c"] + assert executions == ["SF", "NY", "LA"] + + @pytest.mark.parametrize("budget", [0, 1]) + async def test_exhaustion_never_executes_beyond_budget_async( + self, *, litellm_stub: Any, weather_tool: tuple[FunctionTool, list[str]], budget: int + ) -> None: + target = LiteLLMChatTarget(model_name="openai/gpt-4o", tools=[weather_tool[0]], max_tool_rounds=budget) + litellm_stub.acompletion.side_effect = [ + _tool_response(calls=[("a", "weather_async", '{"location":"SF"}')]), + _tool_response(calls=[("b", "weather_async", '{"location":"NY"}')]), + ] + responses = await target.send_prompt_async(message=_user_message()) + assert weather_tool[1] == (["SF"] if budget else []) + assert responses[-1].get_piece().response_error == "processing" + output = responses[-2].get_piece() + assert "max_tool_rounds_exhausted" in output.converted_value + assert ToolExecutionMetadata.from_metadata(metadata=output.prompt_metadata).invoked is False + assert litellm_stub.acompletion.await_count == budget + 1 + stop = ToolLoopStop.from_metadata(metadata=responses[-1].get_piece().prompt_metadata) + assert stop.reason == ToolLoopStopReason.MAX_TOOL_ROUNDS_EXHAUSTED + + @pytest.mark.parametrize( + ("name", "arguments"), + [ + ("unknown", "{}"), + ("weather_async", "{"), + ("weather_async", "[]"), + ("weather_async", "{}"), + ("weather_async", '{"location":"SF","extra":1}'), + ], + ) + async def test_dispatch_errors_return_linked_results_without_execution_async( + self, *, litellm_stub: Any, weather_tool: tuple[FunctionTool, list[str]], name: str, arguments: str + ) -> None: + target = LiteLLMChatTarget(model_name="openai/gpt-4o", tools=[weather_tool[0]]) + litellm_stub.acompletion.side_effect = [ + _tool_response(calls=[("a", name, arguments)]), + _mock_response("Recovered."), + ] + replies = await target.send_prompt_async(message=_user_message()) + assert weather_tool[1] == [] + assert replies[-1].get_value() == "Recovered." + result = json.loads(replies[1].get_value()) + assert result["call_id"] == "a" + assert "error" in json.loads(result["output"]) + assert ToolExecutionMetadata.from_metadata(metadata=replies[1].get_piece().prompt_metadata).invoked is False + + @pytest.mark.parametrize("call_id", ["", " ", "duplicate"]) + async def test_invalid_or_duplicate_ids_stop_before_batch_execution_async( + self, *, litellm_stub: Any, weather_tool: tuple[FunctionTool, list[str]], call_id: str + ) -> None: + target = LiteLLMChatTarget(model_name="openai/gpt-4o", tools=[weather_tool[0]]) + calls = [(call_id, "weather_async", '{"location":"SF"}')] + if call_id == "duplicate": + calls *= 2 + litellm_stub.acompletion.return_value = _tool_response(calls=calls) + replies = await target.send_prompt_async(message=_user_message()) + assert weather_tool[1] == [] + assert replies[-1].get_piece().response_error == "processing" + assert "Invalid tool calls" in replies[-1].get_value() + assert litellm_stub.acompletion.await_count == 1 + stop = ToolLoopStop.from_metadata(metadata=replies[-1].get_piece().prompt_metadata) + assert stop.reason == ToolLoopStopReason.INVALID_TOOL_CALLS + + async def test_reused_id_from_prior_round_does_not_reexecute_async( + self, *, litellm_stub: Any, weather_tool: tuple[FunctionTool, list[str]] + ) -> None: + target = LiteLLMChatTarget(model_name="openai/gpt-4o", tools=[weather_tool[0]]) + litellm_stub.acompletion.side_effect = [ + _tool_response(calls=[("a", "weather_async", '{"location":"SF"}')]), + _tool_response(calls=[("a", "weather_async", '{"location":"NY"}')]), + ] + replies = await target.send_prompt_async(message=_user_message()) + assert weather_tool[1] == ["SF"] + assert "reused" in replies[-1].get_value() + + async def test_truncation_never_executes_partial_calls_async( + self, *, litellm_stub: Any, weather_tool: tuple[FunctionTool, list[str]] + ) -> None: + target = LiteLLMChatTarget(model_name="openai/gpt-4o", tools=[weather_tool[0]]) + litellm_stub.acompletion.return_value = _tool_response( + calls=[("a", "weather_async", '{"location":')], finish_reason="length" + ) + replies = await target.send_prompt_async(message=_user_message()) + assert weather_tool[1] == [] + assert replies[0].get_piece().is_truncated + assert replies[-1].get_piece().response_error == "processing" + stop = ToolLoopStop.from_metadata(metadata=replies[-1].get_piece().prompt_metadata) + assert stop.reason == ToolLoopStopReason.INVALID_TOOL_CALLS + + async def test_continuation_failure_propagates_after_execution_async( + self, *, litellm_stub: Any, weather_tool: tuple[FunctionTool, list[str]] + ) -> None: + target = LiteLLMChatTarget(model_name="openai/gpt-4o", underlying_model="gpt-4o", tools=[weather_tool[0]]) + litellm_stub.acompletion.side_effect = [ + _tool_response(calls=[("a", "weather_async", '{"location":"SF"}')]), + RuntimeError("offline failure"), + ] + with pytest.raises(Exception, match="offline failure"): + await target.send_prompt_async(message=_user_message()) + assert weather_tool[1] == ["SF"] + assert litellm_stub.acompletion.await_count == 2 + + @pytest.mark.parametrize("cancel", [False, True]) + async def test_tool_errors_and_cancellation_close_provider_scope_async( + self, *, litellm_stub: Any, cancel: bool + ) -> None: + @tool + async def failing_async() -> str: + if cancel: + raise asyncio.CancelledError + raise RuntimeError("Tool failed.") + + events: list[str] = [] + + class Provider: + identifier = {"provider": "test"} + + @asynccontextmanager + async def execution_scope_async(self) -> AsyncGenerator[None, None]: + events.append("open") + try: + yield + finally: + events.append("close") + + async def get_tools_async(self) -> list[FunctionTool]: + assert events == ["open"] + return [failing_async] + + target = LiteLLMChatTarget(model_name="openai/gpt-4o", tool_providers=[Provider()]) + litellm_stub.acompletion.side_effect = [ + _tool_response(calls=[("a", "failing_async", "{}")]), + _mock_response("Recovered."), + ] + with pytest.raises(asyncio.CancelledError if cancel else RuntimeError): + await target.send_prompt_async(message=_user_message()) + assert events == ["open", "close"] + assert litellm_stub.acompletion.await_count == 1 + + @pytest.mark.parametrize("target_class", [LiteLLMChatTarget, ClaudeChatTarget]) + @pytest.mark.parametrize("failure_index", [0, 1, 2]) + @pytest.mark.parametrize("failure_invoked", [True, False]) + async def test_infrastructure_failure_ends_round_with_complete_persisted_history_async( + self, + *, + litellm_stub: Any, + sqlite_instance: SQLiteMemory, + target_class: type[LiteLLMChatTarget], + failure_index: int, + failure_invoked: bool, + ) -> None: + executions: list[int] = [] + events: list[str] = [] + + @tool + async def unstable_async(*, index: int) -> str: + executions.append(index) + if index == failure_index: + raise ToolInfrastructureError("Sandbox unavailable.", invoked=failure_invoked) + return f"completed {index}" + + class Provider: + identifier = {"provider": "isolated-test"} + + @asynccontextmanager + async def execution_scope_async(self) -> AsyncGenerator[None, None]: + events.append("open") + try: + yield + finally: + events.append("close") + + async def get_tools_async(self) -> list[FunctionTool]: + return [unstable_async] + + target = target_class(model_name="anthropic/claude-sonnet-4-6", tool_providers=[Provider()]) + litellm_stub.acompletion.side_effect = [ + _tool_response(calls=[(str(index), "unstable_async", json.dumps({"index": index})) for index in range(3)]), + _mock_response("Another model request must not occur."), + ] + reply = await PromptNormalizer().send_prompt_async( + target=target, message=_user_message(), conversation_id="infrastructure-failure" + ) + assert reply.get_piece().response_error == "processing" + assert "Sandbox unavailable." in reply.get_value() + stop = ToolLoopStop.from_metadata(metadata=reply.get_piece().prompt_metadata) + assert stop.reason == ToolLoopStopReason.TOOL_INFRASTRUCTURE_ERROR + assert litellm_stub.acompletion.await_count == 1 + assert executions == list(range(failure_index + 1)) + assert events == ["open", "close"] + history = await sqlite_instance.get_conversation_messages_async(conversation_id="infrastructure-failure") + assert [message.api_role for message in history] == ["user", "assistant", "tool", "tool", "tool", "assistant"] + outputs = history[2:5] + assert [json.loads(message.get_value())["call_id"] for message in outputs] == ["0", "1", "2"] + assert [ + ToolExecutionMetadata.from_metadata(metadata=message.get_piece().prompt_metadata).invoked + for message in outputs + ] == [index < failure_index or (index == failure_index and failure_invoked) for index in range(3)] + errors = [json.loads(json.loads(message.get_value())["output"])["error"] for message in outputs[failure_index:]] + assert errors == ["tool_infrastructure_error"] + ["tool_not_executed"] * (2 - failure_index) + assert "Sandbox" not in outputs[failure_index].get_value() + target.validate_tool_history(history) + + async def test_execution_opt_out_advertises_but_returns_calls_async( + self, *, litellm_stub: Any, weather_tool: tuple[FunctionTool, list[str]] + ) -> None: + target = LiteLLMChatTarget(model_name="openai/gpt-4o", tools=[weather_tool[0]], execute_tools=False) + litellm_stub.acompletion.return_value = _tool_response(calls=[("a", "weather_async", '{"location":"SF"}')]) + replies = await target.send_prompt_async(message=_user_message()) + assert len(replies) == 1 + assert litellm_stub.acompletion.call_args.kwargs["tools"][0]["function"]["name"] == "weather_async" + assert weather_tool[1] == [] + + async def test_probe_neither_discovers_nor_executes_tools_async(self, litellm_stub: Any) -> None: + from pyrit.prompt_target import discover_target_capabilities_async + + class Provider: + identifier = {"provider": "test"} + + async def get_tools_async(self) -> list[FunctionTool]: + raise AssertionError("Probes must not discover tools.") + + target = LiteLLMChatTarget(model_name="openai/gpt-4o", tool_providers=[Provider()]) + litellm_stub.acompletion.return_value = _mock_response() + await discover_target_capabilities_async(target=target, capabilities=["supports_multi_turn"], retries=0) + assert "tools" not in litellm_stub.acompletion.call_args.kwargs + + @pytest.mark.parametrize("enabled", [False, True]) def test_tool_history_capability_from_model_metadata(patch_central_database, litellm_stub, enabled: bool) -> None: litellm_stub.supports_function_calling.return_value = enabled diff --git a/tests/unit/prompt_target/target/test_mcp_tool_provider.py b/tests/unit/prompt_target/target/test_mcp_tool_provider.py index 74fb0b5917..da4defd969 100644 --- a/tests/unit/prompt_target/target/test_mcp_tool_provider.py +++ b/tests/unit/prompt_target/target/test_mcp_tool_provider.py @@ -515,6 +515,7 @@ async def execution_scope(): target._tool_providers = [provider] target._suppress_tools = False target._execute_tools = True + target._max_tool_rounds = 10 target._get_json_response_config = MagicMock(return_value=JsonResponseConfig(enabled=False)) # type: ignore[method-assign] target._construct_request_body_async = AsyncMock(return_value={}) # type: ignore[method-assign] response = Message( diff --git a/tests/unit/prompt_target/target/test_openai_response_target.py b/tests/unit/prompt_target/target/test_openai_response_target.py index e62370ce06..d2a2d7d056 100644 --- a/tests/unit/prompt_target/target/test_openai_response_target.py +++ b/tests/unit/prompt_target/target/test_openai_response_target.py @@ -46,7 +46,8 @@ ) from pyrit.prompt_normalizer import PromptNormalizer from pyrit.prompt_target import OpenAIResponseTarget, PromptTarget -from pyrit.prompt_target.openai.openai_response_target import _ToolDispatchResult, token_usage_from_responses +from pyrit.prompt_target.common.tool_loop import ToolDispatchResult +from pyrit.prompt_target.openai.openai_response_target import token_usage_from_responses from pyrit.score import SelfAskRefusalScorer, TrueFalseInverterScorer @@ -1328,7 +1329,7 @@ def test_make_tool_piece_serializes_output_and_sets_call_id(target: OpenAIRespon conversation_id="test-conv-123", ) piece = target._make_tool_piece( - result=_ToolDispatchResult(output=out, invoked=invoked), call_id="tool-1", reference_piece=reference_piece + result=ToolDispatchResult(output=out, invoked=invoked), call_id="tool-1", reference_piece=reference_piece ) assert ToolExecutionMetadata.from_metadata(metadata=piece.prompt_metadata) == ToolExecutionMetadata(invoked=invoked) assert piece.original_value_data_type == "function_call_output" diff --git a/uv.lock b/uv.lock index 46e05dc83f..56d604c05a 100644 --- a/uv.lock +++ b/uv.lock @@ -5213,8 +5213,8 @@ requires-dist = [ { name = "jinja2", specifier = ">=3.1.6" }, { name = "jsonschema", specifier = ">=4.25.1" }, { name = "jupyter", marker = "extra == 'all'", specifier = ">=1.1.1" }, - { name = "litellm", marker = "extra == 'all'", specifier = ">=1.104.2" }, - { name = "litellm", marker = "extra == 'litellm'", specifier = ">=1.104.2" }, + { name = "litellm", marker = "extra == 'all'", specifier = ">=1.108.0" }, + { name = "litellm", marker = "extra == 'litellm'", specifier = ">=1.108.0" }, { name = "markdown-it-py", specifier = ">=4.0.0,<5" }, { name = "mcp", specifier = ">=2.2,<3" }, { name = "numpy", marker = "python_full_version < '3.14'", specifier = ">=1.26.0" },