Repository navigation
Embeddings
Embeddings are vectors of numbers that capture the meaning of text (and, for some models, other media). Use them for semantic search, similarity, clustering, classification and retrieval-augmented generation. In this SDK you create an EmbeddingModel and call EmbedContentAsync or BatchEmbedContentAsync. The same API works on the Gemini Developer API and on Vertex AI.
Package: Google_GenerativeAI. For Microsoft.Extensions.AI IEmbeddingGenerator support, see Microsoft.Extensions.AI.
| Platform | Constant | Model | How the SDK calls it |
|---|---|---|---|
| Gemini API | GoogleAIModels.GeminiEmbedding2 |
models/gemini-embedding-2 |
embedContent / batchEmbedContents
|
| Gemini API | GoogleAIModels.GeminiEmbedding |
models/gemini-embedding-001 |
embedContent / batchEmbedContents
|
| Vertex AI | VertexAIModels.Embeddings.GeminiEmbedding001 |
gemini-embedding-001 |
embedContent (Vertex format) |
| Vertex AI | VertexAIModels.Gemini.TextEmbedding005 |
text-embedding-005 |
predict |
| Vertex AI |
VertexAIModels.Embeddings.TextMultilingualEmbedding002, MultimodalEmbedding, ... |
others | predict |
The SDK validates the model name against SupportedEmbedingModels.All and throws NotSupportedException for models that aren't listed. On Vertex AI, model names containing gemini (and maas models) use embedContent. All other models use predict. The response always comes back as the same EmbedContentResponse / BatchEmbedContentsResponse types.
Vertex AI location:
gemini-embedding-001andtext-embedding-005aren't served from theglobalendpoint. Create a separateVertexAIinstance with a regional location such asus-central1for embeddings (see Initialization).
using GenerativeAI;
using GenerativeAI.Types;
// Gemini API
var googleAI = new GoogleAi("YOUR_API_KEY");
var embeddingModel = googleAI.CreateEmbeddingModel(GoogleAIModels.GeminiEmbedding);
// Vertex AI (regional location)
var vertexAI = new VertexAI("your-project-id", "us-central1");
var vertexEmbeddingModel = vertexAI.CreateEmbeddingModel(VertexAIModels.Embeddings.GeminiEmbedding001);
// Or directly
var model2 = new EmbeddingModel("YOUR_API_KEY", GoogleAIModels.GeminiEmbedding2);Every method accepts an optional CancellationToken.
EmbedContentResponse response = await embeddingModel.EmbedContentAsync("This is a test embedding.");
List<float>? vector = response.Embedding?.Values;var content = new Content("This is a test embedding.", Roles.User);
EmbedContentResponse response = await embeddingModel.EmbedContentAsync(content);Use a request to set the task type, title and output size:
var request = new EmbedContentRequest
{
Content = new Content("Paris is the capital of France.", Roles.User),
TaskType = TaskType.RETRIEVAL_DOCUMENT,
Title = "Geography facts", // only allowed with RETRIEVAL_DOCUMENT
OutputDimensionality = 256 // truncate the vector to 256 dimensions
};
EmbedContentResponse response = await embeddingModel.EmbedContentAsync(request);
Console.WriteLine(response.Embedding?.Values?.Count); // 256var parts = new List<Part> { new Part { Text = "This is a test embedding." } };
EmbedContentResponse response = await embeddingModel.EmbedContentAsync(parts);Note: This overload joins all strings into one content and returns one embedding. To get one embedding per string, use
BatchEmbedContentAsync.
var messages = new List<string> { "This is a test embedding.", "Another test embedding." };
EmbedContentResponse response = await embeddingModel.EmbedContentAsync(messages); // single embeddingReturns one embedding per request, in order. This is the most efficient way to embed many inputs:
var requests = new List<EmbedContentRequest>
{
new EmbedContentRequest { Content = new Content("This is a test embedding.", Roles.User), TaskType = TaskType.RETRIEVAL_DOCUMENT },
new EmbedContentRequest { Content = new Content("Another test embedding.", Roles.User), TaskType = TaskType.RETRIEVAL_DOCUMENT }
};
BatchEmbedContentsResponse response = await embeddingModel.BatchEmbedContentAsync(requests);
foreach (var embedding in response.Embeddings ?? new List<ContentEmbedding>())
{
Console.WriteLine(embedding.Values?.Count);
}var contents = new List<Content>
{
new Content("This is a test embedding.", Roles.User),
new Content("Another test embedding.", Roles.User)
};
BatchEmbedContentsResponse response = await embeddingModel.BatchEmbedContentAsync(contents);TaskType tells the model what the embedding will be used for, which improves quality for that use:
| Value | Use for |
|---|---|
RETRIEVAL_QUERY |
Search queries |
RETRIEVAL_DOCUMENT |
Documents being indexed (the only type that allows Title) |
SEMANTIC_SIMILARITY |
Comparing text similarity |
CLASSIFICATION |
Text classification |
CLUSTERING |
Clustering |
CODE_RETRIEVAL_QUERY |
Code search queries |
QUESTION_ANSWERING |
Questions in a QA system |
FACT_VERIFICATION |
Statements to verify |
These EmbedContentRequest properties are only sent on Vertex AI. On the Gemini API they throw NotSupportedException.
| Property | Description |
|---|---|
AutoTruncate |
Truncate input that is longer than the model's limit instead of failing |
DocumentOcr |
Run OCR on document input (Gemini embedding models only) |
AudioTrackExtraction |
Extract the audio track from video input (Gemini embedding models only) |
MimeType |
MIME type of the input (predict models) |
var vertexAI = new VertexAI("your-project-id", "us-central1");
var textEmbedding = vertexAI.CreateEmbeddingModel(VertexAIModels.Gemini.TextEmbedding005);
var response = await textEmbedding.EmbedContentAsync(new EmbedContentRequest
{
Content = new Content("What is the capital of France?", Roles.User),
TaskType = TaskType.RETRIEVAL_QUERY,
OutputDimensionality = 128,
AutoTruncate = true
});
var stats = response.Embedding?.Statistics; // TokenCount, TruncatedRules for Vertex predict models (such as text-embedding-005): in a batch, every request must use the same OutputDimensionality and AutoTruncate. DocumentOcr and AudioTrackExtraction aren't allowed. Vertex maas embedding models accept only one content per batch request.
-
EmbedContentResponse.Embeddingis aContentEmbeddingwithValues(List<float>) and optionalStatistics(TokenCount,Truncated,TokensDetails). -
BatchEmbedContentsResponse.Embeddingsis aList<ContentEmbedding>, one per input.
API errors throw GenerativeAI.Exceptions.ApiException. If you use a model the region doesn't serve, the API returns an error. Switch to a regional location.
Getting Started
- Initialization
- Authentication
- Configuration & Error Handling
- Supported Models
- Migration Guide (v4)
- Release Notes (v4)
Core Features
- Generate Content
- Chat Session
- Streaming
- Multimodal Features
- JSON Mode
- Function Calling
- Embeddings
- Context Caching
Gemini APIs
- Interactions API
- Multimodal Live API
- File Search
- Batch API
- Model Tuning
- Webhooks
- Agent APIs
- Image Generation
- Video Generation
- Speech Generation
- Files Client
- Model Client
Vertex AI
Integrations
Guides
Legacy