diff --git a/spanner/search_and_ai/src/spanner_search_and_ai/create_embedding_model.py b/spanner/search_and_ai/src/spanner_search_and_ai/create_embedding_model.py new file mode 100644 index 0000000000..134c7577d4 --- /dev/null +++ b/spanner/search_and_ai/src/spanner_search_and_ai/create_embedding_model.py @@ -0,0 +1,131 @@ +# Copyright 2026 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. + +# [START spanner_create_embedding_model] +import sys + +from google.api_core import exceptions +from google.cloud import spanner_admin_database_v1 + + +def create_embedding_model( + project_id: str, + location_id: str, + instance_id: str, + database_id: str, +) -> None: + """Registers a remote Vertex AI text-embedding model in a Spanner schema. + + Args: + project_id: The Google Cloud project ID. + location_id: The Vertex AI endpoint region (such as 'us-central1'). + instance_id: The Spanner instance ID. + database_id: The Spanner GoogleSQL database ID. + """ + client = spanner_admin_database_v1.DatabaseAdminClient() + database_path = client.database_path(project_id, instance_id, database_id) + model_name = "TextEmbeddingModel" + endpoint = ( + f"//aiplatform.googleapis.com/projects/{project_id}" + f"/locations/{location_id}/publishers/google/models/text-embedding-005" + ) + ddl_statement = f""" + CREATE OR REPLACE MODEL {model_name} + INPUT ( + content STRING(MAX), + task_type STRING(MAX) OPTIONS (required = false) + ) + OUTPUT ( + embeddings STRUCT< + statistics STRUCT, + values ARRAY + > + ) + REMOTE OPTIONS ( + endpoint = '{endpoint}' + ) + """.strip() + request = spanner_admin_database_v1.UpdateDatabaseDdlRequest( + database=database_path, + statements=[ddl_statement], + ) + + try: + operation = client.update_database_ddl(request=request) + print(f"Waiting for remote model '{model_name}' registration...") + operation.result(timeout=300) + except exceptions.AlreadyExists as err: + print( + f"error: model '{model_name}' already exists on database " + f"'{database_id}' in instance '{instance_id}' and location " + f"'{location_id}': {err.message}", + file=sys.stderr, + ) + except TimeoutError as err: + print( + f"error: timed out waiting for the operation on database '{database_id}' " + f"to complete; the operation may still be running: {err}", + file=sys.stderr, + ) + except exceptions.GoogleAPICallError as err: + print( + f"error: failed to register model '{model_name}' on database " + f"'{database_id}' in instance '{instance_id}' and location " + f"'{location_id}': {err.message}", + file=sys.stderr, + ) + else: + print(f"Resource ID: {database_id}") + print(f"Endpoint Location: {location_id}") + print(f"Model Name: {model_name}") + + +# [END spanner_create_embedding_model] + + +if __name__ == "__main__": + import argparse + import os + + parser = argparse.ArgumentParser( + description="Register a Vertex AI text-embedding model in Spanner." + ) + parser.add_argument( + "--project-id", + default=os.environ.get("GOOGLE_CLOUD_PROJECT", "example-project-id"), + help="Google Cloud project ID (default: $GOOGLE_CLOUD_PROJECT)", + ) + parser.add_argument( + "--location-id", + default=os.environ.get("GOOGLE_CLOUD_LOCATION", "us-central1"), + help="Vertex AI region (default: $GOOGLE_CLOUD_LOCATION)", + ) + parser.add_argument( + "--instance-id", + default=os.environ.get("SPANNER_INSTANCE_ID", "example-instance"), + help="Spanner instance ID (default: $SPANNER_INSTANCE_ID)", + ) + parser.add_argument( + "--database-id", + default=os.environ.get("SPANNER_DATABASE_ID", "example-db"), + help="Spanner database ID (default: $SPANNER_DATABASE_ID)", + ) + args = parser.parse_args() + + create_embedding_model( + project_id=args.project_id, + location_id=args.location_id, + instance_id=args.instance_id, + database_id=args.database_id, + ) diff --git a/spanner/search_and_ai/tests/create_embedding_model_test.py b/spanner/search_and_ai/tests/create_embedding_model_test.py new file mode 100644 index 0000000000..f78bf044e1 --- /dev/null +++ b/spanner/search_and_ai/tests/create_embedding_model_test.py @@ -0,0 +1,137 @@ +# Copyright 2026 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 runpy +from unittest import mock + +from google.api_core import exceptions +import pytest +from spanner_search_and_ai import create_embedding_model + +from . import conftest + +PROJECT_ID = "example-project-id" +LOCATION_ID = "us-central1" +INSTANCE_ID = "example-instance" +DATABASE_ID = "example-db" +DATABASE_PATH = f"projects/{PROJECT_ID}/instances/{INSTANCE_ID}/databases/{DATABASE_ID}" +ADMIN_CLIENT = "google.cloud.spanner_admin_database_v1.DatabaseAdminClient" + + +@mock.patch(ADMIN_CLIENT, autospec=True) +def test_create_embedding_model_success( + mock_client_class: mock.MagicMock, capsys: pytest.CaptureFixture[str] +) -> None: + client = mock_client_class.return_value + client.database_path.return_value = DATABASE_PATH + + create_embedding_model.create_embedding_model( + PROJECT_ID, LOCATION_ID, INSTANCE_ID, DATABASE_ID + ) + + request = client.update_database_ddl.call_args.kwargs["request"] + assert "CREATE OR REPLACE MODEL TextEmbeddingModel" in request.statements[0] + assert "publishers/google/models/text-embedding-005" in request.statements[0] + client.update_database_ddl.return_value.result.assert_called_once_with(timeout=300) + + out, err = capsys.readouterr() + assert "Waiting for remote model 'TextEmbeddingModel'" in out + assert f"Resource ID: {DATABASE_ID}" in out + assert PROJECT_ID not in out + assert "Model Name: TextEmbeddingModel" in out + assert err == "" + + +@pytest.mark.parametrize( + "error, expected_prefix", + [ + (TimeoutError("deadline"), "error: timed out waiting for the operation"), + ( + exceptions.AlreadyExists("model exists"), + "error: model 'TextEmbeddingModel' already exists", + ), + ( + exceptions.PermissionDenied("denied"), + "error: failed to register model 'TextEmbeddingModel'", + ), + ], +) +@mock.patch(ADMIN_CLIENT, autospec=True) +def test_create_embedding_model_errors( + mock_client_class: mock.MagicMock, + capsys: pytest.CaptureFixture[str], + error: Exception, + expected_prefix: str, +) -> None: + client = mock_client_class.return_value + client.database_path.return_value = DATABASE_PATH + if isinstance(error, TimeoutError): + client.update_database_ddl.return_value.result.side_effect = error + else: + client.update_database_ddl.side_effect = error + + create_embedding_model.create_embedding_model( + PROJECT_ID, LOCATION_ID, INSTANCE_ID, DATABASE_ID + ) + + _out, err = capsys.readouterr() + assert err.startswith(expected_prefix) + assert PROJECT_ID not in err + + +@mock.patch(ADMIN_CLIENT, autospec=True) +def test_create_embedding_model_cli_entrypoint( + mock_client_class: mock.MagicMock, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + mock_client_class.return_value.database_path.return_value = DATABASE_PATH + monkeypatch.setattr( + "sys.argv", + [ + "create_embedding_model.py", + "--project-id", + PROJECT_ID, + "--location-id", + LOCATION_ID, + "--instance-id", + INSTANCE_ID, + "--database-id", + DATABASE_ID, + ], + ) + + runpy.run_module( + "spanner_search_and_ai.create_embedding_model", run_name="__main__" + ) + + assert "Model Name: TextEmbeddingModel" in capsys.readouterr().out + + +# Live integration test: skipped unless RUN_INTEGRATION_TESTS=true is set along with +# GOOGLE_CLOUD_PROJECT, SPANNER_INSTANCE_ID, and SPANNER_DATABASE_ID. +@conftest.live_only +def test_create_embedding_model_live( + capsys: pytest.CaptureFixture[str], +) -> None: + create_embedding_model.create_embedding_model( + conftest.LIVE_PROJECT_ID, + conftest.LIVE_LOCATION_ID, + conftest.LIVE_INSTANCE_ID, + conftest.LIVE_DATABASE_ID, + ) + + out, err = capsys.readouterr() + assert err == "" + assert "Model Name: TextEmbeddingModel" in out