Skip to main content

How to Generate Embeddings from a Microsoft Foundry Resource in C#

· 10 min read
Jagdish Kumawat
Founder @ Dewiride

An embedding model turns text into a vector, a long list of numbers, and texts with similar meanings get vectors that are close together. This post generates embeddings in C# from a Microsoft Foundry resource, signed in with your Azure CLI account instead of a key, and compares three words to see it work.

Syntax​

#pragma warning disable OPENAI001
EmbeddingClient <client> = new(
model: "<deployment>",
authenticationPolicy: new BearerTokenPolicy(<credential>, "https://ai.azure.com/.default"),
options: new OpenAIClientOptions { Endpoint = new Uri("https://<resource>.openai.azure.com/openai/v1/") });
#pragma warning restore OPENAI001

OpenAIEmbeddingCollection <result> = await <client>.GenerateEmbeddingsAsync(<texts>);
ReadOnlyMemory<float>[] <vectors> = <result>.Select(embedding => embedding.ToFloats()).ToArray();
PartWhat it is
<client>Your name for the client. It talks to one embedding deployment.
<deployment>Your embedding model deployment's name. Microsoft's embeddings documentation: The model value in each request is your Azure model deployment name.
<credential>Who signs in. AzureCliCredential uses your az login account. Microsoft's sample uses DefaultAzureCredential, which uses your signed-in identity locally and can use a managed identity when your application runs in Azure.
<resource>Your Foundry resource's name. https://<resource>.openai.azure.com/openai/v1/ is its Azure OpenAI endpoint.
#pragma warning disable / restoreThe constructor that takes an AuthenticationPolicy is experimental in the OpenAI library (OPENAI001). These two lines accept that for this one statement.
<texts>The strings to embed, all in one request.
<result>The embeddings that came back, one per text, with the request's token usage.
ToFloats()One embedding as numbers: the vector.

The Example​

A console app called EmbeddingCheck embeds three words, cat, kitten and spreadsheet, in one request to a text-embedding-3-small deployment. It prints how many numbers each vector has and the first three for cat, compares cat with the other two words, and prints the tokens the request used. That one request is 5 tokens, so the run costs very little.

Prerequisites​

  • The .NET 10 SDK.
  • A Microsoft Foundry resource with an embedding model deployment, such as text-embedding-3-small.
  • The Cognitive Services OpenAI User role on that resource for your account: Microsoft's embeddings documentation lists it for signing in with Microsoft Entra ID.
  • The Azure CLI, signed in with az login.

Step 1: Create a Console App​

Terminal
dotnet new console -o EmbeddingCheck
cd EmbeddingCheck
dotnet add package OpenAI --version 2.15.0
dotnet add package Azure.Identity --version 1.21.0
dotnet add package System.Numerics.Tensors --version 10.0.15
  • dotnet new console -o EmbeddingCheck creates a console app in a new EmbeddingCheck folder, and cd moves into it.
  • OpenAI is the OpenAI .NET library. Its EmbeddingClient sends embedding requests to the resource's OpenAI endpoint.
  • Azure.Identity lets the app sign in with your Azure CLI account. Microsoft's C# sample installs these two packages as well.
  • System.Numerics.Tensors has TensorPrimitives.CosineSimilarity, which compares two vectors in Step 4.

The project file now references all three:

EmbeddingCheck.csproj
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Azure.Identity" Version="1.21.0" />
<PackageReference Include="OpenAI" Version="2.15.0" />
<PackageReference Include="System.Numerics.Tensors" Version="10.0.15" />
</ItemGroup>

</Project>

Step 2: Create the Embedding Client​

Replace everything in Program.cs with this, using your own resource's name in the endpoint and your own deployment's name in model:

Program.cs
using System.ClientModel.Primitives;
using System.Numerics.Tensors;
using Azure.Identity;
using OpenAI;
using OpenAI.Embeddings;

// The resource's Azure OpenAI endpoint, signed in with your Azure CLI account.
#pragma warning disable OPENAI001
EmbeddingClient embeddings = new(
model: "text-embedding-3-small",
authenticationPolicy: new BearerTokenPolicy(new AzureCliCredential(), "https://ai.azure.com/.default"),
options: new OpenAIClientOptions { Endpoint = new Uri("https://foundry-devblogs-exp.openai.azure.com/openai/v1/") });
#pragma warning restore OPENAI001

Step 3: Generate the Embeddings​

Add the words and the request below the client:

Program.cs (the embeddings)
string[] words = ["cat", "kitten", "spreadsheet"];

// One request for all three texts. Each comes back as a vector of numbers.
OpenAIEmbeddingCollection result = await embeddings.GenerateEmbeddingsAsync(words);
ReadOnlyMemory<float>[] vectors = result.Select(embedding => embedding.ToFloats()).ToArray();

Console.WriteLine($"Each vector has {vectors[0].Length} numbers. The first three for \"cat\": " +
string.Join(", ", vectors[0].Span[..3].ToArray().Select(value => value.ToString("0.0000"))));
  • GenerateEmbeddingsAsync(words) sends all three words in one request and returns an OpenAIEmbeddingCollection, with one embedding per word.
  • embedding.ToFloats() gives each embedding as a ReadOnlyMemory<float>: the vector itself. vectors[0] is the vector for cat.
  • The Console.WriteLine prints the vector's length, then its first three numbers, vectors[0].Span[..3], with four decimal places.

Step 4: Compare the Vectors​

Add the comparison and the token count at the end of the file:

Program.cs (the comparison)
// Texts with similar meanings get similar vectors: compare "cat" with the other two.
for (int i = 1; i < words.Length; i++)
{
float similarity = TensorPrimitives.CosineSimilarity(vectors[0].Span, vectors[i].Span);
Console.WriteLine($"cat / {words[i]}: {similarity:0.00}");
}

