Skip to content

Commit b8301ec

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 b8301ec

6 files changed

Lines changed: 412 additions & 14 deletions

File tree

noxfile.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@
110110
"unit_agentplatform_langchain",
111111
"unit_agentplatform_ag2",
112112
"unit_agentplatform_llama_index",
113+
"unit_agentplatform_a2a",
113114
"system",
114115
"cover",
115116
"lint",
@@ -222,6 +223,7 @@ def default(session):
222223
"--ignore=tests/unit/vertex_langchain",
223224
"--ignore=tests/unit/vertex_ag2",
224225
"--ignore=tests/unit/vertex_llama_index",
226+
"--ignore=tests/unit/vertex_a2a",
225227
"--ignore=tests/unit/architecture",
226228
"--ignore=tests/unit/vertexai/genai/replays",
227229
"--ignore=tests/unit/agentplatform/genai/replays",
@@ -429,6 +431,29 @@ def unit_agentplatform_llama_index(session):
429431
)
430432

431433

434+
@nox.session(python=["3.14"])
435+
def unit_agentplatform_a2a(session):
436+
# Install all test dependencies, then install this package in-place.
437+
438+
constraints_path = str(CURRENT_DIRECTORY / "testing" / "constraints-a2a.txt")
439+
install_unittest_dependencies(session, "-c", constraints_path)
440+
session.install("a2a-sdk", "-c", constraints_path)
441+
442+
# Run py.test against the unit tests.
443+
session.run(
444+
"py.test",
445+
"--quiet",
446+
"--junitxml=unit_agentplatform_a2a_sponge_log.xml",
447+
"--cov=google",
448+
"--cov-append",
449+
"--cov-config=.coveragerc",
450+
"--cov-report=",
451+
"--cov-fail-under=0",
452+
os.path.join("tests", "unit", "vertex_a2a"),
453+
*session.posargs,
454+
)
455+
456+
432457
@nox.session(python=UNIT_TEST_TEMPLATES_PYTHON_VERSIONS)
433458
def unit_langchain(session):
434459
# Install all test dependencies, then install this package in-place.

testing/constraints-a2a.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
protobuf>=5.29.5
2+
a2a-sdk>=1.0.0
Lines changed: 315 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,315 @@
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+
38+
39+
40+
41+
42+
class CapitalizeEngine:
43+
"""A sample Agent Engine."""
44+
45+
def query(self, unused_arbitrary_string_name: str) -> str:
46+
"""Runs the engine."""
47+
return unused_arbitrary_string_name.upper()
48+
49+
50+
class CapitalizeEngineWithCard(CapitalizeEngine):
51+
52+
def __init__(self, card):
53+
self.agent_card = card
54+
55+
def __getstate__(self):
56+
state = self.__dict__.copy()
57+
if hasattr(self.agent_card, "DESCRIPTOR"):
58+
state["agent_card"] = None
59+
return state
60+
61+
def __setstate__(self, state):
62+
self.__dict__.update(state)
63+
64+
65+
class DummyPydanticCard(pydantic.BaseModel):
66+
name: str = "test_pydantic_card"
67+
68+
69+
def _create_empty_fake_package(package_name: str) -> str:
70+
temp_dir = tempfile.mkdtemp()
71+
package_dir = os.path.join(temp_dir, package_name)
72+
os.makedirs(package_dir)
73+
init_path = os.path.join(package_dir, "__init__.py")
74+
open(init_path, "w").close()
75+
return temp_dir
76+
77+
78+
_TEST_CREDENTIALS = mock.Mock(spec=auth_credentials.AnonymousCredentials())
79+
_TEST_STAGING_BUCKET = "gs://test-bucket"
80+
_TEST_LOCATION = "us-central1"
81+
_TEST_PROJECT = "test-project"
82+
_TEST_RESOURCE_ID = "1028944691210842416"
83+
_TEST_PARENT = f"projects/{_TEST_PROJECT}/locations/{_TEST_LOCATION}"
84+
_TEST_AGENT_ENGINE_RESOURCE_NAME = (
85+
f"{_TEST_PARENT}/reasoningEngines/{_TEST_RESOURCE_ID}"
86+
)
87+
_TEST_AGENT_ENGINE_DISPLAY_NAME = "Agent Engine Display Name"
88+
_TEST_GCS_DIR_NAME = _agent_engines._DEFAULT_GCS_DIR_NAME
89+
_TEST_BLOB_FILENAME = _agent_engines._BLOB_FILENAME
90+
_TEST_REQUIREMENTS_FILE = _agent_engines._REQUIREMENTS_FILE
91+
_TEST_EXTRA_PACKAGES_FILE = _agent_engines._EXTRA_PACKAGES_FILE
92+
_TEST_STANDARD_API_MODE = _agent_engines._STANDARD_API_MODE
93+
_TEST_DEFAULT_METHOD_NAME = _agent_engines._DEFAULT_METHOD_NAME
94+
_TEST_MODE_KEY_IN_SCHEMA = _agent_engines._MODE_KEY_IN_SCHEMA
95+
96+
_TEST_AGENT_ENGINE_EXTRA_PACKAGE = "fake.py"
97+
98+
_TEST_AGENT_ENGINE_EXTRA_PACKAGE_PATH = _create_empty_fake_package(
99+
_TEST_AGENT_ENGINE_EXTRA_PACKAGE
100+
)
101+
102+
_TEST_AGENT_ENGINE_REQUIREMENTS = [
103+
"google-cloud-aiplatform==1.29.0",
104+
"langchain",
105+
]
106+
107+
_TEST_AGENT_ENGINE_GCS_URI = "{}/{}/{}".format(
108+
_TEST_STAGING_BUCKET,
109+
_TEST_GCS_DIR_NAME,
110+
_TEST_BLOB_FILENAME,
111+
)
112+
_TEST_AGENT_ENGINE_DEPENDENCY_FILES_GCS_URI = "{}/{}/{}".format(
113+
_TEST_STAGING_BUCKET,
114+
_TEST_GCS_DIR_NAME,
115+
_TEST_EXTRA_PACKAGES_FILE,
116+
)
117+
_TEST_AGENT_ENGINE_REQUIREMENTS_GCS_URI = "{}/{}/{}".format(
118+
_TEST_STAGING_BUCKET,
119+
_TEST_GCS_DIR_NAME,
120+
_TEST_REQUIREMENTS_FILE,
121+
)
122+
123+
_TEST_AGENT_ENGINE_QUERY_SCHEMA = _utils.to_proto(
124+
_utils.generate_schema(
125+
CapitalizeEngine().query,
126+
schema_name=_TEST_DEFAULT_METHOD_NAME,
127+
)
128+
)
129+
_TEST_AGENT_ENGINE_QUERY_SCHEMA[_TEST_MODE_KEY_IN_SCHEMA] = _TEST_STANDARD_API_MODE
130+
131+
_TEST_AGENT_ENGINE_PACKAGE_SPEC = types.ReasoningEngineSpec.PackageSpec(
132+
python_version=f"{sys.version_info.major}.{sys.version_info.minor}",
133+
pickle_object_gcs_uri=_TEST_AGENT_ENGINE_GCS_URI,
134+
dependency_files_gcs_uri=_TEST_AGENT_ENGINE_DEPENDENCY_FILES_GCS_URI,
135+
requirements_gcs_uri=_TEST_AGENT_ENGINE_REQUIREMENTS_GCS_URI,
136+
)
137+
138+
_TEST_AGENT_ENGINE_OBJ = types.ReasoningEngine(
139+
name=_TEST_AGENT_ENGINE_RESOURCE_NAME,
140+
spec=types.ReasoningEngineSpec(
141+
package_spec=_TEST_AGENT_ENGINE_PACKAGE_SPEC,
142+
agent_framework=_agent_engines._DEFAULT_AGENT_FRAMEWORK,
143+
),
144+
)
145+
_TEST_AGENT_ENGINE_OBJ.spec.class_methods.append(_TEST_AGENT_ENGINE_QUERY_SCHEMA)
146+
147+
148+
@pytest.fixture(scope="module")
149+
def google_auth_mock():
150+
with mock.patch.object(auth, "default") as google_auth_mock:
151+
google_auth_mock.return_value = (
152+
auth_credentials.AnonymousCredentials(),
153+
_TEST_PROJECT,
154+
)
155+
yield google_auth_mock
156+
157+
158+
@pytest.fixture(scope="module")
159+
def cloud_storage_create_bucket_mock():
160+
with mock.patch.object(storage, "Client") as cloud_storage_mock:
161+
bucket_mock = mock.Mock(spec=storage.Bucket)
162+
bucket_mock.blob.return_value.open.return_value = "blob_file"
163+
bucket_mock.blob.return_value.upload_from_filename.return_value = None
164+
bucket_mock.blob.return_value.upload_from_string.return_value = None
165+
166+
cloud_storage_mock.get_bucket = mock.Mock(
167+
side_effect=ValueError("bucket not found")
168+
)
169+
cloud_storage_mock.bucket.return_value = bucket_mock
170+
cloud_storage_mock.create_bucket.return_value = bucket_mock
171+
172+
yield cloud_storage_mock
173+
174+
175+
@pytest.fixture(scope="module")
176+
def cloudpickle_load_mock():
177+
with mock.patch.object(cloudpickle, "load") as cloudpickle_load_mock:
178+
yield cloudpickle_load_mock
179+
180+
181+
@pytest.fixture(scope="module")
182+
def create_agent_engine_mock():
183+
with mock.patch.object(
184+
reasoning_engine_service.ReasoningEngineServiceClient,
185+
"create_reasoning_engine",
186+
) as create_agent_engine_mock:
187+
create_agent_engine_lro_mock = mock.Mock(spec=ga_operation.Operation)
188+
create_agent_engine_lro_mock.result.return_value = _TEST_AGENT_ENGINE_OBJ
189+
create_agent_engine_mock.return_value = create_agent_engine_lro_mock
190+
yield create_agent_engine_mock
191+
192+
193+
@pytest.fixture(scope="function")
194+
def get_gca_resource_mock():
195+
with mock.patch.object(
196+
base.VertexAiResourceNoun,
197+
"_get_gca_resource",
198+
) as get_gca_resource_mock:
199+
get_gca_resource_mock.return_value = _TEST_AGENT_ENGINE_OBJ
200+
yield get_gca_resource_mock
201+
202+
203+
@pytest.mark.usefixtures("google_auth_mock")
204+
class TestAgentEngineA2A:
205+
def setup_method(self):
206+
aiplatform.init(
207+
project=_TEST_PROJECT,
208+
location=_TEST_LOCATION,
209+
credentials=_TEST_CREDENTIALS,
210+
staging_bucket=_TEST_STAGING_BUCKET,
211+
)
212+
213+
def test_create_agent_engine_with_protobuf_agent_card(
214+
self,
215+
create_agent_engine_mock,
216+
cloud_storage_create_bucket_mock,
217+
cloudpickle_load_mock,
218+
get_gca_resource_mock,
219+
):
220+
a2a_pb2 = None
221+
try:
222+
try:
223+
from a2a.compat.v0_3 import a2a_v0_3_pb2 as a2a_pb2
224+
except ImportError:
225+
from a2a.grpc import a2a_pb2
226+
has_a2a_pb2 = True
227+
except (ImportError, TypeError):
228+
has_a2a_pb2 = False
229+
230+
if not has_a2a_pb2:
231+
pytest.skip("a2a_pb2 could not be imported.")
232+
233+
card = a2a_pb2.AgentCard(name="test_agent_card")
234+
agent = CapitalizeEngineWithCard(card)
235+
236+
agent_engines.create(
237+
agent,
238+
display_name=_TEST_AGENT_ENGINE_DISPLAY_NAME,
239+
requirements=_TEST_AGENT_ENGINE_REQUIREMENTS,
240+
extra_packages=[_TEST_AGENT_ENGINE_EXTRA_PACKAGE_PATH],
241+
)
242+
243+
expected_reasoning_engine = types.ReasoningEngine(
244+
display_name=_TEST_AGENT_ENGINE_DISPLAY_NAME,
245+
spec=types.ReasoningEngineSpec(
246+
package_spec=_TEST_AGENT_ENGINE_PACKAGE_SPEC,
247+
agent_framework=_agent_engines._DEFAULT_AGENT_FRAMEWORK,
248+
),
249+
)
250+
from google.protobuf import json_format
251+
252+
expected_class_method = struct_pb2.Struct()
253+
expected_class_method.CopyFrom(_TEST_AGENT_ENGINE_QUERY_SCHEMA)
254+
expected_class_method["a2a_agent_card"] = json_format.MessageToJson(card)
255+
expected_reasoning_engine.spec.class_methods.append(expected_class_method)
256+
257+
create_agent_engine_mock.assert_called_with(
258+
parent=_TEST_PARENT,
259+
reasoning_engine=expected_reasoning_engine,
260+
)
261+
262+
def test_create_agent_engine_with_pydantic_agent_card(
263+
self,
264+
create_agent_engine_mock,
265+
cloud_storage_create_bucket_mock,
266+
cloudpickle_load_mock,
267+
get_gca_resource_mock,
268+
):
269+
card = DummyPydanticCard()
270+
agent = CapitalizeEngineWithCard(card)
271+
272+
agent_engines.create(
273+
agent,
274+
display_name=_TEST_AGENT_ENGINE_DISPLAY_NAME,
275+
requirements=_TEST_AGENT_ENGINE_REQUIREMENTS,
276+
extra_packages=[_TEST_AGENT_ENGINE_EXTRA_PACKAGE_PATH],
277+
)
278+
279+
expected_reasoning_engine = types.ReasoningEngine(
280+
display_name=_TEST_AGENT_ENGINE_DISPLAY_NAME,
281+
spec=types.ReasoningEngineSpec(
282+
package_spec=_TEST_AGENT_ENGINE_PACKAGE_SPEC,
283+
agent_framework=_agent_engines._DEFAULT_AGENT_FRAMEWORK,
284+
),
285+
)
286+
287+
expected_class_method = struct_pb2.Struct()
288+
expected_class_method.CopyFrom(_TEST_AGENT_ENGINE_QUERY_SCHEMA)
289+
expected_class_method["a2a_agent_card"] = card.model_dump_json()
290+
expected_reasoning_engine.spec.class_methods.append(expected_class_method)
291+
292+
create_agent_engine_mock.assert_called_with(
293+
parent=_TEST_PARENT,
294+
reasoning_engine=expected_reasoning_engine,
295+
)
296+
297+
def test_create_agent_engine_with_invalid_agent_card(
298+
self,
299+
create_agent_engine_mock,
300+
cloud_storage_create_bucket_mock,
301+
cloudpickle_load_mock,
302+
get_gca_resource_mock,
303+
):
304+
agent = CapitalizeEngineWithCard(card="invalid_card_type_string")
305+
306+
with pytest.raises(
307+
TypeError,
308+
match="Unsupported AgentCard type",
309+
):
310+
agent_engines.create(
311+
agent,
312+
display_name=_TEST_AGENT_ENGINE_DISPLAY_NAME,
313+
requirements=_TEST_AGENT_ENGINE_REQUIREMENTS,
314+
extra_packages=[_TEST_AGENT_ENGINE_EXTRA_PACKAGE_PATH],
315+
)

0 commit comments

Comments
 (0)