Generate text embedding

This code sample demonstrates how to embed text with a pre-trained, foundational model.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

Python

Before trying this sample, follow the Python setup instructions in the Vertex AI quickstart using client libraries . For more information, see the Vertex AI Python API reference documentation .

To authenticate to Vertex AI, set up Application Default Credentials. For more information, see Set up authentication for a local development environment .

  from 
  
 __future__ 
  
 import 
 annotations 
 from 
  
 vertexai.language_models 
  
 import 
 TextEmbeddingInput 
 , 
 TextEmbeddingModel 
 def 
  
 embed_text 
 () 
 - 
> list 
 [ 
 list 
 [ 
 float 
 ]]: 
  
 """Embeds texts with a pre-trained, foundational model. 
 Returns: 
 A list of lists containing the embedding vectors for each input text 
 """ 
 # A list of texts to be embedded. 
 texts 
 = 
 [ 
 "banana muffins? " 
 , 
 "banana bread? banana muffins?" 
 ] 
 # The dimensionality of the output embeddings. 
 dimensionality 
 = 
 3072 
 # The task type for embedding. Check the available tasks in the model's documentation. 
 task 
 = 
 "RETRIEVAL_DOCUMENT" 
 model 
 = 
 TextEmbeddingModel 
 . 
 from_pretrained 
 ( 
 "gemini-embedding-001" 
 ) 
 kwargs 
 = 
 dict 
 ( 
 output_dimensionality 
 = 
 dimensionality 
 ) 
 if 
 dimensionality 
 else 
 {} 
 embeddings 
 = 
 [] 
 # gemini-embedding-001 takes one input at a time 
 for 
 text 
 in 
 texts 
 : 
 text_input 
 = 
 TextEmbeddingInput 
 ( 
 text 
 , 
 task 
 ) 
 embedding 
 = 
 model 
 . 
 get_embeddings 
 ([ 
 text_input 
 ], 
 ** 
 kwargs 
 ) 
 print 
 ( 
 embedding 
 ) 
 # Example response: 
 # [[0.006135190837085247, -0.01462465338408947, 0.004978656303137541, ...]] 
 embeddings 
 . 
 append 
 ( 
 embedding 
 [ 
 0 
 ] 
 . 
 values 
 ) 
 return 
 embeddings 
 

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser .

Create a Mobile Website
View Site in Mobile | Classic
Share by: