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:

- [Text embeddings API](https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/models/text-embeddings-api)

## Code sample

### Python


Before trying this sample, follow the Python setup instructions in the
[Vertex AI quickstart using
client libraries](https://docs.cloud.google.com/vertex-ai/docs/start/client-libraries).


For more information, see the
[Vertex AI Python API
reference documentation](https://docs.cloud.google.com/python/docs/reference/aiplatform/latest).


To authenticate to Vertex AI, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-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](https://docs.cloud.google.com/docs/samples?product=generativeaionvertexai).