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
44 changes: 35 additions & 9 deletions pyrit/prompt_target/openai/openai_realtime_target.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,35 @@
RealTimeVoice = Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse", "marin", "cedar"]


def _url_scheme(url: str) -> str:
"""
Return the lowercased scheme of ``url`` (URL schemes are case-insensitive, RFC 3986 section 3.1).

Args:
url: The URL to inspect.

Returns:
str: The scheme in lowercase, or an empty string when ``url`` has none.
"""
scheme, separator, _ = url.partition("://")
return scheme.lower() if separator else ""


def _to_websocket_url(url: str) -> str:
"""
Rewrite an ``https`` or ``wss`` URL, in any letter case, to start with ``wss://``.

Args:
url: The endpoint URL.

Returns:
str: ``url`` with a ``wss://`` scheme, or ``url`` unchanged for any other scheme.
"""
if _url_scheme(url) in ("https", "wss"):
return "wss://" + url.partition("://")[2]
return url


@dataclass
class _RealtimeReceiveState:
"""
Expand Down Expand Up @@ -285,7 +314,7 @@ def _validate_url_for_target(self, endpoint_url: str) -> None:
endpoint_url: The endpoint URL to validate.
"""
# Convert https to wss for validation (this is expected for websockets)
check_url = endpoint_url.replace("https://", "wss://") if endpoint_url.startswith("https://") else endpoint_url
check_url = _to_websocket_url(endpoint_url)

# Check for proper scheme
if not check_url.startswith("wss://"):
Expand All @@ -312,7 +341,7 @@ def _warn_if_irregular_realtime_endpoint(self, endpoint: str) -> None:
# Also accept https:// versions that will be converted to wss://

# Check for proper scheme (wss:// or https://)
if not endpoint.startswith(("wss://", "https://")):
if _url_scheme(endpoint) not in ("wss", "https"):
logger.warning(
f"Realtime endpoint should start with 'wss://' or 'https://', got: {endpoint}. "
"This may cause connection issues."
Expand All @@ -322,11 +351,12 @@ def _warn_if_irregular_realtime_endpoint(self, endpoint: str) -> None:
# Pattern for Azure endpoints
azure_pattern = re.compile(
r"^(wss|https)://[a-zA-Z0-9\-]+\.openai\.azure\.com/"
r"(openai/(deployments/[^/]+/)?realtime(\?api-version=[^/]+)?|openai/v1|v1)$"
r"(openai/(deployments/[^/]+/)?realtime(\?api-version=[^/]+)?|openai/v1|v1)$",
re.IGNORECASE,
)

# Pattern for Platform OpenAI
platform_pattern = re.compile(r"^(wss|https)://api\.openai\.com/(v1(/realtime)?|realtime)$")
platform_pattern = re.compile(r"^(wss|https)://api\.openai\.com/(v1(/realtime)?|realtime)$", re.IGNORECASE)

if not azure_pattern.match(endpoint) and not platform_pattern.match(endpoint):
logger.warning(
Expand All @@ -344,11 +374,7 @@ def _get_openai_client(self) -> AsyncOpenAI:
"""
if self._realtime_client is None:
# Convert https:// to wss:// for websocket connections if needed
websocket_base_url = (
self._endpoint.replace("https://", "wss://")
if self._endpoint.startswith("https://")
else self._endpoint
)
websocket_base_url = _to_websocket_url(self._endpoint)

logger.info(f"Creating realtime client with websocket_base_url: {websocket_base_url}")

Expand Down
34 changes: 34 additions & 0 deletions tests/unit/prompt_target/target/test_realtime_target.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import asyncio
import base64
import gc
import logging
import wave
from collections.abc import AsyncIterator
from typing import Any, cast
Expand Down Expand Up @@ -1792,3 +1793,36 @@ async def test_cleanup_target_async_swallows_connection_and_client_errors(target
mock_client.close.assert_awaited_once()
assert target._existing_conversation == {}
assert target._realtime_client is None


@pytest.mark.parametrize(
("endpoint", "expected_websocket_url"),
[
("https://res.openai.azure.com/openai/v1", "wss://res.openai.azure.com/openai/v1"),
("HTTPS://res.openai.azure.com/openai/v1", "wss://res.openai.azure.com/openai/v1"),
("Https://api.openai.com/v1", "wss://api.openai.com/v1"),
("WSS://res.openai.azure.com/openai/v1", "wss://res.openai.azure.com/openai/v1"),
],
)
@patch.dict("os.environ", _CLEAN_UNDERLYING_MODEL_ENV)
def test_https_endpoint_scheme_is_converted_to_wss_in_any_case(
sqlite_instance, caplog: pytest.LogCaptureFixture, *, endpoint: str, expected_websocket_url: str
) -> None:
with caplog.at_level(logging.WARNING, logger="pyrit.prompt_target.openai.openai_realtime_target"):
target = RealtimeTarget(api_key="test_key", endpoint=endpoint, model_name="test")

assert str(target._get_openai_client().websocket_base_url) == expected_websocket_url
assert not [r for r in caplog.records if "scheme" in r.getMessage()]


@pytest.mark.parametrize(
"endpoint",
["HTTPS://res.openai.azure.com/openai/v1", "WSS://api.openai.com/v1"],
)
def test_irregular_endpoint_warning_ignores_scheme_case(
target, caplog: pytest.LogCaptureFixture, *, endpoint: str
) -> None:
with caplog.at_level(logging.WARNING, logger="pyrit.prompt_target.openai.openai_realtime_target"):
target._warn_if_irregular_realtime_endpoint(endpoint)

assert not caplog.records
Loading