Skip to content
Open
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
42 changes: 38 additions & 4 deletions google/genai/_api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1509,8 +1509,20 @@ def _request_once(
)
response = self._httpx_client.send(httpx_request, stream=stream) # type: ignore[union-attr, arg-type]
errors.APIError.raise_for_response(response)
if stream:
return HttpResponse(response.headers, response)

text = response.text
# Eagerly release memory to prevent unbounded growth (Issue #2369)
if hasattr(response, "close"):
response.close()
if hasattr(response, "_content"):
response._content = b""
if hasattr(response, "_text"):
response._text = ""

return HttpResponse(
response.headers, response if stream else [response.text]
response.headers, [text]
)

def _request(
Expand Down Expand Up @@ -1656,8 +1668,14 @@ async def _async_request_once(
if hasattr(unwrapped_response, '_response'):
unwrapped_response = unwrapped_response._response

text = await unwrapped_response.text()
if hasattr(unwrapped_response, 'release'):
unwrapped_response.release()
if hasattr(unwrapped_response, '_body'):
unwrapped_response._body = None

return HttpResponse(
unwrapped_response.headers, [await unwrapped_response.text()]
unwrapped_response.headers, [text]
)
except (
aiohttp.ClientConnectorError,
Expand Down Expand Up @@ -1690,9 +1708,15 @@ async def _async_request_once(
if hasattr(unwrapped_retry_response, '_response'):
unwrapped_retry_response = unwrapped_retry_response._response

text = await unwrapped_retry_response.text()
if hasattr(unwrapped_retry_response, 'release'):
unwrapped_retry_response.release()
if hasattr(unwrapped_retry_response, '_body'):
unwrapped_retry_response._body = None

return HttpResponse(
unwrapped_retry_response.headers,
[await unwrapped_retry_response.text()],
[text],
)
else:
# aiohttp is not available. Fall back to httpx.
Expand All @@ -1704,7 +1728,17 @@ async def _async_request_once(
timeout=http_request.timeout,
)
await errors.APIError.raise_for_async_response(client_response)
return HttpResponse(client_response.headers, [client_response.text])

text = client_response.text
# Eagerly release memory to prevent unbounded growth (Issue #2369)
if hasattr(client_response, "aclose"):
await client_response.aclose()
if hasattr(client_response, "_content"):
client_response._content = b""
if hasattr(client_response, "_text"):
client_response._text = ""

return HttpResponse(client_response.headers, [text])

async def _async_request(
self,
Expand Down