Repository navigation
Conversation
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.
|
Here is the summary of changes. You are about to add 1 region tag.
This comment is generated by snippet-bot.
|
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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.
| 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
- 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.
There was a problem hiding this comment.
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.
| 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, | ||
| ) |
There was a problem hiding this comment.
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.
| 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, | |
| ) |
There was a problem hiding this comment.
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.
| "--project-id", | ||
| default=os.environ.get("GOOGLE_CLOUD_PROJECT", "example-project-id"), | ||
| help="Google Cloud project ID (default: $GOOGLE_CLOUD_PROJECT)", | ||
| ) |
There was a problem hiding this comment.
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
- 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.
There was a problem hiding this comment.
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.
Description
Developers building semantic search pipelines on Cloud Spanner had only SQL tutorials for invoking
ML.PREDICTon a registered Vertex AI embedding model and unpackingembeddings.valuesin Python.Adds
spanner_ml_predict_embeddingsshowing parameterized text binding and vector output extraction through a Spanner snapshot.Checklist
Testing
Compliance & Style
spanner/, which the default repository owners cover.Post-Approval Actions