How to Generate Text Embeddings in ASP.NET Core 10 Using C# and Microsoft.Extensions.AI – Complete Guide (2026)
How to Generate Text Embeddings in ASP.NET Core 10 Using C# and Microsoft.Extensions.AI – Complete Guide (2026)
A search for “fix my vehicle” should be able to find an article about car repair even when the words do not match exactly. Text embeddings give an application a numeric representation it can compare for that kind of relatedness. They are useful building blocks for search, recommendation, clustering and retrieval-augmented generation, but a vector is not a factual answer or a permission check.
This tutorial generates text embeddings in ASP.NET Core 10 using C# and Microsoft.Extensions.AI. It uses a real provider adapter behind IEmbeddingGenerator, exposes single-text and document-batch endpoints, and ranks a small request-local candidate set with an explicit cosine implementation.
How do you generate embeddings with Microsoft.Extensions.AI?
Create a compatible embedding provider client, adapt it to IEmbeddingGenerator<string, Embedding<float>>, and register that interface with dependency injection. Call GenerateAsync with a bounded list of strings and a cancellation token. Read each Embedding<float>.Vector, verify its dimensions, and compare only vectors from a compatible embedding configuration.
1. What are text embeddings and vector representations?
An embedding model maps input text into a fixed-length array of numbers. The model’s learned representation can place related inputs in directions that are useful for comparison. Individual coordinates usually do not have simple human labels such as “car” or “finance,” and an embedding does not preserve a readable copy of a sentence.
The Microsoft embeddings overview introduces their role in AI applications. An embedding model is different from a chat model: the embedding endpoint returns numeric vectors, while a chat endpoint generates language. You do not need an agent, chat history or a vector database just to generate and compare a few embeddings.
| Keyword / lexical search | Embedding-based similarity |
|---|---|
| Matches terms, identifiers and lexical structure | Compares learned vector representations |
| Strong for exact SKUs, error codes and names | Useful for paraphrases and related wording |
| Often straightforward to explain term matches | Needs evaluation because relatedness can be unexpected |
| Can be combined with filters and ranking | Still requires authorization, filters and a ranking policy |
Neither technique wins every task. A product code such as KB-01 is often better served by exact matching. A support question may benefit from semantic retrieval. Hybrid retrieval can combine lexical evidence and dense-vector ranking, but this tutorial does not implement a hybrid search engine.
Typical uses include finding related documentation, grouping similar support tickets, suggesting related articles and selecting passages for a RAG prompt. Similarity is evidence for retrieval, not proof that a document answers the question correctly. A highly similar result can still be obsolete, contradictory or inaccessible to the caller.
2. Embedding dimensions and cosine similarity in C#
A dimension is one coordinate in the vector. This tutorial requests 512 coordinates from text-embedding-3-small; its documented default is 1536. A shorter vector reduces raw storage and comparison work, but quality must be evaluated for the task. A 512-dimensional vector from another model is not automatically comparable.
For nonzero vectors a and b, cosine similarity is their dot product divided by the product of their lengths:
cosine(a,b) = sum(a[i] * b[i]) / (sqrt(sum(a[i]^2)) * sqrt(sum(b[i]^2)))
The mathematical range is -1 to 1. Equal direction gives 1, perpendicular toy vectors give 0, and opposite direction gives -1. A score is not a probability or “percentage of shared meaning.” Real text-embedding distributions and useful thresholds depend on the model and dataset; zero does not universally mean unrelated text.
namespace Embeddings.Api;
public static class VectorMath
{
public static double Cosine(ReadOnlySpan<float> a, ReadOnlySpan<float> b)
{
if (a.Length == 0 || a.Length != b.Length)
throw new ArgumentException("Vectors must be non-empty and have equal dimensions.");
double dot = 0, normA = 0, normB = 0;
for (var i = 0; i < a.Length; i++)
{
if (!float.IsFinite(a[i]) || !float.IsFinite(b[i]))
throw new ArgumentException("Vector coordinates must be finite.");
dot += (double)a[i] * b[i];
normA += (double)a[i] * a[i];
normB += (double)b[i] * b[i];
}
if (normA == 0 || normB == 0)
throw new ArgumentException("Cosine is undefined for a zero vector.");
return Math.Clamp(dot / (Math.Sqrt(normA) * Math.Sqrt(normB)), -1.0, 1.0);
}
}The implementation accumulates in double precision, rejects unequal lengths and non-finite values, and rejects zero vectors because their cosine is undefined. Clamping corrects tiny floating-point excursions outside the mathematical range; it must not hide invalid inputs.
| Toy vectors a and b | Expected cosine |
|---|---|
| (1,0), (1,0) | 1 |
| (1,0), (0,1) | 0 |
| (1,0), (-1,0) | -1 |
| (1,0), (1,1) | 1 / sqrt(2), approximately 0.7071067812 |
These four arithmetic results were independently checked with Python. That validates the toy calculations, not execution of this C# class or any provider-generated embedding. OpenAI’s embedding guide discusses similarity and supported dimensionality settings.
3. Microsoft.Extensions.AI architecture and provider compatibility
The Microsoft.Extensions.AI libraries separate application abstractions from provider implementations. IEmbeddingGenerator accepts input values and returns typed embeddings. Embedding<float> exposes vector data through ReadOnlyMemory<float>. The service below depends on that interface rather than calling a provider SDK throughout the application.
At the research date, Microsoft.Extensions.AI.OpenAI 10.11.0 is a stable release compatible with .NET 10. It brings the OpenAI SDK and compatible abstraction dependencies transitively. Do not copy a prerelease switch merely because an older quickstart still shows one.
| Provider choice | What must be configured | Compatibility caution |
|---|---|---|
| OpenAI, used here | Provider API key and an embedding model ID | A chat model ID is not an embedding model |
| Azure OpenAI / Foundry | Supported client, endpoint, identity and model deployment | Deployment name and authentication differ from public OpenAI |
| Local embedding provider | A compatible adapter and an installed embedding-capable model | A local chat model alone is insufficient |
| Another hosted provider | Its maintained IEmbeddingGenerator adapter or a reviewed implementation | Input type, dimensions, normalization and limits may differ |
The AsIEmbeddingGenerator API adapts an OpenAI EmbeddingClient. The model page documents the selected model. Azure-specific setup is described in Microsoft’s Azure embedding guide; it is an alternative integration, not a drop-in API-key substitution.
Provider abstraction does not guarantee identical embedding spaces. Persist provider identity, model/deployment version, dimensionality and preprocessing version alongside stored vectors. Changing any meaningful part of that configuration normally requires a deliberate re-embedding and index migration plan.
4. Create the ASP.NET Core 10 project and configure secrets
Install a serviced .NET 10 SDK, an editor supporting it, and Postman or curl. You need an OpenAI API project with access and budget for the selected embedding model. This project does not use a database. The demo API key and provider API key are separate secrets.
mkdir EmbeddingsDemo
cd EmbeddingsDemo
dotnet new web -n Embeddings.Api -f net10.0
cd Embeddings.Api<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>Embeddings.Api.LocalDevelopment</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" Version="10.11.0" />
</ItemGroup>
</Project>Replace the generated project file and create the remaining C# files in Embeddings.Api. Keep UserSecretsId in the project file. The adapter package supplies the interfaces needed by this example; the higher-level Microsoft.Extensions.AI package is optional when adding its additional pipeline middleware.
{
"Embeddings": { "Model": "text-embedding-3-small", "Dimensions": 512 },
"OpenAI": { "ApiKey": "" },
"Demo": { "ApiKey": "" },
"Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } },
"AllowedHosts": "localhost"
}dotnet user-secrets set "OpenAI:ApiKey" "YOUR_OPENAI_PROJECT_API_KEY"
dotnet user-secrets set "Demo:ApiKey" "YOUR_DIFFERENT_RANDOM_DEMO_KEY_AT_LEAST_32_CHARACTERS"Never paste the provider key into a request sent to this API. Postman uses only the demo key. For deployment, use your controlled secret provider and environment keys such as OpenAI__ApiKey and Demo__ApiKey. User secrets are a development mechanism, not an encrypted production vault; see Microsoft’s secret-storage guidance.
The related OpenAI API integration tutorial covers the broader provider setup. This article focuses on numeric embeddings rather than generated answers.
5. Request DTOs, batching bounds and input validation
namespace Embeddings.Api;
public sealed record EmbedRequest(string? Text, bool IncludeVector = false);
public sealed record DocumentInput(string? Id, string? Text);
public sealed record BatchRequest(DocumentInput[]? Documents, bool IncludeVectors = false);
public sealed record SimilarityRequest(string? Query, DocumentInput[]? Documents, int TopK = 3);
public sealed record EmbeddingItem(string Id, float[]? Vector);
public sealed record EmbeddingResponse(string Model, int Dimensions, EmbeddingItem[] Items);
public sealed record SimilarityHit(string Id, double Score);
public sealed record SimilarityResponse(string Model, int Dimensions, SimilarityHit[] Results);
public sealed record EmbeddingSettings(string Model, int Dimensions);
public sealed class ApiFailure(int status, string safeMessage) : Exception(safeMessage)
{
public int Status { get; } = status;
}namespace Embeddings.Api;
public static class InputPolicy
{
public static string Text(string? value)
{
if (string.IsNullOrWhiteSpace(value) || value.Length > 2000)
throw new ApiFailure(400, "Each text must contain 1–2000 characters.");
return value; // Preserve meaningful whitespace; do not silently rewrite text.
}
public static DocumentInput[] Documents(DocumentInput[]? documents)
{
if (documents is null || documents.Length is < 1 or > 8)
throw new ApiFailure(400, "Supply 1–8 documents.");
var ids = new HashSet<string>(StringComparer.Ordinal);
foreach (var document in documents)
{
if (document is null || string.IsNullOrWhiteSpace(document.Id)
|| document.Id.Length > 64 || !ids.Add(document.Id))
throw new ApiFailure(400, "Document IDs must be non-empty, unique and at most 64 characters.");
_ = Text(document.Text);
}
return documents;
}
}The input policy allows up to eight documents, requires unique IDs, rejects blank text and limits each text to 2,000 UTF-16 characters. The similarity endpoint adds one query, so it can submit up to nine strings in one provider call. The character cap is an application guard, not a tokenizer or a promise about every provider’s token accounting.
The sample preserves input text rather than silently removing punctuation or rewriting whitespace. If production preprocessing changes, version it. A query and document should be embedded with a compatible model-specific preprocessing policy; some retrieval models require different query/document prefixes, while this example does not add such prefixes.
By default the API returns metadata with null vector fields to keep responses compact. IncludeVector or IncludeVectors explicitly requests the full arrays. Hiding the vector does not avoid the provider call or its token cost.
6. Complete embedding service: single text, documents and similarity
using System.Diagnostics;
using Microsoft.Extensions.AI;
namespace Embeddings.Api;
public sealed class EmbeddingService(IEmbeddingGenerator<string, Embedding<float>> generator,
EmbeddingSettings settings, ILogger<EmbeddingService> logger)
{
private async Task<float[][]> GenerateAsync(string[] texts, CancellationToken ct)
{
using var budget = CancellationTokenSource.CreateLinkedTokenSource(ct);
budget.CancelAfter(TimeSpan.FromSeconds(30));
var timer = Stopwatch.StartNew();
try
{
var generated = await generator.GenerateAsync(texts,
new EmbeddingGenerationOptions { Dimensions = settings.Dimensions }, budget.Token);
if (generated.Count != texts.Length)
throw new ApiFailure(502, "Provider returned an unexpected vector count.");
var vectors = generated.Select(x => x.Vector.ToArray()).ToArray();
foreach (var vector in vectors)
{
if (vector.Length != settings.Dimensions)
throw new ApiFailure(502, "Provider returned unexpected dimensions.");
try { _ = VectorMath.Cosine(vector, vector); }
catch (ArgumentException)
{ throw new ApiFailure(502, "Provider returned an invalid vector."); }
}
logger.LogInformation("Generated {Count} vectors, {Dimensions} dimensions, {ElapsedMs} ms",
vectors.Length, settings.Dimensions, timer.ElapsedMilliseconds);
return vectors;
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{ throw new ApiFailure(504, "Embedding generation exceeded its time budget."); }
}
public async Task<EmbeddingResponse> EmbedAsync(EmbedRequest request, CancellationToken ct)
{
var text = InputPolicy.Text(request.Text);
var vectors = await GenerateAsync([text], ct);
return new(settings.Model, settings.Dimensions,
[new("input", request.IncludeVector ? vectors[0] : null)]);
}
public async Task<EmbeddingResponse> BatchAsync(BatchRequest request, CancellationToken ct)
{
var documents = InputPolicy.Documents(request.Documents);
var vectors = await GenerateAsync(documents.Select(x => x.Text!).ToArray(), ct);
return new(settings.Model, settings.Dimensions, documents.Select((d, i) =>
new EmbeddingItem(d.Id!, request.IncludeVectors ? vectors[i] : null)).ToArray());
}
public async Task<SimilarityResponse> SimilarityAsync(SimilarityRequest request, CancellationToken ct)
{
var query = InputPolicy.Text(request.Query);
var documents = InputPolicy.Documents(request.Documents);
if (request.TopK < 1 || request.TopK > documents.Length)
throw new ApiFailure(400, "TopK must be between 1 and the number of documents.");
var inputs = new[] { query }.Concat(documents.Select(x => x.Text!)).ToArray();
var vectors = await GenerateAsync(inputs, ct);
var hits = documents.Select((d, i) => new SimilarityHit(d.Id!,
VectorMath.Cosine(vectors[0], vectors[i + 1])))
.OrderByDescending(x => x.Score).ThenBy(x => x.Id, StringComparer.Ordinal)
.Take(request.TopK).ToArray();
return new(settings.Model, settings.Dimensions, hits);
}
}The IEmbeddingGenerator guide and GenerateAsync reference show the collection-based asynchronous contract. The service requests dimensions through EmbeddingGenerationOptions and passes a linked cancellation token through generation.
It verifies the number of returned embeddings, their dimensions and finite nonzero contents before associating them with document IDs. The selected provider adapter returns the embeddings for the supplied input sequence; a replacement adapter must preserve that contract. The official adapter source is useful when diagnosing provider-specific mapping.
The similarity endpoint embeds the query and supplied documents together, compares the query vector with each document vector, then returns the highest scores. Ties are ordered by document ID for a deterministic tie policy. It is a small exhaustive, request-local comparison, not an approximate-nearest-neighbor index or persistent search service.
All provider work is inside a 30-second cooperative budget. A caller disconnect propagates cancellation. A timeout does not guarantee the remote service stopped computation or billing immediately. Failed batches do not return a silently partial set of results.
7. Dependency injection, error handling and complete Program.cs
using Microsoft.AspNetCore.Diagnostics;
using System.ClientModel;
namespace Embeddings.Api;
public sealed class ApiErrorHandler(ILogger<ApiErrorHandler> logger) : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(HttpContext http, Exception error, CancellationToken ct)
{
if (http.RequestAborted.IsCancellationRequested) return true;
var status = error switch
{
ApiFailure safe => safe.Status,
BadHttpRequestException => 400,
ClientResultException provider when provider.Status == 429 => 503,
ClientResultException or HttpRequestException => 502,
_ => 500
};
logger.LogWarning("Embedding request failed: {Type}, status {Status}, trace {TraceId}",
error.GetType().Name, status, http.TraceIdentifier);
if (status == 503) http.Response.Headers.RetryAfter = "1";
http.Response.Headers.CacheControl = "no-store";
await Results.Problem(statusCode: status,
title: status >= 500 ? "Embedding operation unavailable." : "Request rejected.",
detail: error is ApiFailure known ? known.Message : null,
extensions: new Dictionary<string, object?> { ["traceId"] = http.TraceIdentifier })
.ExecuteAsync(http);
return true;
}
}using System.Security.Cryptography;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.AI;
using OpenAI;
using Embeddings.Api;
var builder = WebApplication.CreateBuilder(args);
string Required(string key) => !string.IsNullOrWhiteSpace(builder.Configuration[key])
? builder.Configuration[key]! : throw new InvalidOperationException(Program.csusing System.Security.Cryptography;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.RateLimiting;
using Microsoft.Extensions.AI;
using OpenAI;
using Embeddings.Api;
var builder = WebApplication.CreateBuilder(args);
string Required(string key) => !string.IsNullOrWhiteSpace(builder.Configuration[key])
? builder.Configuration[key]! : throw new InvalidOperationException($"Configure {key}.");
var providerKey = Required("OpenAI:ApiKey");
var demoKey = Required("Demo:ApiKey");
if (demoKey.Length is < 32 or > 256)
throw new InvalidOperationException("Use a random demo API key of 32–256 characters.");
var model = Required("Embeddings:Model");
var dimensions = builder.Configuration.GetValue<int>("Embeddings:Dimensions");
// Deliberately pin this tutorial's model contract; other providers need a reviewed adapter.
if (model != "text-embedding-3-small" || dimensions is < 1 or > 1536)
throw new InvalidOperationException("Use text-embedding-3-small and dimensions 1–1536.");
builder.WebHost.ConfigureKestrel(o => o.Limits.MaxRequestBodySize = 128 * 1024);
builder.Services.AddSingleton(new EmbeddingSettings(model, dimensions));
builder.Services.AddSingleton<IEmbeddingGenerator<string, Embedding<float>>>(_ =>
new OpenAIClient(providerKey).GetEmbeddingClient(model).AsIEmbeddingGenerator());
builder.Services.AddScoped<EmbeddingService>();
builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler<ApiErrorHandler>();
builder.Services.ConfigureHttpJsonOptions(o =>
o.SerializerOptions.UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow);
builder.Services.AddRateLimiter(o =>
{
o.RejectionStatusCode = 429;
o.AddConcurrencyLimiter("provider", options =>
{ options.PermitLimit = 4; options.QueueLimit = 0; });
});
var expectedKeyHash = SHA256.HashData(Encoding.UTF8.GetBytes(demoKey));
var app = builder.Build();
app.UseExceptionHandler();
app.UseRouting();
app.Use(async (http, next) =>
{
http.Response.Headers.CacheControl = "no-store";
if (!http.Request.Headers.TryGetValue("X-Demo-Key", out var value)
|| value.Count != 1 || value.ToString().Length > 256
|| !CryptographicOperations.FixedTimeEquals(expectedKeyHash,
SHA256.HashData(Encoding.UTF8.GetBytes(value.ToString()))))
{ http.Response.StatusCode = 401; return; }
await next(http);
});
app.UseRateLimiter();
var api = app.MapGroup("/api").RequireRateLimiting("provider");
api.MapPost("/embeddings", (EmbedRequest request, EmbeddingService service, CancellationToken ct)
=> service.EmbedAsync(request, ct));
api.MapPost("/embeddings/batch", (BatchRequest request, EmbeddingService service, CancellationToken ct)
=> service.BatchAsync(request, ct));
api.MapPost("/similarity", (SimilarityRequest request, EmbeddingService service, CancellationToken ct)
=> service.SimilarityAsync(request, ct));
app.Run();
quot;Configure {key}.");
var providerKey = Required("OpenAI:ApiKey");
var demoKey = Required("Demo:ApiKey");
if (demoKey.Length is < 32 or > 256)
throw new InvalidOperationException("Use a random demo API key of 32–256 characters.");
var model = Required("Embeddings:Model");
var dimensions = builder.Configuration.GetValue<int>("Embeddings:Dimensions");
// Deliberately pin this tutorial's model contract; other providers need a reviewed adapter.
if (model != "text-embedding-3-small" || dimensions is < 1 or > 1536)
throw new InvalidOperationException("Use text-embedding-3-small and dimensions 1–1536.");
builder.WebHost.ConfigureKestrel(o => o.Limits.MaxRequestBodySize = 128 * 1024);
builder.Services.AddSingleton(new EmbeddingSettings(model, dimensions));
builder.Services.AddSingleton<IEmbeddingGenerator<string, Embedding<float>>>(_ =>
new OpenAIClient(providerKey).GetEmbeddingClient(model).AsIEmbeddingGenerator());
builder.Services.AddScoped<EmbeddingService>();
builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler<ApiErrorHandler>();
builder.Services.ConfigureHttpJsonOptions(o =>
o.SerializerOptions.UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow);
builder.Services.AddRateLimiter(o =>
{
o.RejectionStatusCode = 429;
o.AddConcurrencyLimiter("provider", options =>
{ options.PermitLimit = 4; options.QueueLimit = 0; });
});
var expectedKeyHash = SHA256.HashData(Encoding.UTF8.GetBytes(demoKey));
var app = builder.Build();
app.UseExceptionHandler();
app.UseRouting();
app.Use(async (http, next) =>
{
http.Response.Headers.CacheControl = "no-store";
if (!http.Request.Headers.TryGetValue("X-Demo-Key", out var value)
|| value.Count != 1 || value.ToString().Length > 256
|| !CryptographicOperations.FixedTimeEquals(expectedKeyHash,
SHA256.HashData(Encoding.UTF8.GetBytes(value.ToString()))))
{ http.Response.StatusCode = 401; return; }
await next(http);
});
app.UseRateLimiter();
var api = app.MapGroup("/api").RequireRateLimiting("provider");
api.MapPost("/embeddings", (EmbedRequest request, EmbeddingService service, CancellationToken ct)
=> service.EmbedAsync(request, ct));
api.MapPost("/embeddings/batch", (BatchRequest request, EmbeddingService service, CancellationToken ct)
=> service.BatchAsync(request, ct));
api.MapPost("/similarity", (SimilarityRequest request, EmbeddingService service, CancellationToken ct)
=> service.SimilarityAsync(request, ct));
app.Run();The singleton generator is created through a DI factory, and the container owns its lifetime. The application service is scoped. The OpenAI SDK client is designed for reuse; no provider client or secret is constructed from user-supplied model names or URLs.
The API deliberately pins the tutorial’s model contract and permits a configured output size up to that model’s default dimensions. It checks the actual returned size rather than trusting configuration alone. EmbeddingGenerationOptions can represent provider-independent options, but an adapter may support only some of them; see the options reference.
The shared X-Demo-Key gate is local teaching authentication, not a production identity system. Replace it with an identity provider, authorization and per-tenant quotas before exposing a paid endpoint. The related JWT authentication guide covers that boundary.
The concurrency limiter admits four requests per process without a queue. It is not a token budget, requests-per-minute quota or fleet-wide limit. The ASP.NET Core rate-limiting guide explains the middleware. Responses use no-store and safe errors; prompt text, keys and vectors are not logged. For error-response concepts, see the related global exception-handling tutorial.
8. Build and test the embedding API with Postman
Execution disclosure: these are local instructions. No live embedding request, C# build or API test was executed while preparing the draft.
dotnet restore --use-lock-file
dotnet build --no-restore
$env:ASPNETCORE_ENVIRONMENT = 'Development'
dotnet run --no-launch-profile -- --urls "http://localhost:5092"The example listens on loopback HTTP for local development. Use HTTPS or a trusted HTTPS reverse proxy for deployment, configure the real hostname, and protect the app’s network boundary. In Postman, set baseUrl=http://localhost:5092 and keep demoKey private. Add Content-Type: application/json and X-Demo-Key: {{demoKey}}.
Generate an embedding for one text
POST {{baseUrl}}/api/embeddings:
{
"text": "ASP.NET Core APIs support dependency injection.",
"includeVector": false
}Expected response shape on success is 200 with the configured model, actual validated dimensionality and one item. This metadata-only example deliberately contains no invented provider coordinates:
{
"model": "text-embedding-3-small",
"dimensions": 512,
"items": [ { "id": "input", "vector": null } ]
}Set includeVector to true to inspect the actual vector. The array should contain 512 finite coordinates under this configuration; do not replace them with a hand-written numeric example and present it as model output.
Embed multiple documents
POST {{baseUrl}}/api/embeddings/batch:
{
"documents": [
{ "id": "api", "text": "Build web APIs with ASP.NET Core and C#." },
{ "id": "garden", "text": "Water indoor plants according to their needs." }
],
"includeVectors": false
}Expect two items with the input IDs and the same configured model/dimensions. Vector fields remain null unless requested. Try duplicate IDs, an empty array or a blank document text and confirm rejection before a provider call.
Rank candidates by semantic similarity
POST {{baseUrl}}/api/similarity:
{
"query": "How can I create a web API in C#?",
"documents": [
{ "id": "dotnet", "text": "Create HTTP endpoints with ASP.NET Core and C#." },
{ "id": "garden", "text": "Growing herbs requires appropriate light and water." },
{ "id": "database", "text": "SQL Server stores relational data in tables." }
],
"topK": 2
}A successful response contains model, dimensions and a descending results list of { id, score } objects. The intended retrieval task favors the relevant API document, but no exact semantic score or guaranteed ranking is invented here. Record the actual output and evaluate it against your relevance labels.
This endpoint is not an answer generator: it returns ranked document IDs rather than a synthesized explanation. It also does not permanently ingest documents. Repeating this request regenerates its query and document vectors and can incur provider cost again.
| Negative test | Expected behavior |
|---|---|
| No valid demo key | 401 without generation |
| Blank/oversized text or duplicate document IDs | 400 |
| TopK exceeds candidate count | 400 |
| More than four admitted concurrent requests | Excess work can receive local 429 |
| Provider admission limit | Safe 503 with a local retry hint |
| Unexpected vector shape / invalid contents | 502 rather than comparing incompatible vectors |
| Generation exceeds the local budget | 504 if caller itself has not cancelled |
| Caller disconnects | Cancellation propagates; do not interpret it as guaranteed zero billing |
For a mathematical smoke test, verify VectorMath against the four toy pairs shown earlier, and verify that zero, empty, unequal-length, NaN and infinity-containing vectors are rejected. Those checks do not validate semantic quality. The C# execution, endpoint response headers and provider behavior still require local testing.
9. Token limits, batching, model compatibility and performance
The OpenAI embeddings API reference documents per-input limits, aggregate request limits and the dimensions parameter. The selected model documentation lists an 8192-token maximum input. A character count is not an exact token count: language, symbols and encoding affect tokenization. Use the provider-appropriate tokenizer when increasing the sample’s bounds.
The API accepts one text or at most eight candidate documents; similarity adds one query. These deliberately small batches make input/output association visible. Production batch size should respect per-item tokens, aggregate tokens, response memory, rate limits and latency requirements. An enormous HTTP body or unbounded Task.WhenAll is not a batching strategy.
For long documents, split on useful boundaries, preserve source IDs and positions, and evaluate overlap rather than splitting blindly by arbitrary bytes. Keep preprocessing and chunking versions with the stored vectors. Do not silently truncate important content merely to make a request succeed.
| Decision | Practical effect | What to evaluate |
|---|---|---|
| Output dimensions | Changes storage and arithmetic per vector | Retrieval quality versus size; recreate compatible indexes |
| Batch size | Changes request count, latency and memory | Provider limits and failure/retry granularity |
| Chunk size and overlap | Changes what each vector represents | Context preservation, duplication and relevance |
| Caching | Avoids repeated generation for identical compatible inputs | Tenant isolation, retention and invalidation |
| Index type | Changes search tradeoffs for a stored corpus | Recall, filtering, latency and update costs |
The comparison algorithm scans every candidate, so its work grows with candidate count times vector dimensions. That is suitable for this bounded demonstration. For a large corpus, precompute document vectors, store them with metadata and authorization fields, embed new queries, and use an appropriate vector index. This article does not reproduce a vector database or RAG pipeline.
Raw float32 coordinate storage is four bytes per dimension: 512 coordinates require 2,048 raw bytes before metadata, index structures or JSON overhead. That is arithmetic, not a database footprint benchmark. Serialization and indexing can materially increase real storage.
Persisted vectors must remain in compatible spaces. Equal length is necessary but insufficient: different models, model versions or preprocessing can make comparisons meaningless. Re-embed deliberately when changing the configuration and evaluate a representative query set before switching production traffic.
10. Privacy, security, cost and production safeguards
Embedding generation sends the supplied text to the configured provider. Do not describe embeddings as anonymization, encryption or a permission boundary. Even if the application stores only vectors, they can encode information about sensitive inputs and need an appropriate data-handling policy.
Review the provider’s data controls for the actual endpoint and account configuration. Avoid blanket claims such as “nothing is retained” or “all prompts train the model.” Retention, access controls and contractual choices must be checked for the deployed service.
- Require real identity and authorization before accepting paid embedding requests.
- Apply tenant-aware request, token and spending budgets; the sample’s per-process concurrency cap is not a cost ceiling.
- Never share cached vectors across tenants without an explicit permitted-data policy.
- Do not log keys, submitted text or full vector arrays by default.
- Keep the provider endpoint and model under server control.
- Limit payload and response sizes, bound concurrency and honor cancellation.
- Store model/configuration metadata and implement retention and deletion procedures.
- Keep document authorization filters separate from semantic ranking; a relevant document can still be forbidden.
API use is priced according to the provider’s current contract, typically including processed input tokens. The interface does not eliminate cost. Do not invent dollar estimates without checking current pricing and actual input usage. Retrying a failed or timed-out request can repeat paid work; avoid stacking SDK, application and infrastructure retries blindly.
For production, replace the shared demo key with a proper identity system, add distributed admission controls where needed, and load-test the service with realistic text sizes. When deploying behind IIS, the related ASP.NET Core 10 IIS guide covers the hosting foundation; secure outbound provider access and inbound HTTPS remain your application’s responsibility.
Troubleshooting text embeddings in .NET
| Symptom | What to check |
|---|---|
| AsIEmbeddingGenerator cannot be found | Install Microsoft.Extensions.AI.OpenAI 10.11.0, restore packages and import Microsoft.Extensions.AI. The abstractions package alone does not provide the OpenAI adapter. |
| Provider rejects the model | Use an embedding model, not a chat completion model. This sample explicitly accepts text-embedding-3-small. Azure deployment names require an Azure-specific client configuration. |
| Vectors have different lengths | Use one configured dimension for ingestion and queries. Rebuild stored vectors after a model or dimension migration. Equal lengths alone do not establish compatibility. |
| 400 before a provider call | Check nonblank text, unique document IDs, the 2,000-character cap, 1–8 documents and topK between 1 and the document count. With only two documents, set topK to 1 or 2. Unknown JSON properties are rejected. |
| 401 versus provider authentication failure | X-Demo-Key authenticates this local API; OpenAI:ApiKey authenticates outbound provider calls. They are different secrets. Outbound failures receive a safe 502 here; investigate server-side telemetry without exposing credentials. |
| 429 or 503 | 429 is the local concurrency limiter. A provider 429 is mapped to 503 by this sample. Check account quota, token throughput and tenant budgets before adding retries. |
| 502 or 504 | Check provider reachability, model access and returned vector count/dimensions. The linked cancellation budget is 30 seconds; it is cooperative cancellation, not proof that provider-side work or billing stopped. |
| Zero or non-finite vector | Do not calculate a cosine score. The implementation rejects these values and malformed provider results rather than returning NaN. |
| A high score seems wrong | Cosine is a similarity measure, not a calibrated probability. Evaluate relevance with representative questions and labeled documents; do not describe 0.8 as 80% confidence. |
| Unexpected cost | The similarity endpoint embeds both the question and every supplied document on every request. Precompute document vectors for real search and apply tenant budgets. |
For a provider 400 caused by token limits, count tokens with the tokenizer appropriate to the model and split the input deliberately. A character limit is a request-size safeguard, not an exact token-count substitute. Do not silently truncate user content and pretend the full document was represented.
Frequently asked questions
What is IEmbeddingGenerator?
It is the Microsoft.Extensions.AI abstraction for generating embeddings. In this article, IEmbeddingGenerator<string, Embedding<float>> accepts text and produces floating-point vectors through an OpenAI adapter.
Does Microsoft.Extensions.AI host an embedding model?
No. It supplies abstractions and integration components. You still need a compatible provider, model access and any provider-specific credentials or local infrastructure.
Can I use embeddings without a vector database?
Yes. This tutorial compares a small supplied document set in memory. Persistent semantic search across a large corpus normally needs stored document vectors and an appropriate search index.
Why use 512 dimensions?
It is an explicit tutorial configuration supported by the selected third-generation OpenAI model. It keeps returned vectors smaller than the default 1,536 dimensions. Whether that tradeoff preserves enough quality must be evaluated on your own documents; no accuracy or speed gain is claimed here.
Can I mix embeddings from different models?
Do not assume that you can. Treat provider, model identity/version, dimensions and preprocessing as the embedding-space contract. Re-embed documents and queries consistently during migration.
Is cosine similarity a percentage?
No. The mathematical range is −1 to 1 for valid nonzero vectors. Its practical distribution depends on the model and data; a threshold needs evaluation, not a universal percentage interpretation.
Does an embedding answer a question?
No. It represents an input numerically. Retrieval can select relevant documents; a separate generative model can use them to produce a RAG answer. This article does not implement a chatbot or generation pipeline.
Can the service embed several documents at once?
Yes. The batch endpoint sends the validated list to GenerateAsync. Provider batch/input limits still apply. For large collections, use bounded batches, a durable ingestion process and explicit failure/retry checkpoints.
Are vectors safe to log or publish?
Treat them as potentially sensitive derived data. Restrict access and retention, avoid logging full vectors or source text, and review the provider’s current data controls for your account and endpoint.
Was the application compiled and tested?
No .NET SDK was available in the authoring environment, and no live provider calls were made. The C# implementation was reviewed against the linked APIs. The four small cosine arithmetic examples were checked independently in Python. All API responses shown are expected contracts, not captured execution results.
Conclusion: start with a small, measurable embedding API
You now have a complete example of the application boundary: validate text, generate vectors through IEmbeddingGenerator, check their shape, calculate cosine similarity and return a limited response without exposing provider errors. The useful next step is to run the project locally, exercise the negative cases and evaluate results with documents that resemble your actual workload.
Keep this small similarity endpoint for learning and controlled experiments. For production search, separate document ingestion from querying, persist compatible vectors, enforce tenant-aware authorization and measure retrieval quality as well as latency and spend.
Suggested supporting articles
- Evaluating embedding relevance with multilingual .NET documentation queries.
- Designing tenant-aware embedding cache keys, retention and deletion.
- Regression testing a model migration before rebuilding a vector index.
These are future topic suggestions only; no additional posts were created.
References and research notes
- Microsoft: IEmbeddingGenerator
- Microsoft: embedding concepts
- Microsoft.Extensions.AI overview
- Stable OpenAI adapter package and dependencies
- OpenAI adapter extension API
- GenerateAsync contract
- EmbeddingGenerationOptions
- Official adapter implementation
- Official OpenAI .NET SDK
- OpenAI embedding guide
- Selected model: text-embedding-3-small
- Embedding API limits and parameters
- Provider data controls
- ASP.NET Core development secrets
- ASP.NET Core rate limiting
Research reviewed on 4 November 2026. Package versions and provider policies can change: verify the linked release/package pages when reproducing the tutorial. The API reference may carry a prerelease warning for its documentation view; the selected NuGet adapter release is stable. Provider-specific extensions should not be inferred from the abstraction alone.
The article targets the primary query text embeddings ASP.NET Core 10, with related developer questions about Microsoft.Extensions.AI, IEmbeddingGenerator, C# cosine similarity, batch embeddings, OpenAI embeddings in .NET and embedding dimensions. Search-intent review found a practical gap between short vector-generation examples and complete validated API boundaries: this tutorial combines configuration, batching, mathematical safeguards and negative-case testing. No search-volume, competition, ranking or benchmark figures are claimed.
- Get link
- X
- Other Apps
Comments
Post a Comment