GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing github.com — `generate_content` with inline bytes allocates 4.3× the file size to build a 1.33× request body · Issue #3424 · googleapis/python-genai Todo Labels priority: p2Moderately-important priority. Fix may not be included in next release.type: bugError or flaw in code with unintended results or allowing sub-optimal usage patterns. DescriptionThis is a client library issue: memory in the SDK's request serialization. It reproduces without an API call. When a Environment details
Steps to reproduce
The script needs no API key and opens no connection: a mock httpx transport answers in-process. A run takes about one second.
|
| File | Body sent | Peak allocated (tracemalloc) | Peak RSS growth | Allocated until the response, async | Allocated until the response, sync |
|---|---|---|---|---|---|
| 10 MiB | 1.33 | 4.38 | 4.11 | 2.79 | 4.07 |
| 20 MiB | 1.33 | 4.36 | 4.06 | 2.73 | 4.03 |
| 50 MiB | 1.33 | 4.34 | 4.02 | 2.69 | 4.01 |
| 100 MiB | 1.33 | 4.34 | 4.01 | 2.68 | 4.01 |
At 50 MiB the figures are the same, within 0.02, with a Vertex AI client, with generate_content_stream, with a file of zero bytes, on CPython 3.14.4 and on google-genai 2.30.1.
Requests in flight add up. Four 50 MiB requests at once in one process took a peak RSS growth of 12.0 times one file with the async client, and 16.0 times with the sync client in four threads. This matters to a service that sends documents to Gemini as inline bytes, with several requests in one process.
Measured inside one real call for a 50 MiB file, by wrapping each step. "Before" and "after" are what is allocated when the step starts and when it returns.
| Step | Before | Peak | After |
|---|---|---|---|
Part.from_bytes, the pydantic models, the converters, convert_to_dict |
0.00 | 0.01 | 0.01 |
1. encode_unserializable_types |
0.01 | 2.68 | 1.35 |
2. json.dumps(http_request.data) |
1.35 | 4.35 | 2.68 |
3. async: .encode('utf-8') |
2.68 | 4.01 | 2.68 |
3. sync: httpx encodes the str it is given |
2.68 | 4.01 | 4.01 |
The code at v3.6.1 (main at 36e2970 has the same lines):
_common.py#L749: base64.urlsafe_b64encode(value).decode('ascii') makes the base64 bytes and then a str of the same text. The str (1.33×) stays in the request dict for the whole call._api_client.py#L2172 (async) and #L2085-L2089 (sync): json.dumps(http_request.data) copies the base64 text into a JSON str. The overall peak is inside this call..encode('utf-8') on the same line makes the bytes body and the JSON str is freed. Sync: the JSON str goes to httpx as content=data (#L2119-L2125). httpx encodes it, and both the str and the bytes live until the response.Only the body, 1.33×, is needed, and change 3 below shows that it does not have to exist in one piece.
Inline data is a documented path at these sizes: up to 100 MB per request on the Gemini Developer API, 50 MB for PDFs (File input methods), and 256 MB per inline part on Vertex AI (Document understanding). The Files API is not available with a Vertex client (files.py#L595-L598). On Vertex a fileUri must be a Cloud Storage object that is public or in the same project, or a public HTTP URL of at most 15 MiB (API reference). Private data that is not in Cloud Storage has to go inline.
Three changes I tried on 3.6.1, with what each one measured. Each goes further than the one before.
1. Sync path: encode before handing the body to httpx, as the async path already does (the same line twice):
- data = json.dumps(http_request.data) if http_request.data else None + data = json.dumps(http_request.data).encode('utf-8') if http_request.data else None
At 50 MiB, allocated until the response goes from 4.01× to 2.68×. The peak stays at 4.34×. The body is byte-identical, and the SDK's unit tests in common, client, types, transformers and live give the same results with and without the change.
2. Keep the bytes as bytes until the body is built (proof of concept). encode_unserializable_types wraps each bytes value in a marker object instead of making a base64 str, and the client writes the base64 of each marked value straight into the body. At 50 MiB the peak goes from 4.34× to 2.68× (peak RSS growth from 4.02× to 2.69×), and what is allocated until the response to 1.35×. The body has the same SHA-256 as the one 3.6.1 sends, on all five client and transport combinations, with streaming, and with a Vertex client.
It is not a drop-in patch: 27 of the unit tests named above fail with it, because the Live module calls json.dumps on the same dict and test_bytes_internal.py reads the base64 string from the request. A real fix would move those call sites to the same helper, or be made in the generator.
diff --git a/google/genai/_api_client.py b/google/genai/_api_client.py --- a/google/genai/_api_client.py +++ b/google/genai/_api_client.py @@ -2083,9 +2083,9 @@ class BaseApiClient: self._credentials.quota_project_id ) - data = json.dumps(http_request.data) if http_request.data else None + data = _common.dumps_bytes(http_request.data) if http_request.data else None else: if http_request.data: if not isinstance(http_request.data, bytes): - data = json.dumps(http_request.data) if http_request.data else None + data = _common.dumps_bytes(http_request.data) if http_request.data else None else: data = http_request.data @@ -2170,5 +2170,5 @@ class BaseApiClient: if http_request.data: if not isinstance(http_request.data, bytes): - data = json.dumps(http_request.data).encode('utf-8') + data = _common.dumps_bytes(http_request.data) else: data = http_request.data diff --git a/google/genai/_common.py b/google/genai/_common.py --- a/google/genai/_common.py +++ b/google/genai/_common.py @@ -21,4 +21,5 @@ import datetime import enum import functools +import json import logging import re @@ -728,4 +729,44 @@ def timestamped_unique_name() -> str: +class _RawBytes: + """Bytes that `dumps_bytes` base64-encodes straight into the request body.""" + + __slots__ = ('value',) + + def __init__(self, value: bytes) -> None: + self.value = value + + +def dumps_bytes(data: object) -> bytes: + """Returns `json.dumps(data).encode('utf-8')` for the output of `encode_unserializable_types`. + + Each `_RawBytes` value is base64-encoded once, into the body, instead of + going through a `str` and then through `json.dumps`. + """ + blobs: list[bytes] = [] + token = uuid.uuid4().hex + + def default(obj: object) -> str: + if isinstance(obj, _RawBytes): + blobs.append(obj.value) + return f'{token}{len(blobs) - 1}{token}' + raise TypeError( + f'Object of type {type(obj).__name__} is not JSON serializable' + ) + + text = json.dumps(data, default=default) + if not blobs: + return text.encode('utf-8') + pieces = text.split(token) + if len(pieces) != 2 * len(blobs) + 1: + raise ValueError('The placeholder token is not unique in the request.') + # Even pieces are JSON text. Odd pieces are the index of a blob; base64url + # characters need no JSON escaping, so they go between the quotes as is. + return b''.join( + base64.urlsafe_b64encode(blobs[int(piece)]) if i % 2 else piece.encode('utf-8') + for i, piece in enumerate(pieces) + ) + + def encode_unserializable_types(data: dict[str, object]) -> dict[str, object]: """Converts unserializable types in dict to json.dumps() compatible types. @@ -747,5 +788,5 @@ def encode_unserializable_types(data: dict[str, object]) -> dict[str, object]: for key, value in data.items(): if isinstance(value, bytes): - processed_data[key] = base64.urlsafe_b64encode(value).decode('ascii') + processed_data[key] = _RawBytes(value) elif isinstance(value, datetime.datetime): processed_data[key] = value.isoformat() @@ -754,7 +795,5 @@ def encode_unserializable_types(data: dict[str, object]) -> dict[str, object]: elif isinstance(value, list): if all(isinstance(v, bytes) for v in value): - processed_data[key] = [ - base64.urlsafe_b64encode(v).decode('ascii') for v in value - ] + processed_data[key] = [_RawBytes(v) for v in value] if all(isinstance(v, datetime.datetime) for v in value): processed_data[key] = [v.isoformat() for v in value]
3. The same, and send the body in chunks (proof of concept). Change 2 still builds the whole body. Here the client gives httpx or aiohttp an iterable instead. It yields the JSON text around each file, and the base64 of the file 768 KiB at a time. The length of the body is known before any base64 is made, so the client sets Content-Length and the request is not sent with chunked transfer encoding. A full copy of the body never exists.
The memory on top of the file no longer depends on the file's size. In MiB, medians over the same five client and transport combinations, 3 runs each, against the same local server:
| File | Peak allocated, 3.6.1 | Peak allocated, chunks | Process peak RSS, 3.6.1 | Process peak RSS, chunks |
|---|---|---|---|---|
| 10 MiB | 44 | 3.6 | 117 | 81 |
| 20 MiB | 87 | 3.6 | 167 | 91 |
| 50 MiB | 217 | 3.6 | 317 | 121 |
| 100 MiB | 434 | 3.6 | 567 | 171 |
| 256 MiB | 1,110 | 3.6 | 1,347 | 327 |
The process peak RSS includes the interpreter, the imports and the file. The 256 MiB row is async with aiohttp and sync with httpx2 only. Over all runs the peak allocated is 3.6 to 4.5 MiB and the peak RSS growth is 4.1 to 5.4 MiB. While the request waits for the response, 0.6 to 1.5 MiB is allocated. With four 50 MiB requests at once the process peaks at 271 MiB RSS with the async client and 278 MiB with four threads; on 3.6.1 it peaks at 867 MiB and 1,068 MiB.
The server received the same bytes. The SHA-256 of the body equals the one 3.6.1 sends, on all five combinations, with streaming, and with a Vertex client. In all 159 single-request runs the request arrived with a Content-Length and without chunked transfer encoding. The call was also shorter: at 100 MiB about 0.25 s instead of about 0.78 s, not counting the one second the server waits before it answers (plain HTTP on the loopback).
Limits of this one:
requests transport that a Vertex client uses with a client certificate. It gets the same object as data=.--- a/google/genai/_api_client.py +++ b/google/genai/_api_client.py @@ -2074,7 +2074,7 @@ http_request: HttpRequest, stream: bool = False, ) -> HttpResponse: - data: Optional[Union[str, bytes]] = None + data: Any = None # If using proj/location, fetch ADC if self.vertexai and (self.project or self.location) and not self.api_key: http_request.headers['Authorization'] = f'Bearer {self._access_token()}' @@ -2082,13 +2082,16 @@ http_request.headers['x-goog-user-project'] = ( self._credentials.quota_project_id ) - data = json.dumps(http_request.data) if http_request.data else None + data = _common.dumps_body(http_request.data) if http_request.data else None else: if http_request.data: if not isinstance(http_request.data, bytes): - data = json.dumps(http_request.data) if http_request.data else None + data = _common.dumps_body(http_request.data) if http_request.data else None else: data = http_request.data + if isinstance(data, _common._ChunkedBody): + # The length is known, so the body is not sent with chunked encoding. + http_request.headers['Content-Length'] = str(data.content_length) if self._use_google_auth_sync(): url = str(http_request.url) @@ -2156,7 +2159,7 @@ *, implicit_retry: bool = True, ) -> HttpResponse: - data: Optional[bytes] = None + data: Any = None # If using proj/location, fetch ADC if self.vertexai and (self.project or self.location) and not self.api_key: @@ -2169,7 +2172,11 @@ ) if http_request.data: if not isinstance(http_request.data, bytes): - data = json.dumps(http_request.data).encode('utf-8') + data = _common.dumps_body(http_request.data) + if isinstance(data, _common._ChunkedBody): + # The length is known, so the body is not sent with chunked encoding. + http_request.headers['Content-Length'] = str(data.content_length) + data = _common._AsyncChunkedBody(data) else: data = http_request.data --- a/google/genai/_common.py +++ b/google/genai/_common.py @@ -16,10 +16,12 @@ """Common utilities for the SDK.""" import base64 +import binascii import collections.abc import datetime import enum import functools +import json import logging import re import sys @@ -727,6 +729,91 @@ return f'{timestamp}_{unique_id}' +class _RawBytes: + """Bytes that `dumps_bytes` base64-encodes straight into the request body.""" + + __slots__ = ('value',) + + def __init__(self, value: bytes) -> None: + self.value = value + + +# Raw bytes per base64 chunk. A multiple of 3, so the chunks join without padding. +_BASE64_CHUNK = 3 * 256 * 1024 +_URLSAFE = bytes.maketrans(b'+/', b'-_') + + +class _ChunkedBody: + """A JSON request body that is produced in chunks. + + The JSON text around each `_RawBytes` value is kept as small `bytes` pieces. + The base64 of each value is made a chunk at a time, while the body is sent, + so a full copy of the body never exists. + """ + + def __init__(self, pieces: list[Union[bytes, '_RawBytes']]) -> None: + self._pieces = pieces + self.content_length = sum( + len(piece) if isinstance(piece, bytes) else 4 * ((len(piece.value) + 2) // 3) + for piece in pieces + ) + + def __iter__(self) -> collections.abc.Iterator[bytes]: + for piece in self._pieces: + if isinstance(piece, bytes): + yield piece + continue + view = memoryview(piece.value) + for start in range(0, len(view), _BASE64_CHUNK): + yield binascii.b2a_base64( + view[start : start + _BASE64_CHUNK], newline=False + ).translate(_URLSAFE) + + +class _AsyncChunkedBody: + """The same body for an async HTTP client.""" + + def __init__(self, body: _ChunkedBody) -> None: + self._body = body + self.content_length = body.content_length + + async def __aiter__(self) -> collections.abc.AsyncIterator[bytes]: + for chunk in self._body: + yield chunk + + +def dumps_body(data: object) -> Union[bytes, _ChunkedBody]: + """Returns the JSON body for the output of `encode_unserializable_types`. + + Plain `bytes` when the request holds no `_RawBytes`; otherwise a + `_ChunkedBody` whose bytes are the same as + `json.dumps(data).encode('utf-8')` would give with base64 strings. + """ + blobs: list[_RawBytes] = [] + token = uuid.uuid4().hex + + def default(obj: object) -> str: + if isinstance(obj, _RawBytes): + blobs.append(obj) + return f'{token}{len(blobs) - 1}{token}' + raise TypeError( + f'Object of type {type(obj).__name__} is not JSON serializable' + ) + + text = json.dumps(data, default=default) + if not blobs: + return text.encode('utf-8') + pieces = text.split(token) + if len(pieces) != 2 * len(blobs) + 1: + raise ValueError('The placeholder token is not unique in the request.') + # Even pieces are JSON text. Odd pieces are the index of a blob; base64url + # characters need no JSON escaping, so they go between the quotes as is. + return _ChunkedBody([ + blobs[int(piece)] if i % 2 else piece.encode('utf-8') + for i, piece in enumerate(pieces) + ]) + + def encode_unserializable_types(data: dict[str, object]) -> dict[str, object]: """Converts unserializable types in dict to json.dumps() compatible types. @@ -746,16 +833,14 @@ return data for key, value in data.items(): if isinstance(value, bytes): - processed_data[key] = base64.urlsafe_b64encode(value).decode('ascii') + processed_data[key] = _RawBytes(value) elif isinstance(value, datetime.datetime): processed_data[key] = value.isoformat() elif isinstance(value, dict): processed_data[key] = encode_unserializable_types(value) elif isinstance(value, list): if all(isinstance(v, bytes) for v in value): - processed_data[key] = [ - base64.urlsafe_b64encode(v).decode('ascii') for v in value - ] + processed_data[key] = [_RawBytes(v) for v in value] if all(isinstance(v, datetime.datetime) for v in value): processed_data[key] = [v.isoformat() for v in value] else:
_interactions layer. It does not touch generate_content.Hi @ascillitoe,
Thank you for providing minimal reproduction & details!
We have successfully reproduced this exact behavior locally (4.33x peak allocated on top of the file, with 2.67x async and 4.00x sync held until the response for a 1.33x request body) and also verified the _ChunkedBody proof of concept (3.00 MiB peak with a byte-for-byte identical SHA-256 payload).
We have escalated this internally to our engineering team to review the serialization fixes.
Thanks
No worries @Venkaiahbabuneelam, happy to help, thanks for the quick reply!