Console.WriteLine($"Tokens used: {result.Usage.InputTokenCount}");
  • TensorPrimitives.CosineSimilarity compares two vectors. Its reference: Computes the cosine similarity between the two specified non-empty, equal-length tensors of single-precision floating-point numbers. That's the dot product of the two vectors divided by the product of their lengths, so vectors that point the same way score higher.
  • The loop compares cat, vectors[0], with kitten and spreadsheet, and prints each score with two decimal places.
  • result.Usage.InputTokenCount is the number of tokens the request used.

Step 5: Run It​

Terminal
dotnet run
Output
Each vector has 1536 numbers. The first three for "cat": 0.0255, -0.0234, -0.0161
cat / kitten: 0.57
cat / spreadsheet: 0.23
Tokens used: 5

macOS-style terminal window titled Terminal — EmbeddingCheck showing dotnet run: each vector has 1536 numbers, the first three for cat are 0.0255, -0.0234 and -0.0161, cat and kitten score 0.57, cat and spreadsheet score 0.23, and the request used 5 tokens

  • 1536 numbers per vector. The numbers aren't readable on their own: what matters is how close two vectors are.
  • cat / kitten 0.57, cat / spreadsheet 0.23. Kitten is much closer in meaning to cat than spreadsheet is, and the vectors show it. Microsoft's embeddings documentation: Similar text produces vectors that are close together, which makes embeddings useful for vector search, recommendations, classification, and clustering.
  • 5 tokens for the three words, sent in one request.

The Complete File​

Program.cs
using System.ClientModel.Primitives;
using System.Numerics.Tensors;
using Azure.Identity;
using OpenAI;
using OpenAI.Embeddings;

// The resource's Azure OpenAI endpoint, signed in with your Azure CLI account.
#pragma warning disable OPENAI001
EmbeddingClient embeddings = new(
model: "text-embedding-3-small",
authenticationPolicy: new BearerTokenPolicy(new AzureCliCredential(), "https://ai.azure.com/.default"),
options: new OpenAIClientOptions { Endpoint = new Uri("https://foundry-devblogs-exp.openai.azure.com/openai/v1/") });
#pragma warning restore OPENAI001

string[] words = ["cat", "kitten", "spreadsheet"];

// One request for all three texts. Each comes back as a vector of numbers.
OpenAIEmbeddingCollection result = await embeddings.GenerateEmbeddingsAsync(words);
ReadOnlyMemory<float>[] vectors = result.Select(embedding => embedding.ToFloats()).ToArray();

Console.WriteLine($"Each vector has {vectors[0].Length} numbers. The first three for \"cat\": " +
string.Join(", ", vectors[0].Span[..3].ToArray().Select(value => value.ToString("0.0000"))));

// Texts with similar meanings get similar vectors: compare "cat" with the other two.
for (int i = 1; i < words.Length; i++)
{
float similarity = TensorPrimitives.CosineSimilarity(vectors[0].Span, vectors[i].Span);
Console.WriteLine($"cat / {words[i]}: {similarity:0.00}");
}

Console.WriteLine($"Tokens used: {result.Usage.InputTokenCount}");

macOS-style code window titled Program.cs — EmbeddingCheck showing an EmbeddingClient for the text-embedding-3-small deployment on the resource's openai/v1 endpoint, signed in with a BearerTokenPolicy and AzureCliCredential between pragma lines for OPENAI001, then GenerateEmbeddingsAsync for cat, kitten and spreadsheet, TensorPrimitives.CosineSimilarity comparing cat with the other two words, and the token count

Common Mistakes​

MistakeWhat happensDo this instead
Using the Foundry project endpoint for embeddingsService request failed. Status: 404 (Not Found) at the first requestUse the resource's /openai/v1/ endpoint
Leaving out the two pragma linesThe build fails with error OPENAI001 on the constructorKeep them around the statement that creates the client
Putting the model's name in model when your deployment has another nameA 404, which Microsoft's troubleshooting list traces to the deployment nameUse your deployment's name

Troubleshooting​

Microsoft's embeddings documentation lists what each error status usually means:

StatusWhat to check
401Sign in again with az login, and check that the access token uses the correct audience. The example asks for its token with https://ai.azure.com/.default, as Microsoft's sample does
403That your account has the Cognitive Services OpenAI User role on the resource
404That the endpoint includes /openai/v1/ and that model is a valid deployment name
400The request body, each input's token count, the number of inputs and the total tokens

FAQ​

Why doesn't the project endpoint work for embeddings?​

Microsoft's page on Foundry SDKs and endpoints: Use the OpenAI SDK endpoint for generating embeddings. The project endpoint serves chat models and Foundry's own features, but it doesn't currently route embedding requests.

Can I use an API key instead?​

Yes: The v1 embeddings API supports Microsoft Entra ID and API key authentication. Microsoft recommends Microsoft Entra ID, because there's no long-lived credential to store.

How much can one request embed?​

Microsoft's embeddings documentation gives the limits: The maximum input length for the current embedding models is 8,192 tokens. If you send an array of inputs in a single embedding request, the maximum array size is 2,048. And: Each /embeddings request has a 300,000-token aggregate limit across all inputs.

Conclusion​

To generate embeddings from a Microsoft Foundry resource in C#, create an EmbeddingClient for your deployment on the resource's /openai/v1/ endpoint, sign it in with a BearerTokenPolicy, accept OPENAI001 around that statement, and call GenerateEmbeddingsAsync. Here three words came back as vectors of 1536 numbers in one 5-token request, and cosine similarity scored cat and kitten 0.57 against 0.23 for cat and spreadsheet.

Additional Resources​