Skip to content

feat(spanner): Add in-database ML.PREDICT text embedding sample - #14843

Open
iennae wants to merge 3 commits into
mainfrom
feat/spanner-ml-predict-embeddings
Open

iennae wants to merge 3 commits into
mainfrom
feat/spanner-ml-predict-embeddings

Conversation

@iennae

@iennae iennae commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Description

Developers building semantic search pipelines on Cloud Spanner had only SQL tutorials for invoking ML.PREDICT on a registered Vertex AI embedding model and unpacking embeddings.values in Python.

Adds spanner_ml_predict_embeddings showing parameterized text binding and vector output extraction through a Spanner snapshot.

Note: Stacked on #14836 (feat/spanner-vector-search-knn) so this PR shows only this sample's diff. It will merge into main after #14836.

Checklist

Testing

  • I have tested this change on a live environment and verified it works as intended. Unit and live integration tests pass on Python 3.13.

Compliance & Style


Post-Approval Actions

  • Please merge this PR for me once it is approved

Python developers implementing semantic similarity search on Cloud Spanner lacked a client library example showing parameterized FLOAT32 vector bindings with COSINE_DISTANCE.
Generating vector embeddings directly inside Cloud Spanner SQL queries avoids round-tripping text to an external service before similarity search, but lacked a Python SDK example.
@iennae
iennae requested review from a team as code owners November 17, 2026 18:48
@product-auto-label product-auto-label Bot added the api: spanner Issues related to the Spanner API. label Nov 17, 2026
@snippet-bot

snippet-bot Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Here is the summary of changes.

You are about to add 1 region tag.

This comment is generated by snippet-bot.
If you find problems with this result, please file an issue at:
https://github.com/googleapis/repo-automation-bots/issues.
To update this comment, add snippet-bot:force-run label or use the checkbox below:

  • Refresh this comment

@product-auto-label product-auto-label Bot added the samples Issues that are directly related to samples. label Nov 17, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

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.

Code Review

This pull request introduces a new module ml_predict_embeddings.py and its corresponding tests to generate text embeddings using Spanner's ML.PREDICT and rank products by cosine distance. The review feedback suggests making the project_id parameter and CLI argument optional to allow automatic inference from Application Default Credentials (ADC), and updating the error handling to log the resolved project ID.

Comment on lines +23 to +38
def generate_and_query_embeddings(
project_id: str, instance_id: str, database_id: str
) -> None:
"""Generates text embeddings via ML.PREDICT and ranks products by distance.

Generating embeddings in a read-only snapshot avoids holding read-write
locks during remote Vertex AI inference calls.

Args:
project_id: The Google Cloud project ID.
instance_id: The Spanner instance ID.
database_id: The Spanner database ID with TextEmbeddingModel and
Products registered.
"""
client = spanner.Client(project=project_id)
database = client.instance(instance_id).database(database_id)

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

Make project_id optional (str | None) to allow Spanner client to automatically infer the project ID from Application Default Credentials (ADC) if not provided. We can resolve the project ID using project_id or client.project to ensure error messages still print the correct project ID.

Suggested change
def generate_and_query_embeddings(
project_id: str, instance_id: str, database_id: str
) -> None:
"""Generates text embeddings via ML.PREDICT and ranks products by distance.
Generating embeddings in a read-only snapshot avoids holding read-write
locks during remote Vertex AI inference calls.
Args:
project_id: The Google Cloud project ID.
instance_id: The Spanner instance ID.
database_id: The Spanner database ID with TextEmbeddingModel and
Products registered.
"""
client = spanner.Client(project=project_id)
database = client.instance(instance_id).database(database_id)
def generate_and_query_embeddings(
project_id: str | None, instance_id: str, database_id: str
) -> None:
"""Generates text embeddings via ML.PREDICT and ranks products by distance.
Generating embeddings in a read-only snapshot avoids holding read-write
locks during remote Vertex AI inference calls.
Args:
project_id: The Google Cloud project ID.
instance_id: The Spanner instance ID.
database_id: The Spanner database ID with TextEmbeddingModel and
Products registered.
"""
client = spanner.Client(project=project_id)
resolved_project_id = project_id or client.project
database = client.instance(instance_id).database(database_id)
References
  1. When using argparse for a command-line script, the --project_id argument can be optional, as the project can be inferred from Application Default Credentials (ADC) if not provided.

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 suggestion! We are intentionally keeping project_id: str explicit in the sample signature so callers pass configuration directly rather than relying on implicit ADC resolution, and we intentionally omit project identifiers (project_id / client.project) from stdout and stderr output so project metadata is not echoed in logs.

Comment on lines +89 to +102
except exceptions.NotFound as err:
print(
f"error: database '{database_id}' or model on instance "
f"'{instance_id}' in project '{project_id}' was not found: "
f"{err.message}",
file=sys.stderr,
)
except exceptions.GoogleAPICallError as err:
print(
f"error: ML.PREDICT embedding query failed on database "
f"'{database_id}' in instance '{instance_id}' for project "
f"'{project_id}': {err.message}",
file=sys.stderr,
)

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

Use resolved_project_id instead of project_id in the error messages to ensure that the correct, resolved project ID is printed even if project_id was passed as None.

Suggested change
except exceptions.NotFound as err:
print(
f"error: database '{database_id}' or model on instance "
f"'{instance_id}' in project '{project_id}' was not found: "
f"{err.message}",
file=sys.stderr,
)
except exceptions.GoogleAPICallError as err:
print(
f"error: ML.PREDICT embedding query failed on database "
f"'{database_id}' in instance '{instance_id}' for project "
f"'{project_id}': {err.message}",
file=sys.stderr,
)
except exceptions.NotFound as err:
print(
f"error: database '{database_id}' or model on instance "
f"'{instance_id}' in project '{resolved_project_id}' was not found: "
f"{err.message}",
file=sys.stderr,
)
except exceptions.GoogleAPICallError as err:
print(
f"error: ML.PREDICT embedding query failed on database "
f"'{database_id}' in instance '{instance_id}' for project "
f"'{resolved_project_id}': {err.message}",
file=sys.stderr,
)

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! project_id is an explicit, required argument in this sample, so there is no separate resolved value to report; we also intentionally keep project identifiers out of stdout and stderr.

Comment on lines +122 to +125
"--project-id",
default=os.environ.get("GOOGLE_CLOUD_PROJECT", "example-project-id"),
help="Google Cloud project ID (default: $GOOGLE_CLOUD_PROJECT)",
)

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

Make the --project-id argument optional by defaulting to None (via os.environ.get("GOOGLE_CLOUD_PROJECT")) so that the project can be inferred from Application Default Credentials (ADC) if not provided.

    parser.add_argument(
        "--project-id",
        default=os.environ.get("GOOGLE_CLOUD_PROJECT"),
        help="Google Cloud project ID (default: inferred from Application Default Credentials or $GOOGLE_CLOUD_PROJECT)",
    )
References
  1. When using argparse for a command-line script, the --project_id argument can be optional, as the project can be inferred from Application Default Credentials (ADC) if not provided.

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 suggestion! We are intentionally keeping project_id: str explicit in the sample signature so callers pass configuration directly rather than relying on implicit ADC resolution, and we intentionally omit project identifiers (project_id / client.project) from stdout and stderr output so project metadata is not echoed in logs.

Prints short resource identifiers instead of full project-prefixed resource paths and omits project_id from diagnostic messages.
Base automatically changed from feat/spanner-vector-search-knn to main December 1, 2026 00:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api: spanner Issues related to the Spanner API. samples Issues that are directly related to samples.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants