A partire dal 29 aprile 2025, i modelli Gemini 1.5 Pro e Gemini 1.5 Flash non sono disponibili nei progetti che non li hanno mai utilizzati, inclusi i nuovi progetti. Per maggiori dettagli, vedi Versioni e ciclo di vita dei modelli.
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Questo documento descrive come creare un embedding di testo utilizzando l'API Text Embeddings di Vertex AI.
L'API Vertex AI text embeddings utilizza rappresentazioni vettoriali dense: gemini-embedding-001,
ad esempio, utilizza vettori tridimensionali. I modelli di incorporamento vettoriale denso utilizzano metodi di deep learning simili a quelli utilizzati dai modelli linguistici di grandi dimensioni. A differenza dei vettori sparsi, che tendono a mappare direttamente le parole ai numeri, i vettori densi sono progettati per rappresentare meglio il significato di un testo. Il vantaggio di utilizzare gli incorporamenti vettoriali densi nell'AI generativa è che, anziché cercare corrispondenze dirette di parole o sintassi, puoi cercare meglio i passaggi che corrispondono al significato della query, anche se non utilizzano la stessa lingua.
I vettori sono normalizzati, quindi puoi utilizzare la somiglianza del coseno, il prodotto scalare o la distanza euclidea per fornire gli stessi ranking di somiglianza.
Per scoprire di più sui modelli di incorporamento di testo, consulta
Incorporamenti di testo.
Per informazioni sulle lingue supportate da ciascun modello di incorporamento, consulta Lingue di testo supportate.
Prima di iniziare
Sign in to your Google Cloud account. If you're new to
Google Cloud,
create an account to evaluate how our products perform in
real-world scenarios. New customers also get $300 in free credits to
run, test, and deploy workloads.
In the Google Cloud console, on the project selector page,
select or create a Google Cloud project.
Puoi ottenere incorporamenti di testo utilizzando i seguenti modelli:
Nome modello
Descrizione
Dimensioni di output
Lunghezza massima della sequenza
Lingue di testo supportate
gemini-embedding-001
Prestazioni all'avanguardia in attività in inglese, multilingue e di programmazione. Unifica i modelli precedentemente specializzati come text-embedding-005 e text-multilingual-embedding-002 e ottiene prestazioni migliori nei rispettivi domini. Per ulteriori dettagli, leggi il nostro report tecnico.
Per una qualità di incorporamento superiore, gemini-embedding-001 è il nostro modello di grandi dimensioni progettato per offrire le massime prestazioni. Tieni presente che
gemini-embedding-001 supporta un'istanza per richiesta.
Ottenere incorporamenti di testo per un frammento di testo
Puoi ottenere incorporamenti di testo per un frammento di testo utilizzando l'API Vertex AI o
l'SDK Vertex AI per Python.
Limiti dell'API
Per ogni richiesta, puoi inserire un massimo di 250 testi di input.
L'API ha un limite massimo di token di input di 20.000.
Gli input che superano questo limite generano un errore 400. Ogni singolo testo di input
è ulteriormente limitato a 2048 token; l'eventuale eccesso viene troncato automaticamente. Puoi
anche disattivare il troncamento silenzioso impostando autoTruncate su false.
Per impostazione predefinita, tutti i modelli producono un vettore di embedding a lunghezza intera. Per gemini-embedding-001,
questo vettore ha 3072 dimensioni, mentre altri modelli producono vettori a 768 dimensioni. Tuttavia, utilizzando il parametro output_dimensionality, gli utenti possono controllare le dimensioni del vettore di incorporamento di output.
La selezione di una dimensionalità di output più piccola può consentire di risparmiare spazio di archiviazione e
aumentare l'efficienza di calcolo per le applicazioni downstream, sacrificando
poco in termini di qualità.
Gli esempi riportati di seguito utilizzano il modello gemini-embedding-001.
Imposta le variabili di ambiente per utilizzare l'SDK Gen AI con Vertex AI:
# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values# with appropriate values for your project.exportGOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECTexportGOOGLE_CLOUD_LOCATION=globalexportGOOGLE_GENAI_USE_VERTEXAI=True
fromgoogleimportgenaifromgoogle.genai.typesimportEmbedContentConfigclient=genai.Client()response=client.models.embed_content(model="gemini-embedding-001",contents=["How do I get a driver's license/learner's permit?","How long is my driver's license valid for?","Driver's knowledge test study guide",],config=EmbedContentConfig(task_type="RETRIEVAL_DOCUMENT",# Optionaloutput_dimensionality=3072,# Optionaltitle="Driver's License",# Optional),)print(response)# Example response:# embeddings=[ContentEmbedding(values=[-0.06302902102470398, 0.00928034819662571, 0.014716853387653828, -0.028747491538524628, ... ],# statistics=ContentEmbeddingStatistics(truncated=False, token_count=13.0))]# metadata=EmbedContentMetadata(billable_character_count=112)
Aggiungere un embedding a un database vettoriale
Dopo aver generato l'embedding, puoi aggiungerlo a un database vettoriale, come Vector Search. Ciò consente il recupero a bassa latenza
ed è fondamentale man mano che le dimensioni dei dati aumentano.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 2025-09-04 UTC."],[],[],null,["# Get text embeddings\n\nThis document describes how to create a text embedding using the\nVertex AI\n[Text embeddings API](/vertex-ai/generative-ai/docs/model-reference/text-embeddings-api).\n\nVertex AI text embeddings API uses dense vector representations: [gemini-embedding-001](#supported-models),\nfor example, uses 3072-dimensional vectors. Dense vector embedding models use deep-learning methods similar to the ones used by large language models. Unlike sparse vectors, which tend to directly map words to numbers, dense vectors are designed to better represent the meaning of a piece of text. The benefit of using dense vector\nembeddings in generative AI is that instead of searching for direct word or\nsyntax matches, you can better search for passages that align to the meaning of\nthe query, even if the passages don't use the same language.\n\nThe vectors are normalized, so you can use cosine similarity, dot product, or\nEuclidean distance to provide the same similarity rankings.\n\n- To learn more about embeddings, see the [embeddings APIs overview](/vertex-ai/generative-ai/docs/embeddings).\n- To learn about text embedding models, see [Text embeddings](/vertex-ai/generative-ai/docs/model-reference/text-embeddings).\n- For information about which languages each embeddings model supports, see [Supported text languages](/vertex-ai/generative-ai/docs/model-reference/text-embeddings-api#supported_text_languages).\n\n| To see an example of getting text embeddings,\n| run the \"Getting Started with Text Embeddings + Vertex AI Vector Search\" notebook in one of the following\n| environments:\n|\n| [Open in Colab](https://colab.research.google.com/github/GoogleCloudPlatform/generative-ai/blob/main/embeddings/intro-textemb-vectorsearch.ipynb)\n|\n|\n| \\|\n|\n| [Open in Colab Enterprise](https://console.cloud.google.com/vertex-ai/colab/import/https%3A%2F%2Fraw.githubusercontent.com%2FGoogleCloudPlatform%2Fgenerative-ai%2Fmain%2Fembeddings%2Fintro-textemb-vectorsearch.ipynb)\n|\n|\n| \\|\n|\n| [Open\n| in Vertex AI Workbench](https://console.cloud.google.com/vertex-ai/workbench/deploy-notebook?download_url=https%3A%2F%2Fraw.githubusercontent.com%2FGoogleCloudPlatform%2Fgenerative-ai%2Fmain%2Fembeddings%2Fintro-textemb-vectorsearch.ipynb)\n|\n|\n| \\|\n|\n| [View on GitHub](https://github.com/GoogleCloudPlatform/generative-ai/blob/main/embeddings/intro-textemb-vectorsearch.ipynb)\n\nBefore you begin\n----------------\n\n- Sign in to your Google Cloud account. If you're new to Google Cloud, [create an account](https://console.cloud.google.com/freetrial) to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.\n- In the Google Cloud console, on the project selector page,\n select or create a Google Cloud project.\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n\n [Go to project selector](https://console.cloud.google.com/projectselector2/home/dashboard)\n-\n\n\n Enable the Vertex AI API.\n\n\n [Enable the API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com)\n\n- In the Google Cloud console, on the project selector page,\n select or create a Google Cloud project.\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n\n [Go to project selector](https://console.cloud.google.com/projectselector2/home/dashboard)\n-\n\n\n Enable the Vertex AI API.\n\n\n [Enable the API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com)\n\n1. [Choose a task type](/vertex-ai/generative-ai/docs/embeddings/task-types) for your embeddings job.\n\n\u003cbr /\u003e\n\nSupported models\n----------------\n\nYou can get text embeddings by using the following models:\n\nFor superior embedding quality, `gemini-embedding-001` is our large\nmodel designed to provide the highest performance. Note that\n`gemini-embedding-001` supports one instance per request.\n| **Note:** Only use the models as listed in the supported models table. Don't specify a model without the `@version` suffix or `@latest`. These model names are not considered valid.\n\nGet text embeddings for a snippet of text\n-----------------------------------------\n\nYou can get text embeddings for a snippet of text by using the Vertex AI API or\nthe Vertex AI SDK for Python.\n\n### API limits\n\nFor each request, you're limited to 250 input texts.\nThe API has a maximum input token limit of 20,000.\nInputs exceeding this limit result in a 400 error. Each individual input text\nis further limited to 2048 tokens; any excess is silently truncated. You can\nalso disable silent truncation by setting `autoTruncate` to `false`.\n\nFor more information, see [Text embedding limits](/vertex-ai/docs/quotas#text-embedding-limits).\n\n### Choose an embedding dimension\n\nAll models produce a full-length embedding vector by default. For `gemini-embedding-001`,\nthis vector has 3072 dimensions, and other models produce 768-dimensional vectors. However, by\nusing the `output_dimensionality` parameter, users can control the size of the output embedding vector.\nSelecting a smaller output dimensionality can save storage space and\nincrease computational efficiency for downstream applications, while sacrificing\nlittle in terms of quality.\n\nThe following examples use the `gemini-embedding-001` model. \n\n### Python\n\n#### Install\n\n```\npip install --upgrade google-genai\n```\n\n\nTo learn more, see the\n[SDK reference documentation](https://googleapis.github.io/python-genai/).\n\n\nSet environment variables to use the Gen AI SDK with Vertex AI:\n\n```bash\n# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values\n# with appropriate values for your project.\nexport GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT\nexport GOOGLE_CLOUD_LOCATION=global\nexport GOOGLE_GENAI_USE_VERTEXAI=True\n```\n\n\u003cbr /\u003e\n\n from google import genai\n from google.genai.types import EmbedContentConfig\n\n client = genai.Client()\n response = client.models.embed_content(\n model=\"gemini-embedding-001\",\n contents=[\n \"How do I get a driver's license/learner's permit?\",\n \"How long is my driver's license valid for?\",\n \"Driver's knowledge test study guide\",\n ],\n config=EmbedContentConfig(\n task_type=\"RETRIEVAL_DOCUMENT\", # Optional\n output_dimensionality=3072, # Optional\n title=\"Driver's License\", # Optional\n ),\n )\n print(response)\n # Example response:\n # embeddings=[ContentEmbedding(values=[-0.06302902102470398, 0.00928034819662571, 0.014716853387653828, -0.028747491538524628, ... ],\n # statistics=ContentEmbeddingStatistics(truncated=False, token_count=13.0))]\n # metadata=EmbedContentMetadata(billable_character_count=112)\n\n\u003cbr /\u003e\n\nAdd an embedding to a vector database\n-------------------------------------\n\nAfter you've generated your embedding you can add embeddings to a vector\ndatabase, like Vector Search. This enables low-latency retrieval,\nand is critical as the size of your data increases.\n\nTo learn more about Vector Search,\nsee [Overview of Vector Search](/vertex-ai/docs/vector-search/overview).\n\nWhat's next\n-----------\n\n- To learn more about rate limits, see [Generative AI on Vertex AI rate limits](/vertex-ai/generative-ai/docs/quotas).\n- To get batch predictions for embeddings, see [Get batch text embeddings predictions](/vertex-ai/generative-ai/docs/embeddings/batch-prediction-genai-embeddings)\n- To learn more about multimodal embeddings, see [Get multimodal embeddings](/vertex-ai/generative-ai/docs/embeddings/get-multimodal-embeddings)\n- To tune an embedding, see [Tune text embeddings](/vertex-ai/generative-ai/docs/models/tune-embeddings)\n- To learn more about the research behind `text-embedding-005` and `text-multilingual-embedding-002`, see the research paper [Gecko: Versatile Text Embeddings Distilled from Large Language Models](https://arxiv.org/abs/2403.20327)."]]