Skip to content

Commit a8eecfa

Browse files
shawn-yang-googlecopybara-github
authored andcommitted
fix: forward reference resolution in Pydantic schema generation.
FUTURE_COPYBARA_INTEGRATE_REVIEW=#6099 from googleapis:release-please--branches--main 4597d87 PiperOrigin-RevId: 829577742
1 parent ed53c69 commit a8eecfa

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

vertexai/_genai/_agent_engines_utils.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -590,6 +590,11 @@ def _is_pydantic_serializable(param: inspect.Parameter) -> bool:
590590
if param.annotation == inspect.Parameter.empty:
591591
return True
592592

593+
# Forward references can't be resolved by Pydantic if the type is not
594+
# available at runtime (e.g. inside `if TYPE_CHECKING:`).
595+
if "ForwardRef" in repr(param.annotation):
596+
return False
597+
593598
if isinstance(param.annotation, str):
594599
return False
595600

@@ -664,7 +669,17 @@ def _generate_schema(
664669
# it is not JSON serializable. We hence exclude it from the schema.
665670
and param.annotation != asyncio.Queue and _is_pydantic_serializable(param)
666671
}
667-
parameters = pydantic.create_model(f.__name__, **fields_dict).schema()
672+
model = pydantic.create_model(f.__name__, **fields_dict)
673+
# Pydantic v2 may not be able to resolve forward references if the
674+
# types are not in the same module. We need to explicitly call
675+
# `model_rebuild` with the correct namespace from the function's module.
676+
# See https://errors.pydantic.dev/2/u/class-not-fully-defined
677+
f_module = inspect.getmodule(f)
678+
if f_module:
679+
model.model_rebuild(
680+
_types_namespace=f_module.__dict__,
681+
)
682+
parameters = model.schema()
668683
# Postprocessing
669684
# 4. Suppress unnecessary title generation:
670685
# * https://github.com/pydantic/pydantic/issues/1051

0 commit comments

Comments
 (0)