Skip to content

Commit 150a8e7

Browse files
vertex-sdk-botcopybara-github
authored andcommitted
fix: resolve AttributeError by supporting both Pydantic and Protobuf AgentCard serialization
PiperOrigin-RevId: 930002178
1 parent 14a2265 commit 150a8e7

5 files changed

Lines changed: 371 additions & 14 deletions

File tree

setup.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,7 @@
280280
"mock",
281281
"pytest-xdist",
282282
"Pillow",
283+
"a2a-sdk >= 1.0.0",
283284
"scikit-learn<1.6.0; python_version<='3.10'",
284285
"scikit-learn; python_version>'3.10'",
285286
# Lazy import requires > 2.12.0
Lines changed: 300 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,300 @@
1+
# Copyright 2026 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
#
15+
16+
import os
17+
import sys
18+
import tempfile
19+
from unittest import mock
20+
import pytest
21+
import cloudpickle
22+
import pydantic
23+
24+
from google import auth
25+
from google.api_core import operation as ga_operation
26+
from google.auth import credentials as auth_credentials
27+
from google.cloud import storage
28+
from google.cloud import aiplatform
29+
from google.cloud.aiplatform import base
30+
31+
from google.cloud.aiplatform_v1 import types
32+
from google.cloud.aiplatform_v1.services import reasoning_engine_service
33+
from vertexai import agent_engines
34+
from vertexai.agent_engines import _agent_engines
35+
from vertexai.agent_engines import _utils
36+
from google.protobuf import struct_pb2
37+
from a2a.compat.v0_3 import a2a_v0_3_pb2 as a2a_pb2
38+
39+
40+
class CapitalizeEngine:
41+
"""A sample Agent Engine."""
42+
43+
def query(self, unused_arbitrary_string_name: str) -> str:
44+
"""Runs the engine."""
45+
return unused_arbitrary_string_name.upper()
46+
47+
48+
class CapitalizeEngineWithCard(CapitalizeEngine):
49+
50+
def __init__(self, card):
51+
self.agent_card = card
52+
53+
def __getstate__(self):
54+
state = self.__dict__.copy()
55+
if hasattr(self.agent_card, "DESCRIPTOR"):
56+
state["agent_card"] = None
57+
return state
58+
59+
def __setstate__(self, state):
60+
self.__dict__.update(state)
61+
62+
63+
class DummyPydanticCard(pydantic.BaseModel):
64+
name: str = "test_pydantic_card"
65+
66+
67+
def _create_empty_fake_package(package_name: str) -> str:
68+
temp_dir = tempfile.mkdtemp()
69+
package_dir = os.path.join(temp_dir, package_name)
70+
os.makedirs(package_dir)
71+
init_path = os.path.join(package_dir, "__init__.py")
72+
open(init_path, "w").close()
73+
return temp_dir
74+
75+
76+
_TEST_CREDENTIALS = mock.Mock(spec=auth_credentials.AnonymousCredentials())
77+
_TEST_STAGING_BUCKET = "gs://test-bucket"
78+
_TEST_LOCATION = "us-central1"
79+
_TEST_PROJECT = "test-project"
80+
_TEST_RESOURCE_ID = "1028944691210842416"
81+
_TEST_PARENT = f"projects/{_TEST_PROJECT}/locations/{_TEST_LOCATION}"
82+
_TEST_AGENT_ENGINE_RESOURCE_NAME = (
83+
f"{_TEST_PARENT}/reasoningEngines/{_TEST_RESOURCE_ID}"
84+
)
85+
_TEST_AGENT_ENGINE_DISPLAY_NAME = "Agent Engine Display Name"
86+
_TEST_GCS_DIR_NAME = _agent_engines._DEFAULT_GCS_DIR_NAME
87+
_TEST_BLOB_FILENAME = _agent_engines._BLOB_FILENAME
88+
_TEST_REQUIREMENTS_FILE = _agent_engines._REQUIREMENTS_FILE
89+
_TEST_EXTRA_PACKAGES_FILE = _agent_engines._EXTRA_PACKAGES_FILE
90+
_TEST_STANDARD_API_MODE = _agent_engines._STANDARD_API_MODE
91+
_TEST_DEFAULT_METHOD_NAME = _agent_engines._DEFAULT_METHOD_NAME
92+
_TEST_MODE_KEY_IN_SCHEMA = _agent_engines._MODE_KEY_IN_SCHEMA
93+
94+
_TEST_AGENT_ENGINE_EXTRA_PACKAGE = "fake.py"
95+
96+
_TEST_AGENT_ENGINE_EXTRA_PACKAGE_PATH = _create_empty_fake_package(
97+
_TEST_AGENT_ENGINE_EXTRA_PACKAGE
98+
)
99+
100+
_TEST_AGENT_ENGINE_REQUIREMENTS = [
101+
"google-cloud-aiplatform==1.29.0",
102+
"langchain",
103+
]
104+
105+
_TEST_AGENT_ENGINE_GCS_URI = "{}/{}/{}".format(
106+
_TEST_STAGING_BUCKET,
107+
_TEST_GCS_DIR_NAME,
108+
_TEST_BLOB_FILENAME,
109+
)
110+
_TEST_AGENT_ENGINE_DEPENDENCY_FILES_GCS_URI = "{}/{}/{}".format(
111+
_TEST_STAGING_BUCKET,
112+
_TEST_GCS_DIR_NAME,
113+
_TEST_EXTRA_PACKAGES_FILE,
114+
)
115+
_TEST_AGENT_ENGINE_REQUIREMENTS_GCS_URI = "{}/{}/{}".format(
116+
_TEST_STAGING_BUCKET,
117+
_TEST_GCS_DIR_NAME,
118+
_TEST_REQUIREMENTS_FILE,
119+
)
120+
121+
_TEST_AGENT_ENGINE_QUERY_SCHEMA = _utils.to_proto(
122+
_utils.generate_schema(
123+
CapitalizeEngine().query,
124+
schema_name=_TEST_DEFAULT_METHOD_NAME,
125+
)
126+
)
127+
_TEST_AGENT_ENGINE_QUERY_SCHEMA[_TEST_MODE_KEY_IN_SCHEMA] = _TEST_STANDARD_API_MODE
128+
129+
_TEST_AGENT_ENGINE_PACKAGE_SPEC = types.ReasoningEngineSpec.PackageSpec(
130+
python_version=f"{sys.version_info.major}.{sys.version_info.minor}",
131+
pickle_object_gcs_uri=_TEST_AGENT_ENGINE_GCS_URI,
132+
dependency_files_gcs_uri=_TEST_AGENT_ENGINE_DEPENDENCY_FILES_GCS_URI,
133+
requirements_gcs_uri=_TEST_AGENT_ENGINE_REQUIREMENTS_GCS_URI,
134+
)
135+
136+
_TEST_AGENT_ENGINE_OBJ = types.ReasoningEngine(
137+
name=_TEST_AGENT_ENGINE_RESOURCE_NAME,
138+
spec=types.ReasoningEngineSpec(
139+
package_spec=_TEST_AGENT_ENGINE_PACKAGE_SPEC,
140+
agent_framework=_agent_engines._DEFAULT_AGENT_FRAMEWORK,
141+
),
142+
)
143+
_TEST_AGENT_ENGINE_OBJ.spec.class_methods.append(_TEST_AGENT_ENGINE_QUERY_SCHEMA)
144+
145+
146+
@pytest.fixture(scope="module")
147+
def google_auth_mock():
148+
with mock.patch.object(auth, "default") as google_auth_mock:
149+
google_auth_mock.return_value = (
150+
auth_credentials.AnonymousCredentials(),
151+
_TEST_PROJECT,
152+
)
153+
yield google_auth_mock
154+
155+
156+
@pytest.fixture(scope="module")
157+
def cloud_storage_create_bucket_mock():
158+
with mock.patch.object(storage, "Client") as cloud_storage_mock:
159+
bucket_mock = mock.Mock(spec=storage.Bucket)
160+
bucket_mock.blob.return_value.open.return_value = "blob_file"
161+
bucket_mock.blob.return_value.upload_from_filename.return_value = None
162+
bucket_mock.blob.return_value.upload_from_string.return_value = None
163+
164+
cloud_storage_mock.get_bucket = mock.Mock(
165+
side_effect=ValueError("bucket not found")
166+
)
167+
cloud_storage_mock.bucket.return_value = bucket_mock
168+
cloud_storage_mock.create_bucket.return_value = bucket_mock
169+
170+
yield cloud_storage_mock
171+
172+
173+
@pytest.fixture(scope="module")
174+
def cloudpickle_load_mock():
175+
with mock.patch.object(cloudpickle, "load") as cloudpickle_load_mock:
176+
yield cloudpickle_load_mock
177+
178+
179+
@pytest.fixture(scope="module")
180+
def create_agent_engine_mock():
181+
with mock.patch.object(
182+
reasoning_engine_service.ReasoningEngineServiceClient,
183+
"create_reasoning_engine",
184+
) as create_agent_engine_mock:
185+
create_agent_engine_lro_mock = mock.Mock(spec=ga_operation.Operation)
186+
create_agent_engine_lro_mock.result.return_value = _TEST_AGENT_ENGINE_OBJ
187+
create_agent_engine_mock.return_value = create_agent_engine_lro_mock
188+
yield create_agent_engine_mock
189+
190+
191+
@pytest.fixture(scope="function")
192+
def get_gca_resource_mock():
193+
with mock.patch.object(
194+
base.VertexAiResourceNoun,
195+
"_get_gca_resource",
196+
) as get_gca_resource_mock:
197+
get_gca_resource_mock.return_value = _TEST_AGENT_ENGINE_OBJ
198+
yield get_gca_resource_mock
199+
200+
201+
@pytest.mark.usefixtures("google_auth_mock")
202+
class TestAgentEngineA2A:
203+
def setup_method(self):
204+
aiplatform.init(
205+
project=_TEST_PROJECT,
206+
location=_TEST_LOCATION,
207+
credentials=_TEST_CREDENTIALS,
208+
staging_bucket=_TEST_STAGING_BUCKET,
209+
)
210+
211+
def test_create_agent_engine_with_protobuf_agent_card(
212+
self,
213+
create_agent_engine_mock,
214+
cloud_storage_create_bucket_mock,
215+
cloudpickle_load_mock,
216+
get_gca_resource_mock,
217+
):
218+
card = a2a_pb2.AgentCard(name="test_agent_card")
219+
agent = CapitalizeEngineWithCard(card)
220+
221+
agent_engines.create(
222+
agent,
223+
display_name=_TEST_AGENT_ENGINE_DISPLAY_NAME,
224+
requirements=_TEST_AGENT_ENGINE_REQUIREMENTS,
225+
extra_packages=[_TEST_AGENT_ENGINE_EXTRA_PACKAGE_PATH],
226+
)
227+
228+
expected_reasoning_engine = types.ReasoningEngine(
229+
display_name=_TEST_AGENT_ENGINE_DISPLAY_NAME,
230+
spec=types.ReasoningEngineSpec(
231+
package_spec=_TEST_AGENT_ENGINE_PACKAGE_SPEC,
232+
agent_framework=_agent_engines._DEFAULT_AGENT_FRAMEWORK,
233+
),
234+
)
235+
from google.protobuf import json_format
236+
237+
expected_class_method = struct_pb2.Struct()
238+
expected_class_method.CopyFrom(_TEST_AGENT_ENGINE_QUERY_SCHEMA)
239+
expected_class_method["a2a_agent_card"] = json_format.MessageToJson(card)
240+
expected_reasoning_engine.spec.class_methods.append(expected_class_method)
241+
242+
create_agent_engine_mock.assert_called_with(
243+
parent=_TEST_PARENT,
244+
reasoning_engine=expected_reasoning_engine,
245+
)
246+
247+
def test_create_agent_engine_with_pydantic_agent_card(
248+
self,
249+
create_agent_engine_mock,
250+
cloud_storage_create_bucket_mock,
251+
cloudpickle_load_mock,
252+
get_gca_resource_mock,
253+
):
254+
card = DummyPydanticCard()
255+
agent = CapitalizeEngineWithCard(card)
256+
257+
agent_engines.create(
258+
agent,
259+
display_name=_TEST_AGENT_ENGINE_DISPLAY_NAME,
260+
requirements=_TEST_AGENT_ENGINE_REQUIREMENTS,
261+
extra_packages=[_TEST_AGENT_ENGINE_EXTRA_PACKAGE_PATH],
262+
)
263+
264+
expected_reasoning_engine = types.ReasoningEngine(
265+
display_name=_TEST_AGENT_ENGINE_DISPLAY_NAME,
266+
spec=types.ReasoningEngineSpec(
267+
package_spec=_TEST_AGENT_ENGINE_PACKAGE_SPEC,
268+
agent_framework=_agent_engines._DEFAULT_AGENT_FRAMEWORK,
269+
),
270+
)
271+
272+
expected_class_method = struct_pb2.Struct()
273+
expected_class_method.CopyFrom(_TEST_AGENT_ENGINE_QUERY_SCHEMA)
274+
expected_class_method["a2a_agent_card"] = card.model_dump_json()
275+
expected_reasoning_engine.spec.class_methods.append(expected_class_method)
276+
277+
create_agent_engine_mock.assert_called_with(
278+
parent=_TEST_PARENT,
279+
reasoning_engine=expected_reasoning_engine,
280+
)
281+
282+
def test_create_agent_engine_with_invalid_agent_card(
283+
self,
284+
create_agent_engine_mock,
285+
cloud_storage_create_bucket_mock,
286+
cloudpickle_load_mock,
287+
get_gca_resource_mock,
288+
):
289+
agent = CapitalizeEngineWithCard(card="invalid_card_type_string")
290+
291+
with pytest.raises(
292+
TypeError,
293+
match="Unsupported AgentCard type",
294+
):
295+
agent_engines.create(
296+
agent,
297+
display_name=_TEST_AGENT_ENGINE_DISPLAY_NAME,
298+
requirements=_TEST_AGENT_ENGINE_REQUIREMENTS,
299+
extra_packages=[_TEST_AGENT_ENGINE_EXTRA_PACKAGE_PATH],
300+
)

