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
11 changes: 6 additions & 5 deletions google/genai/_api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1910,11 +1910,12 @@ def _websocket_base_url(
# API gateway proxy can use the auth in custom headers, not url.
# Enable custom url if auth is not sufficient.
return http_options.base_url or self.custom_base_url
url_parts = urlparse(http_options.base_url)
url = url_parts._replace(scheme='wss').geturl() # type: ignore[arg-type]
if self._websocket_use_mtls_endpoint:
url = to_mtls_url(url) # type: ignore[arg-type]
return url # type: ignore[return-value]
url_parts = urlparse(http_options.base_url or '')
scheme = {'http': 'ws', 'ws': 'ws'}.get(url_parts.scheme.lower(), 'wss')
url = url_parts._replace(scheme=scheme).geturl()
if self._websocket_use_mtls_endpoint and scheme == 'wss':
url = to_mtls_url(url)
return url

def _access_token(self) -> str:
"""Retrieves the access token for the credentials."""
Expand Down
5 changes: 4 additions & 1 deletion google/genai/live.py
Original file line number Diff line number Diff line change
Expand Up @@ -1164,8 +1164,11 @@ async def connect(
headers = {}
_mcp_utils.set_mcp_usage_header(headers)

ws_kwargs = dict(self._api_client._websocket_ssl_ctx)
if not uri.lower().startswith('wss://'):
ws_kwargs.pop('ssl', None)
async with ws_connect(
uri, additional_headers=headers, **self._api_client._websocket_ssl_ctx
uri, additional_headers=headers, **ws_kwargs
) as ws:
await ws.send(request)
try:
Expand Down
140 changes: 140 additions & 0 deletions google/genai/tests/live/test_live.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,146 @@ def test_websocket_base_url_no_auth_with_http_options():
)


def test_websocket_base_url_maps_http_and_preserves_ws():
from google.auth.credentials import AnonymousCredentials

vertex_client = Client(
vertexai=True,
project='my-project',
location='europe-west4',
credentials=AnonymousCredentials(),
http_options=types.HttpOptions(base_url='http://proxy.internal:8080/vertex'),
)
assert (
vertex_client._api_client._websocket_base_url()
== 'ws://proxy.internal:8080/vertex'
)

ws_client = Client(
vertexai=True,
project='my-project',
location='europe-west4',
credentials=AnonymousCredentials(),
http_options=types.HttpOptions(base_url='ws://proxy.internal:8080/vertex'),
)
assert (
ws_client._api_client._websocket_base_url()
== 'ws://proxy.internal:8080/vertex'
)

https_client = Client(
vertexai=True,
project='my-project',
location='europe-west4',
credentials=AnonymousCredentials(),
http_options=types.HttpOptions(
base_url='https://europe-west4-aiplatform.googleapis.com'
),
)
assert (
https_client._api_client._websocket_base_url()
== 'wss://europe-west4-aiplatform.googleapis.com'
)
https_client._api_client._websocket_use_mtls_endpoint = True
assert (
https_client._api_client._websocket_base_url()
== 'wss://europe-west4-aiplatform.mtls.googleapis.com'
)

ws_mtls_client = Client(
vertexai=True,
project='my-project',
location='europe-west4',
credentials=AnonymousCredentials(),
http_options=types.HttpOptions(
base_url='http://europe-west4-aiplatform.googleapis.com'
),
)
ws_mtls_client._api_client._websocket_use_mtls_endpoint = True
assert (
ws_mtls_client._api_client._websocket_base_url()
== 'ws://europe-west4-aiplatform.googleapis.com'
)

fallback_client = Client(
vertexai=True,
project='my-project',
location='europe-west4',
credentials=AnonymousCredentials(),
http_options=types.HttpOptions(
base_url='ftp://proxy.internal:8080/vertex'
),
)
assert (
fallback_client._api_client._websocket_base_url()
== 'wss://proxy.internal:8080/vertex'
)


@pytest.mark.asyncio
async def test_async_live_connect_ws_omits_ssl_kwarg():
from google.auth.credentials import AnonymousCredentials

captured: dict[str, object] = {}
mock_ws = AsyncMock()
mock_ws.send = AsyncMock()
mock_ws.recv = AsyncMock(
return_value=b'{"setupComplete": {"sessionId": "test_session_id"}}'
)

@contextlib.asynccontextmanager
async def mock_connect(uri, additional_headers=None, **kwargs):
captured['uri'] = uri
captured['kwargs'] = kwargs
yield mock_ws

client = Client(
vertexai=True,
project='my-project',
location='europe-west4',
credentials=AnonymousCredentials(),
http_options=types.HttpOptions(base_url='http://proxy.internal:8080/vertex'),
)
assert 'ssl' in client._api_client._websocket_ssl_ctx

with (
patch.object(
client._api_client,
'_async_access_token',
AsyncMock(return_value='test-token'),
),
patch.object(live, 'ws_connect', new=mock_connect),
):
async with client.aio.live.connect(
model='gemini-2.0-flash',
config={'response_modalities': ['AUDIO']},
):
pass

assert str(captured['uri']).startswith('ws://proxy.internal:8080/vertex/ws/')
assert 'ssl' not in captured['kwargs']

captured.clear()
custom_ws_url = 'ws://127.0.0.1:18080/ws/google.cloud.aiplatform.v1beta1.LlmBidiService/BidiGenerateContent'
custom_client = Client(
vertexai=True,
credentials=AnonymousCredentials(),
http_options=types.HttpOptions(base_url=custom_ws_url),
)
custom_client._api_client.project = None
custom_client._api_client.location = None

with patch.object(live, 'ws_connect', new=mock_connect):
async with custom_client.aio.live.connect(
model='projects/my-project/locations/europe-west4/publishers/google/models/gemini-live',
config={'response_modalities': ['AUDIO']},
):
pass

assert captured['uri'] == custom_ws_url
assert 'ssl' not in captured['kwargs']


@pytest.mark.parametrize('vertexai', [True, False])
@pytest.mark.asyncio
async def test_async_session_send_text(mock_websocket, vertexai):
Expand Down