From 0e5a2768a080b12b21c4da8c5802d5c5a13442fa Mon Sep 17 00:00:00 2001 From: salah9003 Date: Sun, 17 Aug 2025 16:40:47 +0300 Subject: [PATCH] fix: pydantic v2.11+ compatibility in BaseModel Replace deprecated populate_by_name with validate_by_name/validate_by_alias Add version detection for backward compatibility with Pydantic v1 Fixes SchemaError when importing google.genai with Pydantic v2.11+ --- google/genai/_common.py | 43 +++++++++++++++++++++++++++++------------ 1 file changed, 31 insertions(+), 12 deletions(-) diff --git a/google/genai/_common.py b/google/genai/_common.py index c8926df5f..601a5b40a 100644 --- a/google/genai/_common.py +++ b/google/genai/_common.py @@ -412,18 +412,37 @@ def _format_collection( class BaseModel(pydantic.BaseModel): - model_config = pydantic.ConfigDict( - alias_generator=alias_generators.to_camel, - populate_by_name=True, - from_attributes=True, - protected_namespaces=(), - extra='forbid', - # This allows us to use arbitrary types in the model. E.g. PIL.Image. - arbitrary_types_allowed=True, - ser_json_bytes='base64', - val_json_bytes='base64', - ignored_types=(typing.TypeVar,) - ) + # Check Pydantic version for compatibility + _pydantic_v2 = hasattr(pydantic, '__version__') and pydantic.__version__.startswith('2.') + + if _pydantic_v2: + # Pydantic v2: use validate_by_name and validate_by_alias instead of populate_by_name + model_config = pydantic.ConfigDict( + alias_generator=alias_generators.to_camel, + validate_by_name=True, + validate_by_alias=True, + from_attributes=True, + protected_namespaces=(), + extra='forbid', + # This allows us to use arbitrary types in the model. E.g. PIL.Image. + arbitrary_types_allowed=True, + ser_json_bytes='base64', + val_json_bytes='base64', + ) + else: + # Pydantic v1: keep using populate_by_name + model_config = pydantic.ConfigDict( + alias_generator=alias_generators.to_camel, + populate_by_name=True, + from_attributes=True, + protected_namespaces=(), + extra='forbid', + # This allows us to use arbitrary types in the model. E.g. PIL.Image. + arbitrary_types_allowed=True, + ser_json_bytes='base64', + val_json_bytes='base64', + ignored_types=(typing.TypeVar,) + ) def __repr__(self) -> str: try: