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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import importlib
import json
from unittest import mock

from google import auth
from google.api_core import operation as ga_operation
from google.auth import credentials as auth_credentials
from google.cloud import aiplatform
from google.cloud.aiplatform import initializer
from google.cloud.aiplatform import utils as aip_utils
from google.cloud.aiplatform_v1beta1 import types
from google.cloud.aiplatform_v1beta1.services import (
    extension_execution_service,
)
from google.cloud.aiplatform_v1beta1.services import (
    extension_registry_service,
)
from vertexai.generative_models import _generative_models
from vertexai.preview import extensions
from vertexai.reasoning_engines import _utils
import pytest


_TEST_CREDENTIALS = mock.Mock(spec=auth_credentials.AnonymousCredentials())
_TEST_AUTH_CONFIG = types.AuthConfig(auth_type="GOOGLE_SERVICE_ACCOUNT_AUTH")
_TEST_RESOURCE_ID = "1028944691210842416"
_TEST_OPEN_API_GCS_URI = "gs://vertex-extension-experiment/code_interpreter.yaml"
_TEST_OPEN_API_YAML = """
      openapi: 3.0.0
      info:
        title: SomeApi
        version: 1.0.0
      servers:
        - url: https://www.someapi.com
      paths:
        /path1:
          get:
            summary: Request description
            operationId: requestSomething
            parameters:
              - name: request_parameter
                in: query
                required: true
                schema:
                  type: string
            responses:
              '200':
                description: Response description
                content:
                  application/json:
                    schema:
                      type: object
                      properties:
                        response_parameter:
                          type: string"""
_TEST_EXTENSION_MANIFEST_NAME = "code_interpreter_tool"
_TEST_EXTENSION_MANIFEST_DESCRIPTION = "Google Code Interpreter Extension"
_TEST_EXTENSION_MANIFEST_WITH_GCS_URI_OBJ = types.ExtensionManifest(
    name=_TEST_EXTENSION_MANIFEST_NAME,
    description=_TEST_EXTENSION_MANIFEST_DESCRIPTION,
    api_spec=types.ExtensionManifest.ApiSpec(
        open_api_gcs_uri=_TEST_OPEN_API_GCS_URI,
    ),
    auth_config=_TEST_AUTH_CONFIG,
)
_TEST_EXTENSION_MANIFEST_WITH_YAML_OBJ = types.ExtensionManifest(
    name=_TEST_EXTENSION_MANIFEST_NAME,
    description=_TEST_EXTENSION_MANIFEST_DESCRIPTION,
    api_spec=types.ExtensionManifest.ApiSpec(
        open_api_yaml=_TEST_OPEN_API_YAML,
    ),
    auth_config=_TEST_AUTH_CONFIG,
)
_TEST_EXTENSION_MANIFEST_WITH_NO_API_SPEC = types.ExtensionManifest(
    name=_TEST_EXTENSION_MANIFEST_NAME,
    description=_TEST_EXTENSION_MANIFEST_DESCRIPTION,
    auth_config=_TEST_AUTH_CONFIG,
)
_TEST_LOCATION = "us-central1"
_TEST_PROJECT = "test-project"
_TEST_PARENT = f"projects/{_TEST_PROJECT}/locations/{_TEST_LOCATION}"
_TEST_EXTENSION_RESOURCE_NAME = f"{_TEST_PARENT}/extensions/{_TEST_RESOURCE_ID}"
_TEST_EXTENSION_DISPLAY_NAME = "Extension Display Name"
_TEST_EXTENSION_OBJ = types.Extension(
    name=_TEST_EXTENSION_RESOURCE_NAME,
    display_name=_TEST_EXTENSION_DISPLAY_NAME,
    manifest=_TEST_EXTENSION_MANIFEST_WITH_GCS_URI_OBJ,
)
_TEST_EXTENSION_WITH_YAML_API_SPEC_OBJ = types.Extension(
    name=_TEST_EXTENSION_RESOURCE_NAME,
    display_name=_TEST_EXTENSION_DISPLAY_NAME,
    manifest=_TEST_EXTENSION_MANIFEST_WITH_YAML_OBJ,
)
_TEST_EXTENSION_WITH_NO_API_SPEC_OBJ = types.Extension(
    name=_TEST_EXTENSION_RESOURCE_NAME,
    display_name=_TEST_EXTENSION_DISPLAY_NAME,
    manifest=_TEST_EXTENSION_MANIFEST_WITH_NO_API_SPEC,
)
_TEST_EXTENSION_OPERATION_ID = "search"
_TEST_QUERY_PROMPT = "Find the first fibonacci number greater than 999"
_TEST_EXTENSION_OPERATION_PARAMS = {"query": _TEST_QUERY_PROMPT}
_TEST_RESPONSE_CONTENT = json.dumps(
    {
        "execution_error": "",
        "execution_result": "The first fibonacci number greater than 999 is 1597\n",
        "generated_code": "```python\n"
        "def fibonacci(n):\n"
        "    a, b = 0, 1\n"
        "    for _ in range(n):\n"
        "        a, b = b, a + b\n"
        "    return a\n"
        "\n"
        "# Find the first fibonacci number greater than 999\n"
        "n = 1\n"
        "while fibonacci(n) <= 999:\n"
        "    n += 1\n"
        "\n"
        'print(f"The first fibonacci number greater than 999 is '
        '{fibonacci(n)}")\n'
        "```",
        "output_files": [],
    }
)
_TEST_EXECUTE_EXTENSION_RESPONSE = types.ExecuteExtensionResponse(
    content=_TEST_RESPONSE_CONTENT,
)


@pytest.fixture(scope="module")
def google_auth_mock():
    with mock.patch.object(auth, "default") as google_auth_mock:
        google_auth_mock.return_value = (
            auth_credentials.AnonymousCredentials(),
            _TEST_PROJECT,
        )
        yield google_auth_mock


@pytest.fixture
def get_extension_mock():
    with mock.patch.object(
        extension_registry_service.ExtensionRegistryServiceClient,
        "get_extension",
    ) as get_extension_mock:
        api_client_mock = mock.Mock(
            spec=extension_registry_service.ExtensionRegistryServiceClient,
        )
        api_client_mock.get_extension.return_value = _TEST_EXTENSION_OBJ
        get_extension_mock.return_value = api_client_mock
        yield get_extension_mock


@pytest.fixture
def create_extension_mock():
    with mock.patch.object(
        extension_registry_service.ExtensionRegistryServiceClient,
        "import_extension",
    ) as create_extension_mock:
        create_extension_lro_mock = mock.Mock(ga_operation.Operation)
        create_extension_lro_mock.result.return_value = _TEST_EXTENSION_OBJ
        create_extension_mock.return_value = create_extension_lro_mock
        yield create_extension_mock


@pytest.fixture
def execute_extension_mock():
    with mock.patch.object(
        extension_execution_service.ExtensionExecutionServiceClient, "execute_extension"
    ) as execute_extension_mock:
        execute_extension_mock.return_value.content = _TEST_RESPONSE_CONTENT
        yield execute_extension_mock


@pytest.fixture
def query_extension_mock():
    with mock.patch.object(
        extension_execution_service.ExtensionExecutionServiceClient, "query_extension"
    ) as query_extension_mock:
        query_extension_mock.return_value.steps = [
            types.Content(
                role="user",
                parts=[
                    types.Part(
                        text=_TEST_QUERY_PROMPT,
                    )
                ],
            ),
            types.Content(
                role="extension",
                parts=[
                    types.Part(
                        text=_TEST_RESPONSE_CONTENT,
                    )
                ],
            ),
        ]
        query_extension_mock.return_value.failure_message = ""
        yield query_extension_mock


@pytest.fixture
def delete_extension_mock():
    with mock.patch.object(
        extension_registry_service.ExtensionRegistryServiceClient,
        "delete_extension",
    ) as delete_extension_mock:
        delete_extension_lro_mock = mock.Mock(ga_operation.Operation)
        delete_extension_lro_mock.result.return_value = None
        delete_extension_mock.return_value = delete_extension_lro_mock
        yield delete_extension_mock


@pytest.fixture
def to_dict_mock():
    with mock.patch.object(_utils, "to_dict") as to_dict_mock:
        to_dict_mock.return_value = {}
        yield to_dict_mock


@pytest.fixture
def load_yaml_mock():
    with mock.patch.object(
        aip_utils.yaml_utils,
        "load_yaml",
        autospec=True,
    ) as load_yaml_mock:
        load_yaml_mock.return_value = lambda x: x
        yield load_yaml_mock


@pytest.mark.usefixtures("google_auth_mock")
class TestExtension:
    def setup_method(self):
        importlib.reload(initializer)
        importlib.reload(aiplatform)
        aiplatform.init(
            project=_TEST_PROJECT,
            location=_TEST_LOCATION,
            credentials=_TEST_CREDENTIALS,
        )

    def teardown_method(self):
        initializer.global_pool.shutdown(wait=True)

    def test_get_extension(self, get_extension_mock):
        extensions.Extension(_TEST_RESOURCE_ID)
        get_extension_mock.assert_called_once_with(
            name=_TEST_EXTENSION_RESOURCE_NAME,
            retry=aiplatform.base._DEFAULT_RETRY,
        )

    def test_create_extension(
        self,
        create_extension_mock,
        get_extension_mock,
        load_yaml_mock,
    ):
        extensions.Extension.create(
            extension_name=_TEST_EXTENSION_RESOURCE_NAME,
            display_name=_TEST_EXTENSION_DISPLAY_NAME,
            manifest=_TEST_EXTENSION_MANIFEST_WITH_GCS_URI_OBJ,
        )
        create_extension_mock.assert_called_once_with(
            parent=_TEST_PARENT,
            extension=_TEST_EXTENSION_OBJ,
        )
        get_extension_mock.assert_called_once_with(
            name=_TEST_EXTENSION_RESOURCE_NAME,
            retry=aiplatform.base._DEFAULT_RETRY,
        )

    def test_delete_after_create_extension(
        self,
        create_extension_mock,
        get_extension_mock,
        delete_extension_mock,
        load_yaml_mock,
    ):
        test_extension = extensions.Extension.create(
            extension_name=_TEST_EXTENSION_RESOURCE_NAME,
            display_name=_TEST_EXTENSION_DISPLAY_NAME,
            manifest=_TEST_EXTENSION_MANIFEST_WITH_GCS_URI_OBJ,
        )
        create_extension_mock.assert_called_once_with(
            parent=_TEST_PARENT,
            extension=_TEST_EXTENSION_OBJ,
        )
        get_extension_mock.assert_any_call(
            name=_TEST_EXTENSION_RESOURCE_NAME,
            retry=aiplatform.base._DEFAULT_RETRY,
        )
        # Manually set _gca_resource here to prevent the mocks from propagating.
        test_extension._gca_resource = _TEST_EXTENSION_OBJ
        test_extension.delete()
        delete_extension_mock.assert_called_once_with(
            name=test_extension.resource_name,
        )

    def test_delete_after_get_extension(
        self,
        get_extension_mock,
        delete_extension_mock,
        load_yaml_mock,
    ):
        test_extension = extensions.Extension(_TEST_RESOURCE_ID)
        get_extension_mock.assert_any_call(
            name=_TEST_EXTENSION_RESOURCE_NAME,
            retry=aiplatform.base._DEFAULT_RETRY,
        )
        # Manually set _gca_resource here to prevent the mocks from propagating.
        test_extension._gca_resource = _TEST_EXTENSION_OBJ
        test_extension.delete()
        delete_extension_mock.assert_called_once_with(
            name=test_extension.resource_name,
        )

    def test_execute_extension(
        self,
        get_extension_mock,
        execute_extension_mock,
        load_yaml_mock,
    ):
        test_extension = extensions.Extension(_TEST_RESOURCE_ID)
        get_extension_mock.assert_called_once_with(
            name=_TEST_EXTENSION_RESOURCE_NAME,
            retry=aiplatform.base._DEFAULT_RETRY,
        )
        # Manually set _gca_resource here to prevent the mocks from propagating.
        test_extension._gca_resource = _TEST_EXTENSION_OBJ
        test_extension.execute(
            operation_id=_TEST_EXTENSION_OPERATION_ID,
            operation_params=_TEST_EXTENSION_OPERATION_PARAMS,
            runtime_auth_config=_TEST_AUTH_CONFIG,
        )
        execute_extension_mock.assert_called_once_with(
            types.ExecuteExtensionRequest(
                name=_TEST_EXTENSION_RESOURCE_NAME,
                operation_id=_TEST_EXTENSION_OPERATION_ID,
                operation_params=_utils.to_proto(
                    _TEST_EXTENSION_OPERATION_PARAMS,
                ),
                runtime_auth_config=_TEST_AUTH_CONFIG,
            ),
        )

    def test_query_extension(
        self,
        get_extension_mock,
        query_extension_mock,
        load_yaml_mock,
    ):
        test_extension = extensions.Extension(_TEST_RESOURCE_ID)
        get_extension_mock.assert_called_once_with(
            name=_TEST_EXTENSION_RESOURCE_NAME,
            retry=aiplatform.base._DEFAULT_RETRY,
        )
        # Manually set _gca_resource here to prevent the mocks from propagating.
        test_extension._gca_resource = _TEST_EXTENSION_OBJ
        response = test_extension.query(
            contents=[
                _generative_models.Content(
                    parts=[
                        _generative_models.Part.from_text(
                            _TEST_QUERY_PROMPT,
                        )
                    ],
                    role="user",
                )
            ],
        )
        assert response.steps[-1].parts[0].text == _TEST_RESPONSE_CONTENT

        query_extension_mock.assert_called_once_with(
            types.QueryExtensionRequest(
                name=_TEST_EXTENSION_RESOURCE_NAME,
                contents=[
                    types.Content(
                        role="user",
                        parts=[
                            types.Part(
                                text=_TEST_QUERY_PROMPT,
                            )
                        ],
                    )
                ],
            ),
        )

    def test_api_spec_from_yaml(self, get_extension_mock, load_yaml_mock):
        test_extension = extensions.Extension(_TEST_RESOURCE_ID)
        get_extension_mock.assert_called_once_with(
            name=_TEST_EXTENSION_RESOURCE_NAME,
            retry=aiplatform.base._DEFAULT_RETRY,
        )
        # Manually set _gca_resource here to prevent the mocks from propagating.
        test_extension._gca_resource = _TEST_EXTENSION_WITH_YAML_API_SPEC_OBJ
        test_extension.api_spec() == {}

    def test_no_api_spec(self, get_extension_mock, load_yaml_mock):
        test_extension = extensions.Extension(_TEST_RESOURCE_ID)
        get_extension_mock.assert_called_once_with(
            name=_TEST_EXTENSION_RESOURCE_NAME,
            retry=aiplatform.base._DEFAULT_RETRY,
        )
        # Manually set _gca_resource here to prevent the mocks from propagating.
        test_extension._gca_resource = _TEST_EXTENSION_WITH_NO_API_SPEC_OBJ
        test_extension.api_spec() == {}

    def test_api_spec_from_gcs_uri(
        self,
        get_extension_mock,
        load_yaml_mock,
    ):
        test_extension = extensions.Extension(_TEST_RESOURCE_ID)
        get_extension_mock.assert_called_once_with(
            name=_TEST_EXTENSION_RESOURCE_NAME,
            retry=aiplatform.base._DEFAULT_RETRY,
        )
        # Manually set _gca_resource here to prevent the mocks from propagating.
        test_extension._gca_resource = _TEST_EXTENSION_OBJ
        test_extension.api_spec()
        load_yaml_mock.assert_called_once_with(_TEST_OPEN_API_GCS_URI)

    def test_operation_schemas(self, get_extension_mock):
        test_extension = extensions.Extension(_TEST_RESOURCE_ID)
        get_extension_mock.assert_called_once_with(
            name=_TEST_EXTENSION_RESOURCE_NAME,
            retry=aiplatform.base._DEFAULT_RETRY,
        )
        # Manually set _gca_resource here to prevent the mocks from propagating.
        test_extension._gca_resource = _TEST_EXTENSION_OBJ
        test_extension.operation_schemas()