Skip to content
Open
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
26 changes: 25 additions & 1 deletion pyrit/prompt_target/common/chat_completions_tool_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"""The bounded local tool loop for targets that speak the Chat Completions wire format."""

import json
import logging
from abc import ABC, abstractmethod
from collections.abc import Callable, Mapping, Sequence
from contextlib import AsyncExitStack
Expand All @@ -27,6 +28,8 @@
from pyrit.prompt_target.common.tool_provider import Tool, ToolProvider, _ScopedToolProvider, collect_tools_async
from pyrit.prompt_target.common.utils import nested_tools

logger = logging.getLogger(__name__)


class _ChatCompletionsToolLoopMixin(ABC):
"""Run a Chat Completions target's configured tools locally, in the shared bounded tool loop."""
Expand Down Expand Up @@ -67,6 +70,15 @@ def _init_tools(
n=n,
extra_body_parameters=extra_body_parameters or {},
)
# The deprecated n argument already warns in the constructor, so only an n that comes from the
# passthrough parameters is logged here.
requested_n = _effective_n(n=None, extra_body_parameters=extra_body_parameters or {})
if n is None and requested_n not in (None, 1):
logger.warning(
f"{type(self).__name__} requests n={requested_n} choices per request through "
"extra_body_parameters, but only the first choice is returned; the others are generated and "
"billed, then discarded. Send once per sample, each in its own conversation, instead."
)
self._direct_tools = list(tools or [])
self._tool_providers = list(tool_providers or [])
self._execute_tools = execute_tools
Expand Down Expand Up @@ -229,6 +241,18 @@ async def _send_completion_async(
"""


def _effective_n(*, n: int | None, extra_body_parameters: Mapping[str, Any]) -> Any:
"""
Return the ``n`` a request sends, after the passthrough parameters and a nested ``extra_body`` override it.

Returns:
Any: The ``n`` value the request sends, or None when it sends none.
"""
nested = extra_body_parameters.get("extra_body")
nested_parameters: Mapping[str, Any] = nested if isinstance(nested, Mapping) else {}
return nested_parameters.get("n", extra_body_parameters.get("n", n))


def _check_tool_settings(
*,
has_tools: bool,
Expand All @@ -253,7 +277,7 @@ def _check_tool_settings(
"Tools in extra_body_parameters['extra_body'] would replace the configured tools. "
"Declare passthrough tools in extra_body_parameters['tools'] instead."
)
effective_n = nested_parameters.get("n", extra_body_parameters.get("n", n))
effective_n = _effective_n(n=n, extra_body_parameters=extra_body_parameters)
if execute_tools and has_tools and effective_n not in (None, 1):
raise ValueError("Automatic tool execution requires n=1.")

Expand Down
10 changes: 9 additions & 1 deletion pyrit/prompt_target/litellm_chat_target.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from typing import Any, ClassVar, NoReturn, cast

from pyrit.auth import ensure_async_token_provider
from pyrit.common import print_deprecation_message
from pyrit.common.constructor_capture import capture_constructor_parameters
from pyrit.exceptions import (
EmptyResponseException,
Expand Down Expand Up @@ -213,7 +214,8 @@ class LiteLLMChatTarget(_ChatCompletionsToolLoopMixin, PromptTarget):
frequency_penalty: Penalize frequently generated tokens; a finite value in [-2, 2], or None.
presence_penalty: Penalize tokens already present in the conversation; a finite value in [-2, 2], or None.
seed: Best-effort deterministic sampling seed.
n: Number of completions to generate.
n: Deprecated, and removed in 1.4.0. Number of completions to generate; only the first is returned.
Send once per sample, each in its own conversation, instead.
stop: Stop sequence(s).
audio_response_config: Optional audio-output configuration (voice + format). When set,
audio modality is enabled on the request (``modalities``/``audio``) for models that
Expand Down Expand Up @@ -330,6 +332,12 @@ def __init__(
if not resolved_model:
raise ValueError("model_name is required. Pass it directly or set the LITELLM_MODEL environment variable.")

if n is not None:
print_deprecation_message(
old_item=f"The n argument of {type(self).__name__}",
new_item="one send per sample, each in its own conversation,",
removed_in="1.4.0",
)
validate_temperature(temperature)
validate_top_p(top_p)
validate_presence_penalty(presence_penalty)
Expand Down
18 changes: 13 additions & 5 deletions pyrit/prompt_target/openai/openai_chat_target.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from openai.types.chat import ChatCompletion

from pyrit.common import forward_init_parameters
from pyrit.common import forward_init_parameters, print_deprecation_message
from pyrit.exceptions import (
EmptyResponseException,
pyrit_target_retry,
Expand Down Expand Up @@ -80,9 +80,9 @@ class OpenAIChatTarget(_ChatCompletionsToolLoopMixin, OpenAITarget):
seed (int): This feature is in Beta. If specified, our system will make a best effort to sample
deterministically, such that repeated requests with the same seed
and parameters should return the same result.
n (int): How many chat completion choices to generate for each input message.
Note that you will be charged based on the number of generated tokens across all
of the choices. Keep n as 1 to minimize costs.
n (int): Deprecated, and removed in 1.4.0. How many chat completion choices to generate for
each input message. You are charged for the tokens of every choice, but only the first is
returned. Send once per sample, each in its own conversation, instead.
extra_body_parameters (dict): Additional parameters to send in the request body
tools (Sequence[Tool]): Executable tools advertised to the model.
tool_providers (Sequence[ToolProvider]): Providers discovered within each send's resource scope.
Expand Down Expand Up @@ -157,7 +157,9 @@ def __init__(
tokens that are already present in the conversation history.
seed (int, Optional): If specified, openAI will make a best effort to sample deterministically,
such that repeated requests with the same seed and parameters should return the same result.
n (int, Optional): The number of completions to generate for each prompt.
n (int, Optional): Deprecated, and removed in 1.4.0. The number of completions to generate
for each prompt; only the first is returned. Send once per sample, each in its own
conversation, instead.
audio_response_config (OpenAIChatAudioConfig, Optional): Configuration for audio output from models
that support it (e.g., gpt-4o-audio-preview). When provided, enables audio modality in responses.
extra_body_parameters (dict, Optional): Additional parameters to be included in the request body.
Expand Down Expand Up @@ -185,6 +187,12 @@ def __init__(
json.JSONDecodeError: If the response from the target is not valid JSON.
Exception: If the request fails for any other reason.
"""
if n is not None:
print_deprecation_message(
old_item=f"The n argument of {type(self).__name__}",
new_item="one send per sample, each in its own conversation,",
removed_in="1.4.0",
)
# Validate generation parameters.
validate_temperature(temperature)
validate_top_p(top_p)
Expand Down
11 changes: 9 additions & 2 deletions pyrit/prompt_target/openai/openai_completion_target.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import logging
from typing import Any, ClassVar

from pyrit.common import forward_init_parameters
from pyrit.common import forward_init_parameters, print_deprecation_message
from pyrit.exceptions import (
pyrit_target_retry,
)
Expand Down Expand Up @@ -73,7 +73,8 @@ def __init__(
frequency_penalty (float, Optional): Number between -2.0 and 2.0. Positive values penalize new
tokens based on their existing frequency in the text so far, decreasing the model's likelihood to
repeat the same line verbatim.
n (int, Optional): How many completions to generate for each prompt.
n (int, Optional): Deprecated, and removed in 1.4.0. How many completions to generate for each
prompt. Send once per sample, each in its own conversation, instead.
custom_configuration (TargetConfiguration, Optional): Override the default configuration for
this target instance. Defaults to None.
**kwargs: Additional keyword arguments passed to the parent OpenAITarget class.
Expand All @@ -84,6 +85,12 @@ def __init__(
Raises:
PyritException: If a generation parameter is out of bounds or a penalty is non-finite.
"""
if n is not None:
print_deprecation_message(
old_item=f"The n argument of {type(self).__name__}",
new_item="one send per sample, each in its own conversation,",
removed_in="1.4.0",
)
# Validate generation parameters.
validate_temperature(temperature)
validate_top_p(top_p)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -292,3 +292,14 @@ def test_boundary_temperature_and_top_p_are_accepted(patch_central_database):

assert target._temperature == 0.0
assert target._top_p == 1.0


@pytest.mark.parametrize("n", [1, 3])
def test_init_warns_that_n_is_deprecated(*, patch_central_database, n: int) -> None:
with pytest.warns(
DeprecationWarning,
match=r"The n argument of OpenAICompletionTarget is deprecated and will be removed in 1\.4\.0",
):
OpenAICompletionTarget(
model_name="gpt-35-turbo", endpoint="https://mock.azure.com/", api_key="mock-api-key", n=n
)
24 changes: 24 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 @@ -5,6 +5,7 @@
import base64
import copy
import json
import logging
import os
import sys
import types
Expand Down Expand Up @@ -2217,3 +2218,26 @@ async def provider() -> str:

def test_is_json_response_supported_reflects_capability(target):
assert target.is_json_response_supported() is True


def test_init_warns_that_n_is_deprecated(*, patch_central_database: Any, litellm_stub: Any) -> None:
with pytest.warns(
DeprecationWarning, match=r"The n argument of LiteLLMChatTarget is deprecated and will be removed in 1\.4\.0"
):
LiteLLMChatTarget(model_name="openai/gpt-4o", n=1)


def test_init_logs_when_passthrough_n_would_discard_choices(
*, caplog: pytest.LogCaptureFixture, patch_central_database: Any, litellm_stub: Any
) -> None:
# Only the first choice is returned, so asking for more generates and bills output nobody sees.
with caplog.at_level(logging.WARNING):
LiteLLMChatTarget(model_name="openai/gpt-4o", extra_body_parameters={"n": 2})
messages = [record.getMessage() for record in caplog.records if "only the first choice" in record.getMessage()]
assert messages == [
(
"LiteLLMChatTarget requests n=2 choices per request through extra_body_parameters, but only the "
"first choice is returned; the others are generated and billed, then discarded. Send once per "
"sample, each in its own conversation, instead."
)
]
63 changes: 63 additions & 0 deletions tests/unit/prompt_target/target/test_openai_chat_target.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import json
import logging
import os
import warnings
from collections.abc import MutableSequence
from tempfile import NamedTemporaryFile
from types import SimpleNamespace
Expand Down Expand Up @@ -2572,3 +2573,65 @@ async def test_construct_message_from_response_token_usage_omits_missing_attrs(
assert piece.prompt_metadata["token_usage_total_tokens"] == 15
assert "token_usage_cached_tokens" not in piece.prompt_metadata
assert "token_usage_reasoning_tokens" not in piece.prompt_metadata


def _make_chat_target(*, n: int | None = None, extra_body_parameters: dict[str, Any] | None = None) -> OpenAIChatTarget:
return OpenAIChatTarget(
model_name="gpt-4o",
endpoint="https://api.openai.com/v1",
api_key="test-key",
n=n,
extra_body_parameters=extra_body_parameters,
)


@pytest.mark.parametrize("n", [1, 3])
def test_init_warns_that_n_is_deprecated(*, patch_central_database: Any, n: int) -> None:
# Passing n at all is deprecated, including n=1, because the argument goes away in 1.4.0.
with pytest.warns(
DeprecationWarning, match=r"The n argument of OpenAIChatTarget is deprecated and will be removed in 1\.4\.0"
):
_make_chat_target(n=n)


def test_init_without_n_does_not_warn(*, caplog: pytest.LogCaptureFixture, patch_central_database: Any) -> None:
with warnings.catch_warnings():
warnings.simplefilter("error", DeprecationWarning)
with caplog.at_level(logging.WARNING):
_make_chat_target()
assert not [record for record in caplog.records if "only the first choice" in record.getMessage()]


@pytest.mark.parametrize(
"extra_body_parameters, logs",
[
({"n": 2}, True),
({"extra_body": {"n": 3}}, True),
({"n": 1}, False),
({"n": 2, "extra_body": {"n": 1}}, False),
],
)
def test_init_logs_when_passthrough_n_would_discard_choices(
*,
caplog: pytest.LogCaptureFixture,
patch_central_database: Any,
extra_body_parameters: dict[str, Any],
logs: bool,
) -> None:
# An n above 1 in extra_body_parameters is not the deprecated argument, but the extra choices
# are still generated, billed and discarded.
with caplog.at_level(logging.WARNING):
_make_chat_target(extra_body_parameters=extra_body_parameters)
messages = [record.getMessage() for record in caplog.records if "only the first choice" in record.getMessage()]
assert bool(messages) is logs
if logs:
assert messages[0].startswith("OpenAIChatTarget requests n=")


def test_init_does_not_log_when_the_n_argument_already_warned(
*, caplog: pytest.LogCaptureFixture, patch_central_database: Any
) -> None:
with pytest.warns(DeprecationWarning, match="The n argument of OpenAIChatTarget"):
with caplog.at_level(logging.WARNING):
_make_chat_target(n=2, extra_body_parameters={"n": 2})
assert not [record for record in caplog.records if "only the first choice" in record.getMessage()]
Loading