From 162cdaf1e6f0cddd1a6d2173e0972503ac5fffa0 Mon Sep 17 00:00:00 2001 From: David Montague Date: Tue, 28 Jul 2026 13:36:18 -0600 Subject: [PATCH] perf: defer building model validators until first use google.genai.types defines ~770 models, and importing the package builds a pydantic validator and serializer for every one of them. Any single application uses a small fraction: a client doing text generation never touches the Live, Batch, Tuning or Caching families. Setting defer_build=True on the shared BaseModel builds each model's validator and serializer the first time that model is actually used instead. Measured on Python 3.12 with google-genai 1.72.0, RSS attributable to `import google.genai` drops from 84.1MB to 78.2MB (-7.0%) and import time from 0.73s to 0.57s (-22%), against a one-off cost of ~5ms for the first model used and ~16ms for the first GenerateContentConfig. Steady-state validation throughput is unchanged. --- google/genai/_common.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/google/genai/_common.py b/google/genai/_common.py index f4a6984f7..36e542173 100644 --- a/google/genai/_common.py +++ b/google/genai/_common.py @@ -559,6 +559,10 @@ class BaseModel(pydantic.BaseModel): ser_json_bytes='base64', val_json_bytes='base64', ignored_types=(typing.TypeVar,), + # Most of the ~770 models defined in `types` are never used by any single + # application, so build each model's validator and serializer the first time + # the model is actually used rather than when `google.genai` is imported. + defer_build=True, ) @pydantic.model_validator(mode='before')