mirror of
https://github.com/GoogleCloudPlatform/vertex-ai-samples.git
synced 2026-09-26 14:42:04 +00:00
* refactor: remove runtime reboot * Remove spaces * Use %pip instead * Update model path * Update BQ path * Downgrade numpy for backfoward compability
13 KiB
13 KiB
In [ ]:
# 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
#
# https://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.In [ ]:
%pip install --quiet --upgrade google-cloud-aiplatformIn [ ]:
import sys
if "google.colab" in sys.modules:
from google.colab import auth
auth.authenticate_user()In [ ]:
PROJECT_ID = "[your-project-id]" # @param {type:"string"}
LOCATION = "us-central1" # @param {type:"string"}
from google.cloud import aiplatform
aiplatform.init(project=PROJECT_ID, location=LOCATION)In [ ]:
from vertexai.language_models import TextEmbeddingInput, TextEmbeddingModelIn [ ]:
# @title { run: "auto" }
MODEL = "text-embedding-004" # @param ["text-embedding-004", "text-multilingual-embedding-002","text-embedding-preview-0815","text-embedding-preview-0409", "text-multilingual-embedding-preview-0409", "textembedding-gecko@003", "textembedding-gecko-multilingual@001"]
TASK = "RETRIEVAL_DOCUMENT" # @param ["RETRIEVAL_QUERY", "RETRIEVAL_DOCUMENT", "SEMANTIC_SIMILARITY", "CLASSIFICATION", "CLUSTERING", "QUESTION_ANSWERING", "FACT_VERIFICATION", "CODE_RETRIEVAL_QUERY"]
TEXT = "Banana Muffin?" # @param {type:"string"}
TITLE = "" # @param {type:"string"}
OUTPUT_DIMENSIONALITY = 256 # @param [1, 768, "None"] {type:"raw", allow-input:true}
if not MODEL:
raise ValueError("MODEL must be specified.")
if not TEXT:
raise ValueError("TEXT must be specified.")
if TITLE and TASK != "RETRIEVAL_DOCUMENT":
raise ValueError("TITLE can only be specified for TASK 'RETRIEVAL_DOCUMENT'")
if OUTPUT_DIMENSIONALITY is not None and MODEL not in [
"text-embedding-004",
"text-multilingual-embedding-002",
"text-embedding-preview-0815",
"text-embedding-preview-0409",
"text-multilingual-embedding-preview-0409",
]:
raise ValueError(f"OUTPUT_DIMENTIONALITY cannot be specified for model '{MODEL}'.")
if TASK in ["QUESTION_ANSWERING", "FACT_VERIFICATION"] and MODEL not in [
"text-embedding-004",
"text-multilingual-embedding-002",
"text-embedding-preview-0815",
"text-embedding-preview-0409",
"text-multilingual-embedding-preview-0409",
]:
raise ValueError(f"TASK '{TASK}' is not valid for model '{MODEL}'.")
if TASK in ["CODE_RETRIEVAL_QUERY"] and MODEL not in [
"text-embedding-preview-0815",
]:
raise ValueError(f"TASK '{TASK}' is not valid for model '{MODEL}'.")In [ ]:
def embed_text(
model_name: str,
task_type: str,
text: str,
title: str = "",
output_dimensionality=None,
) -> list:
"""Generates a text embedding with a Large Language Model."""
model = TextEmbeddingModel.from_pretrained(model_name)
text_embedding_input = TextEmbeddingInput(
task_type=task_type, title=title, text=text
)
kwargs = (
dict(output_dimensionality=output_dimensionality)
if output_dimensionality
else {}
)
embeddings = model.get_embeddings([text_embedding_input], **kwargs)
return embeddings[0].values
# Get a text embedding for a downstream task.
embedding = embed_text(
model_name=MODEL,
task_type=TASK,
text=TEXT,
title=TITLE,
output_dimensionality=OUTPUT_DIMENSIONALITY,
)
print(len(embedding)) # Expected value: {OUTPUT_DIMENSIONALITY}.

