GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

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

generate_content with inline bytes allocates 4.3× the file size to build a 1.33× request body #3424

New issue
Copy link
New issue
Copy link
Todo
Todo
generate_content with inline bytes allocates 4.3× the file size to build a 1.33× request body#3424
Copy link
Assignees
Venkaiahbabuneelam
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.

Description

@ascillitoe
ascillitoe
opened on Nov 26, 2026
Issue body actions

This is a client library issue: memory in the SDK's request serialization. It reproduces without an API call.

When a generate_content request carries a large inline file (types.Part.from_bytes), the SDK allocates about 4.3 times the file's size, on top of the file, while it builds the request body. About 2.7 times (async client) or 4.0 times (sync client) then stays allocated until the response arrives. The body that is sent is 1.33 times the file (base64). The rest is intermediate copies.

Environment details

  • Programming language: Python
  • OS: Linux x86_64 (Ubuntu 26.04)
  • Language runtime version: CPython 3.12.9 (also checked on 3.14.4)
  • Package version: google-genai 3.6.1 (also checked on 2.30.1), with httpx2 2.16.2, httpx 0.29.0, aiohttp 3.14.5, pydantic 2.14.4

Steps to reproduce

  1. In a fresh virtual environment: pip install google-genai==3.6.1
  2. Save the script below as repro.py.
  3. Run python repro.py 50 async and python repro.py 50 sync. The first argument is the file size in MiB.

The script needs no API key and opens no connection: a mock httpx transport answers in-process. A run takes about one second.

repro.py
"""Memory while google-genai sends one generate_content request that holds an inline file.

No network and no API key: a mock httpx transport, passed through the public
HttpOptions.client_args, answers in-process.

    python repro.py [MiB] [async|sync]
"""
import asyncio
import os
import sys
import tracemalloc

try:
    import httpx2 as httpx  # google-genai 3.x
except ImportError:
    import httpx  # google-genai 2.x

from google import genai
from google.genai import types

MIB = int(sys.argv[1]) if len(sys.argv) > 1 else 50
MODE = sys.argv[2] if len(sys.argv) > 2 else 'async'
SIZE = MIB * 2**20
seen = {}


def status_kib(field):  # Linux only
    try:
        with open('/proc/self/status') as f:
            return next(int(line.split()[1]) for line in f if line.startswith(field + ':'))
    except OSError:
        return 0


def answer(request):
    # Called when the SDK hands the finished body to the HTTP client.
    seen['body'] = len(request.content)
    seen['held'] = tracemalloc.get_traced_memory()[0]  # stays allocated until the response is back
    reply = {'candidates': [{'content': {'role': 'model', 'parts': [{'text': 'ok'}]}}]}
    return httpx.Response(200, json=reply)


async def async_answer(request):
    return answer(request)


client = genai.Client(
    api_key='not-a-key',
    http_options=types.HttpOptions(
        client_args={'transport': httpx.MockTransport(answer)},
        async_client_args={'transport': httpx.MockTransport(async_answer)},
    ),
)

data = os.urandom(SIZE)  # the file: allocated before measuring starts, so it is not counted
contents = [types.Part.from_bytes(data=data, mime_type='application/pdf'), 'Summarise this.']

rss_before = status_kib('VmRSS')
tracemalloc.start()
if MODE == 'async':
    asyncio.run(client.aio.models.generate_content(model='gemini-2.5-flash', contents=contents))
else:
    client.models.generate_content(model='gemini-2.5-flash', contents=contents)
peak = tracemalloc.get_traced_memory()[1]
tracemalloc.stop()
rss_peak = status_kib('VmHWM')

print(f'google-genai {genai.__version__}, {httpx.__name__} {httpx.__version__}, '
      f'Python {sys.version.split()[0]}, {MODE}, file {MIB} MiB')
print(f'request body:                           {seen["body"] / SIZE:.2f} x file')
print(f'peak allocated (tracemalloc):           {peak / SIZE:.2f} x file, on top of the file')
print(f'allocated when the body is handed over: {seen["held"] / SIZE:.2f} x file, on top of the file')
if rss_before:
    print(f'peak RSS growth during the call:        {(rss_peak - rss_before) * 1024 / SIZE:.2f} x file')

Output:

google-genai 3.6.1, httpx2 2.16.2, Python 3.12.9, async, file 50 MiB
request body:                           1.33 x file
peak allocated (tracemalloc):           4.34 x file, on top of the file
allocated when the body is handed over: 2.68 x file, on top of the file
peak RSS growth during the call:        4.04 x file

google-genai 3.6.1, httpx2 2.16.2, Python 3.12.9, sync, file 50 MiB
request body:                           1.33 x file
peak allocated (tracemalloc):           4.34 x file, on top of the file
allocated when the body is handed over: 4.01 x file, on top of the file
peak RSS growth during the call:        4.04 x file

Measurements

Multiples of the file's size, not counting the file itself. Each figure is the median over 3 runs for each client and transport, pooled (async with aiohttp, httpx2 and httpx; sync with httpx2 and httpx). Every run is a fresh process that sends to a local server, which discards the body. Every run is within 0.06 of its median.

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.

Where the copies are made

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):

  1. _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.
  2. _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.
  3. Async: .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.

Why not the Files API or a URL

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.

Suggested fix

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.

Proof-of-concept diff against v3.6.1
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:

  • The same 27 unit tests fail as with change 2, for the same reason.
  • Every measurement is against a local plain-HTTP server. I did not test TLS, a proxy, a retry, a redirect, or the real API.
  • I did not test the requests transport that a Vertex client uses with a client certificate. It gets the same object as data=.
  • A transport that reads the whole request joins the chunks again. The mock transport in the script above does, so with this change the script prints 2.68×, not the figures in this table.
Chunked-body diff against v3.6.1 (includes the marker from change 2)
--- 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:

Related

  • model_dump() in _generate_content_stream serializes full image contents per response (~32 MB wasted) #2235 (closed, fixed in a695bbd): a copy of the inline data made for every response. The same kind of cost, on the response side.
  • fix: prevent OOM by using file handles and chunked base64 encoding #1951 (open pull request): chunked base64 for file inputs in the _interactions layer. It does not touch generate_content.

Activity

  1. ascillitoe
    added
    type: bugError or flaw in code with unintended results or allowing sub-optimal usage patterns.
    priority: p2Moderately-important priority. Fix may not be included in next release.
    on Nov 26, 2026
  2. Venkaiahbabuneelam
    self-assigned this
    on Nov 27, 2026
  3. Venkaiahbabuneelam commented on Nov 27, 2026

    @Venkaiahbabuneelam
    Venkaiahbabuneelam
    on Nov 27, 2026
    More actions

    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

  4. ascillitoe commented on Nov 27, 2026

    @ascillitoe
    ascillitoe
    on Nov 27, 2026
    Author
    More actions

    No worries @Venkaiahbabuneelam, happy to help, thanks for the quick reply!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

  • @Venkaiahbabuneelam
    Venkaiahbabuneelam

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.

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

    You are visitor 01402775 — GeezerVison does not store the pages you look up.
    Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.