From f0adefbe4894816c7d625098726f3963a2aeceae Mon Sep 17 00:00:00 2001 From: Adrian Gavrila Date: Mon, 23 Nov 2026 10:03:01 -0500 Subject: [PATCH] Let the registry copy LiteLLM targets Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- doc/code/registry/0_registry.md | 9 +- pyrit/backend/README.md | 12 +- pyrit/prompt_target/litellm_chat_target.py | 48 +++++++ .../unit/backend/test_temporary_components.py | 40 ++++++ .../target/test_litellm_chat_target.py | 121 ++++++++++++++++++ 5 files changed, 221 insertions(+), 9 deletions(-) diff --git a/doc/code/registry/0_registry.md b/doc/code/registry/0_registry.md index 8bfe8cd033..0621e5f00c 100644 --- a/doc/code/registry/0_registry.md +++ b/doc/code/registry/0_registry.md @@ -133,10 +133,11 @@ Use `source.params` to override constructor defaults; do not also supply `params keeps the source's other constructor inputs, including authentication, on the server. It does not change the source. A copy also keeps the settings that choose where requests go and how they sign in, such as `endpoint`, `auth_mode`, -`api_key` and `headers` for OpenAI targets, and the region, key and resource ID -for the Azure Speech converters; overriding one of these is an error. Such -parameters report `copy_locked: true`, and components declare them in -`COPY_LOCKED_PARAMETER_NAMES`. Missing, changed, or ambiguous sources +`api_key` and `headers` for OpenAI targets, `model_name`, `endpoint`, `api_key`, +`headers` and `extra_body_parameters` for LiteLLM targets (including Claude), and +the region, key and resource ID for the Azure Speech converters; overriding one of +these is an error. Such parameters report `copy_locked: true`, and components +declare them in `COPY_LOCKED_PARAMETER_NAMES`. Missing, changed, or ambiguous sources produce an error. If a source was renamed, a unique matching hash can resolve it. An optional `effective_hash` checks the reconstructed object's identity. Converter descriptors expose `reconstructable` and `reconstruction_error`; diff --git a/pyrit/backend/README.md b/pyrit/backend/README.md index 7f9fddc9fa..11a862adaa 100644 --- a/pyrit/backend/README.md +++ b/pyrit/backend/README.md @@ -943,11 +943,13 @@ uses them: folder, and callers cannot supply their own. - A copy of a registered target or converter, made from its `source`, keeps the source's connection: it can't change the parameters its type reports as `copy_locked` (for OpenAI - targets the endpoint, `auth_mode`, key, headers, and HTTP client settings; for the Azure - Speech converters the region, key, and resource ID), and trying returns **400**. So a copy - can't take its source's credentials, or a token for an identity its source was set up with, - to another endpoint or resource. This rule covers copies only: creating a new target can - still send this server's key to an endpoint the caller chooses, as described below. + targets the endpoint, `auth_mode`, key, headers, and HTTP client settings; for LiteLLM + targets, including Claude, the model name, endpoint, key, headers, and extra body + parameters; for the Azure Speech converters the region, key, and resource ID), and trying + returns **400**. So a copy can't take its source's credentials, or a token for an identity + its source was set up with, to another endpoint or resource. This rule covers copies only: + creating a new target can still send this server's key to an endpoint the caller chooses, + as described below. Targets that need a setting the API does not allow can be registered in Python or with an initializer. diff --git a/pyrit/prompt_target/litellm_chat_target.py b/pyrit/prompt_target/litellm_chat_target.py index 84a9455ff0..8d51881741 100644 --- a/pyrit/prompt_target/litellm_chat_target.py +++ b/pyrit/prompt_target/litellm_chat_target.py @@ -11,6 +11,7 @@ from typing import Any, ClassVar, NoReturn, cast from pyrit.auth import ensure_async_token_provider +from pyrit.common.constructor_capture import capture_constructor_parameters from pyrit.exceptions import ( EmptyResponseException, PyritException, @@ -226,6 +227,12 @@ class LiteLLMChatTarget(PromptTarget): """ server_fallback_parameters: ClassVar[Mapping[str, str | None]] = MappingProxyType({"api_key": None}) + # A model name's provider prefix chooses where requests and the key go. + COPY_LOCKED_PARAMETER_NAMES: ClassVar[frozenset[str]] = frozenset( + {"model_name", "endpoint", "api_key", "headers", "extra_body_parameters"} + ) + + _reconstruction_parameters: dict[str, object] = {} # 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. @@ -258,6 +265,13 @@ class LiteLLMChatTarget(PromptTarget): ) ) + def __init_subclass__(cls, **kwargs: object) -> None: + """Opt in LiteLLM implementations to server-only reconstruction.""" + super().__init_subclass__(**kwargs) + if "__init__" in cls.__dict__: + type.__setattr__(cls, "__init__", capture_constructor_parameters(cls.__init__)) + + @capture_constructor_parameters def __init__( self, *, @@ -474,6 +488,40 @@ def _identifier_headers(self) -> dict[str, str] | None: name: value for name, value in (self._headers or {}).items() if name.lower() not in self._CREDENTIAL_HEADERS } or None + def get_reconstruction_parameters(self) -> dict[str, object]: + """ + Return server-only inputs, including resolved authentication. + + Returns: + dict[str, object]: Resolved constructor inputs. + + Raises: + ValueError: If ``extra_body_parameters`` sets temperature, which a copy's temperature can't override. + """ + if "temperature" in (self._extra_body_parameters or {}): + raise ValueError( + "Separate temperature settings are not supported when extra_body_parameters sets temperature" + ) + # Resolved values, so a copy never reads this server's environment for what its source already resolved. + return { + **self._reconstruction_parameters, + "model_name": self._model_name, + "endpoint": self._endpoint, + "api_key": self._api_key, + "underlying_model": self._underlying_model, + "custom_configuration": self.configuration, + } + + def attach_reconstruction_source(self, source: object) -> None: + """ + Share request pacing and credential status, not behavioral configuration. + + Args: + source (object): The registered target this copy was built from. + """ + super().attach_reconstruction_source(source) + self._rate_limit_source = getattr(source, "_rate_limit_source", source) + def is_json_response_supported(self) -> bool: """ Whether this target honors a JSON ``response_format`` request. diff --git a/tests/unit/backend/test_temporary_components.py b/tests/unit/backend/test_temporary_components.py index 4660ea3344..899e3c605f 100644 --- a/tests/unit/backend/test_temporary_components.py +++ b/tests/unit/backend/test_temporary_components.py @@ -72,7 +72,9 @@ ) from pyrit.models.component_spec import SourceInstanceSpec, TargetBinding from pyrit.prompt_target import ( + ClaudeChatTarget, HuggingFaceChatTarget, + LiteLLMChatTarget, OpenAIChatTarget, OpenAICompletionTarget, OpenAIResponseTarget, @@ -84,6 +86,7 @@ from unit.async_utils import TEST_WATCHDOG_SECONDS, drain_tasks_async, wait_for_event_async from unit.backend.mocks import _settle_send_async from unit.mocks import openai_chat_response_json_dict +from unit.prompt_target.target.test_litellm_chat_target import _make_litellm_stub @pytest.fixture(autouse=True) @@ -99,6 +102,13 @@ def isolated_registries() -> Iterator[None]: registry.reset_registry_singleton() +@pytest.fixture +def litellm_sdk() -> Iterator[None]: + sdk, exceptions = _make_litellm_stub() + with patch.dict(sys.modules, {"litellm": sdk, "litellm.exceptions": exceptions}): + yield + + def source_target() -> OpenAIChatTarget: return OpenAIChatTarget( endpoint="https://example.test/v1", @@ -1041,6 +1051,36 @@ async def test_source_copy_keeps_connection_settings_async(self, params: dict[st finally: await source.cleanup_target_async() + @pytest.mark.usefixtures("litellm_sdk") + async def test_litellm_source_copy_is_private_and_shares_pacing_async(self) -> None: + source = ClaudeChatTarget( + model_name="claude-sonnet-4-6", api_key="test-only-key", temperature=0.2, max_requests_per_minute=30 + ) + registry = TargetRegistry.get_registry_singleton() + registry.instances.register(source, name="source") + private = await TargetService().build_from_source_async( + SourceInstanceSpec( + source_name="source", source_hash=source.get_identifier().hash, params={"temperature": 0.8} + ) + ) + assert private.get_identifier().temperature == 0.8 + assert private._api_key == "test-only-key" + assert _get_rate_limit_lock(private) is _get_rate_limit_lock(source) + assert source._temperature == 0.2 + assert registry.instances.get_names() == ["source"] + + @pytest.mark.usefixtures("litellm_sdk") + @pytest.mark.parametrize( + "params", [{"model_name": "openai/gpt-4o"}, {"endpoint": "https://other.test"}, {"api_key": "other-key"}] + ) + async def test_litellm_source_copy_keeps_connection_settings_async(self, params: dict[str, str]) -> None: + source = LiteLLMChatTarget(model_name="anthropic/claude-sonnet-4-6", api_key="test-only-key") + TargetRegistry.get_registry_singleton().instances.register(source, name="source") + with pytest.raises(ValueError, match=f"can't set {next(iter(params))}"): + await TargetService().build_from_source_async( + SourceInstanceSpec(source_name="source", source_hash=source.get_identifier().hash, params=params) + ) + async def test_runtime_temperature_preserves_saved_variant_binding_async( self, sqlite_instance: SQLiteMemory ) -> None: 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 6f6ba4b333..2e88fff3c6 100644 --- a/tests/unit/prompt_target/target/test_litellm_chat_target.py +++ b/tests/unit/prompt_target/target/test_litellm_chat_target.py @@ -48,6 +48,7 @@ ClaudeChatTarget, FunctionTool, LiteLLMChatTarget, + LiteLLMDecisionTarget, OpenAIChatAudioConfig, TargetCapabilities, TargetConfiguration, @@ -57,6 +58,7 @@ tool, ) from pyrit.prompt_target.common.discover_target_capabilities import CapabilityDiscoveryError +from pyrit.registry import TargetRegistry from pyrit.score import InMemoryTraceClient, InMemoryTraceExporter, OtelToolCallScorer, OtelTraceSource # --------------------------------------------------------------------------- @@ -591,6 +593,125 @@ async def test_tool_history_discovery_preserves_litellm_wire_fields(target: Lite assert messages[2]["tool_call_id"] == messages[1]["tool_calls"][0]["id"] +# --------------------------------------------------------------------------- +# Reconstruction +# --------------------------------------------------------------------------- + +_SECRET_HEADERS = {"Authorization": "Bearer test-only", "X-Route": "blue"} + + +@pytest.mark.usefixtures("patch_central_database", "litellm_stub") +class TestLiteLLMReconstruction: + @pytest.mark.parametrize( + "build", + [ + lambda: LiteLLMChatTarget( + model_name="openai/gpt-4o", + api_key="test-only-key", + endpoint="https://gateway.test", + headers=dict(_SECRET_HEADERS), + temperature=0.3, + max_tokens=64, + stop=["END"], + extra_body_parameters={"metadata": {"run": "1"}}, + max_requests_per_minute=30, + ), + lambda: LiteLLMChatTarget( + model_name="openai/gpt-4o-audio-preview", + audio_response_config=OpenAIChatAudioConfig(voice="alloy", audio_format="wav"), + ), + lambda: ClaudeChatTarget( + model_name="claude-sonnet-4-6", api_key="test-only-key", headers=dict(_SECRET_HEADERS), max_tokens=256 + ), + lambda: LiteLLMDecisionTarget( + model_name="openai/gpt-4o", api_key="test-only-key", headers=dict(_SECRET_HEADERS) + ), + ], + ids=["chat", "chat-audio", "claude", "decision"], + ) + def test_copy_without_overrides_matches_source(self, build: Callable[[], LiteLLMChatTarget]) -> None: + source = build() + copy = TargetRegistry().recreate_instance(source=source, params={}) + assert copy is not source + assert type(copy) is type(source) + assert copy.get_identifier().hash == source.get_identifier().hash + assert copy._api_key == source._api_key + assert copy._headers == source._headers + assert copy._extra_body_parameters == source._extra_body_parameters + assert copy._rate_limit_source is source + + @pytest.mark.parametrize( + ("target_class", "kwargs", "environment", "expected"), + [ + ( + LiteLLMChatTarget, + {}, + { + "LITELLM_MODEL": "openai/gpt-4o", + "LITELLM_API_KEY": "source-key", + "LITELLM_ENDPOINT": "https://source.test", + }, + ("openai/gpt-4o", "source-key", "https://source.test"), + ), + ( + ClaudeChatTarget, + {"model_name": "claude-sonnet-4-6"}, + {"ANTHROPIC_API_KEY": "source-key"}, + ("anthropic/claude-sonnet-4-6", "source-key", None), + ), + ], + ) + def test_copy_keeps_values_resolved_from_the_environment( + self, + *, + target_class: type[LiteLLMChatTarget], + kwargs: dict[str, Any], + environment: dict[str, str], + expected: tuple[str, str, str | None], + ) -> None: + with patch.dict("os.environ", environment): + source = target_class(**kwargs) + with patch.dict("os.environ", dict.fromkeys(environment, "changed")): + copy = TargetRegistry().recreate_instance(source=source, params={}) + assert (copy._model_name, copy._api_key, copy._endpoint) == expected + + async def test_copy_reuses_the_resolved_token_provider_async(self) -> None: + source = LiteLLMChatTarget(model_name="azure/gpt-4o", api_key=lambda: "test-token") + copy = TargetRegistry().recreate_instance(source=source, params={}) + assert copy._api_key is source._api_key + assert await copy._resolve_api_key_async() == "test-token" + + def test_copy_keeps_tool_settings(self, weather_tool: tuple[FunctionTool, list[str]]) -> None: + weather, _ = weather_tool + source = LiteLLMChatTarget(model_name="openai/gpt-4o", tools=[weather], execute_tools=False, max_tool_rounds=3) + copy = TargetRegistry().recreate_instance(source=source, params={}) + assert copy._direct_tools == [weather] + assert copy._execute_tools is False + assert copy._max_tool_rounds == 3 + assert copy.get_identifier().hash == source.get_identifier().hash + + def test_copy_adds_tools_without_changing_the_source(self, weather_tool: tuple[FunctionTool, list[str]]) -> None: + weather, _ = weather_tool + source = ClaudeChatTarget(model_name="claude-sonnet-4-6") + copy = TargetRegistry().recreate_instance(source=source, params={"tools": [weather], "max_tool_rounds": 2}) + assert copy._direct_tools == [weather] + assert copy._max_tool_rounds == 2 + assert source._direct_tools == [] + assert copy.get_identifier().hash != source.get_identifier().hash + + def test_copy_keeps_the_source_configuration(self) -> None: + source = LiteLLMChatTarget(model_name="openai/gpt-4o") + assert source.capabilities.supports_json_schema is False + source.apply_capabilities(capabilities=source.capabilities.model_copy(update={"supports_json_schema": True})) + copy = TargetRegistry().recreate_instance(source=source, params={}) + assert copy.capabilities == source.capabilities + + def test_copy_refuses_a_separate_temperature_in_extra_body_parameters(self) -> None: + source = LiteLLMChatTarget(model_name="openai/gpt-4o", extra_body_parameters={"temperature": 0.5}) + with pytest.raises(ValueError, match="extra_body_parameters sets temperature"): + TargetRegistry().get_reconstruction_parameters(source) + + # --------------------------------------------------------------------------- # Constructor # ---------------------------------------------------------------------------