Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions doc/code/registry/0_registry.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Comment thread
adrian-gavrila marked this conversation as resolved.
Resolved
`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`;
Expand Down
12 changes: 7 additions & 5 deletions pyrit/backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion pyrit/prompt_target/claude_chat_target.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def __init__(
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``.
``ANTHROPIC_API_KEY``, never ``LITELLM_API_KEY``; an empty string skips that default.
endpoint: Optional Anthropic API base URL; ignores ``LITELLM_ENDPOINT``.
headers: Additional request headers, copied at construction.
custom_configuration: Override model-specific capabilities and policy.
Expand Down
59 changes: 55 additions & 4 deletions pyrit/prompt_target/litellm_chat_target.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -182,9 +183,10 @@ class LiteLLMChatTarget(PromptTarget):
``LITELLM_MODEL`` environment variable.
api_key: Optional API key, or a callable that returns an access token (sync or async).
When omitted, falls back to the ``LITELLM_API_KEY`` environment variable and then
to LiteLLM's own provider-specific environment variable lookup.
to LiteLLM's own provider-specific environment variable lookup. An empty string
skips the ``LITELLM_API_KEY`` fallback.
endpoint: Optional base URL override (e.g. for a self-hosted proxy or LiteLLM gateway).
Falls back to the ``LITELLM_ENDPOINT`` environment variable.
Falls back to the ``LITELLM_ENDPOINT`` environment variable unless it is an empty string.
headers: Optional extra HTTP headers forwarded to the provider (``extra_headers``).
temperature: Sampling temperature (0-2).
top_p: Nucleus sampling probability (0-1).
Expand Down Expand Up @@ -226,6 +228,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.
Expand Down Expand Up @@ -258,6 +266,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,
*,
Expand Down Expand Up @@ -323,10 +338,12 @@ def __init__(
# sync token provider so we can uniformly await it at request time.
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._api_key = None if api_key == "" else ensure_async_token_provider(api_key)

endpoint_variable = self._ENDPOINT_ENVIRONMENT_VARIABLE
self._endpoint = endpoint or (os.environ.get(endpoint_variable) if endpoint_variable else None)
if endpoint is None and endpoint_variable:
endpoint = os.environ.get(endpoint_variable)
self._endpoint = endpoint or None
self._headers = headers
self._temperature = temperature
self._top_p = top_p
Expand Down Expand Up @@ -474,6 +491,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, with "" for unset ones, so a copy never reads this server's environment.
return {
**self._reconstruction_parameters,
"model_name": self._model_name,
"endpoint": self._endpoint or "",
"api_key": "" if self._api_key is None else 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.
Expand Down
40 changes: 40 additions & 0 deletions tests/unit/backend/test_temporary_components.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,9 @@
)
from pyrit.models.component_spec import SourceInstanceSpec, TargetBinding
from pyrit.prompt_target import (
ClaudeChatTarget,
HuggingFaceChatTarget,
LiteLLMChatTarget,
OpenAIChatTarget,
OpenAICompletionTarget,
OpenAIResponseTarget,
Expand All @@ -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)
Expand All @@ -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",
Expand Down Expand Up @@ -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:
Expand Down
148 changes: 148 additions & 0 deletions tests/unit/prompt_target/target/test_litellm_chat_target.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import asyncio
import base64
import json
import os
import sys
import types
from collections.abc import AsyncGenerator, Callable
Expand Down Expand Up @@ -48,6 +49,7 @@
ClaudeChatTarget,
FunctionTool,
LiteLLMChatTarget,
LiteLLMDecisionTarget,
OpenAIChatAudioConfig,
TargetCapabilities,
TargetConfiguration,
Expand All @@ -57,6 +59,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

# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -591,6 +594,145 @@ 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

@pytest.mark.parametrize(
("target_class", "model_name", "variables"),
[
(LiteLLMChatTarget, "openai/gpt-4o", ("LITELLM_API_KEY", "LITELLM_ENDPOINT")),
(ClaudeChatTarget, "claude-sonnet-4-6", ("ANTHROPIC_API_KEY",)),
(LiteLLMDecisionTarget, "openai/gpt-4o", ("LITELLM_API_KEY", "LITELLM_ENDPOINT")),
],
)
def test_copy_keeps_unset_values_unset_when_the_environment_sets_them(
self, *, target_class: type[LiteLLMChatTarget], model_name: str, variables: tuple[str, ...]
) -> None:
with patch.dict("os.environ"):
for variable in variables:
os.environ.pop(variable, None)
source = target_class(model_name=model_name)
with patch.dict("os.environ", dict.fromkeys(variables, "environment-value")):
copy = TargetRegistry().recreate_instance(source=source, params={})
assert (copy._api_key, copy._endpoint) == (None, None)
assert copy.get_identifier().hash == source.get_identifier().hash

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
# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -625,6 +767,12 @@ def test_init_endpoint_from_env(patch_central_database, litellm_stub):
assert t._endpoint == "http://localhost:4000"


def test_init_empty_api_key_and_endpoint_skip_the_environment(patch_central_database, litellm_stub):
with patch.dict("os.environ", {"LITELLM_API_KEY": "sk-env", "LITELLM_ENDPOINT": "http://localhost:4000"}):
t = LiteLLMChatTarget(model_name="openai/gpt-4o", api_key="", endpoint="")
assert (t._api_key, t._endpoint) == (None, None)


def test_drop_params_defaults_to_true_in_body(target):
body = target._construct_request_body(
messages=[{"role": "user", "content": "hi"}], json_config=_disabled_json_config()
Expand Down
Loading