vertexai/_genai/_agent_engines_utils.py

Lines changed: 59 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -652,10 +652,9 @@ def _generate_class_methods_spec_or_raise(
652652

653653
class_method = _to_proto(schema_dict)
654654
class_method[_MODE_KEY_IN_SCHEMA] = mode
655-
if hasattr(agent, "agent_card"):
656-
class_method[_A2A_AGENT_CARD] = json_format.MessageToJson(
657-
getattr(agent, "agent_card")
658-
)
655+
card = getattr(agent, "agent_card", None)
656+
if card is not None:
657+
class_method[_A2A_AGENT_CARD] = _serialize_agent_card_to_json(card)
659658
class_methods_spec.append(class_method)
660659

661660
return class_methods_spec
@@ -2148,3 +2147,59 @@ def _add_telemetry_enablement_env(
21482147
return env_vars
21492148

21502149
return env_vars | env_to_add
2150+
2151+
2152+
def _serialize_agent_card_to_dict(card: Any) -> Optional[Dict[str, Any]]:
2153+
"""Validates and serializes an AgentCard to a dictionary representation.
2154+
2155+
Args:
2156+
card: The AgentCard instance (Pydantic model or Protobuf Message).
2157+
2158+
Returns:
2159+
The serialized card as a dictionary.
2160+
2161+
Raises:
2162+
TypeError: If the card type is not supported.
2163+
"""
2164+
if card is None:
2165+
return None
2166+
2167+
if hasattr(card, "model_dump"):
2168+
return typing.cast(dict[str, Any], card.model_dump(exclude_none=True))
2169+
elif hasattr(card, "DESCRIPTOR"):
2170+
from google.protobuf import json_format
2171+
2172+
return typing.cast(dict[str, Any], json_format.MessageToDict(card))
2173+
else:
2174+
raise TypeError(
2175+
f"Unsupported AgentCard type: {type(card)}. "
2176+
"Only Pydantic models and Protobuf Messages are supported."
2177+
)
2178+
2179+
2180+
def _serialize_agent_card_to_json(card: Any) -> Optional[str]:
2181+
"""Validates and serializes an AgentCard to a JSON string representation.
2182+
2183+
Args:
2184+
card: The AgentCard instance (Pydantic model or Protobuf Message).
2185+
2186+
Returns:
2187+
The serialized card as a JSON string.
2188+
2189+
Raises:
2190+
TypeError: If the card type is not supported.
2191+
"""
2192+
if card is None:
2193+
return None
2194+
2195+
if hasattr(card, "model_dump_json"):
2196+
return typing.cast(str, card.model_dump_json())
2197+
elif hasattr(card, "DESCRIPTOR"):
2198+
from google.protobuf import json_format
2199+
2200+
return typing.cast(str, json_format.MessageToJson(card))
2201+
else:
2202+
raise TypeError(
2203+
f"Unsupported AgentCard type: {type(card)}. "
2204+
"Only Pydantic models and Protobuf Messages are supported."
2205+
)

0 commit comments

Comments
 (0)