Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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<truncated BOOL, token_count FLOAT64>,
values ARRAY<FLOAT32>
>
)
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,
)
Comment on lines +64 to +87

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Catching the exceptions and only printing them to stderr causes the function to return normally (None). This means that any programmatic caller will not know that the operation failed, and running this file as a CLI script will exit with status 0 (success) even on failure. It is better to re-raise the exceptions so that failures are propagated correctly.

Suggested change
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}' for project '{project_id}': {err.message}",
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}' for project '{project_id}': {err.message}",
file=sys.stderr,
)
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}' for project '{project_id}': {err.message}",
file=sys.stderr,
)
raise
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}' for project '{project_id}': {err.message}",
file=sys.stderr,
)
raise

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the feedback! Standalone documentation snippets here intentionally catch google.api_core.exceptions inside the sample function and print actionable diagnostic messages to stderr so readers can see concrete error handling directly in context, so we are keeping the try/except block.

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,
)
137 changes: 137 additions & 0 deletions spanner/search_and_ai/tests/create_embedding_model_test.py
Original file line number Diff line number Diff line change
@@ -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)
Comment on lines +71 to +89

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Update the test to expect the exception to be raised, aligning with the propagated exceptions in the main function.

Suggested change
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
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)
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
client.update_database_ddl.side_effect = error
with pytest.raises(type(error)):
create_embedding_model.create_embedding_model(
PROJECT_ID, LOCATION_ID, INSTANCE_ID, DATABASE_ID
)
_out, err = capsys.readouterr()
assert err.startswith(expected_prefix)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! Since the sample keeps its explicit exception handling and stderr reporting, this test keeps its capsys stderr assertions.

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