Skip to content

Commit 0e5a276

Browse files
committed
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+
1 parent 0101d47 commit 0e5a276

File tree

1 file changed

+31
-12
lines changed

1 file changed

+31
-12
lines changed

google/genai/_common.py

Lines changed: 31 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -412,18 +412,37 @@ def _format_collection(
412412

413413
class BaseModel(pydantic.BaseModel):
414414

415-
model_config = pydantic.ConfigDict(
416-
alias_generator=alias_generators.to_camel,
417-
populate_by_name=True,
418-
from_attributes=True,
419-
protected_namespaces=(),
420-
extra='forbid',
421-
# This allows us to use arbitrary types in the model. E.g. PIL.Image.
422-
arbitrary_types_allowed=True,
423-
ser_json_bytes='base64',
424-
val_json_bytes='base64',
425-
ignored_types=(typing.TypeVar,)
426-
)
415+
# Check Pydantic version for compatibility
416+
_pydantic_v2 = hasattr(pydantic, '__version__') and pydantic.__version__.startswith('2.')
417+
418+
if _pydantic_v2:
419+
# Pydantic v2: use validate_by_name and validate_by_alias instead of populate_by_name
420+
model_config = pydantic.ConfigDict(
421+
alias_generator=alias_generators.to_camel,
422+
validate_by_name=True,
423+
validate_by_alias=True,
424+
from_attributes=True,
425+
protected_namespaces=(),
426+
extra='forbid',
427+
# This allows us to use arbitrary types in the model. E.g. PIL.Image.
428+
arbitrary_types_allowed=True,
429+
ser_json_bytes='base64',
430+
val_json_bytes='base64',
431+
)
432+
else:
433+
# Pydantic v1: keep using populate_by_name
434+
model_config = pydantic.ConfigDict(
435+
alias_generator=alias_generators.to_camel,
436+
populate_by_name=True,
437+
from_attributes=True,
438+
protected_namespaces=(),
439+
extra='forbid',
440+
# This allows us to use arbitrary types in the model. E.g. PIL.Image.
441+
arbitrary_types_allowed=True,
442+
ser_json_bytes='base64',
443+
val_json_bytes='base64',
444+
ignored_types=(typing.TypeVar,)
445+
)
427446

428447
def __repr__(self) -> str:
429448
try:

0 commit comments

Comments
 (0)