How to Generate Embeddings from a Microsoft Foundry Resource in C#
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();
| Part | What 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 / restore | The 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
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 EmbeddingCheckcreates a console app in a newEmbeddingCheckfolder, andcdmoves into it.OpenAIis the OpenAI .NET library. ItsEmbeddingClientsends embedding requests to the resource's OpenAI endpoint.Azure.Identitylets the app sign in with your Azure CLI account. Microsoft's C# sample installs these two packages as well.System.Numerics.TensorshasTensorPrimitives.CosineSimilarity, which compares two vectors in Step 4.
The project file now references all three:
<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:
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
- The endpoint is the Foundry resource's Azure OpenAI endpoint, with the
/openai/v1/path. It isn't the project endpoint that ends in/api/projects/and a project name: Microsoft's page on Foundry SDKs and endpoints says The project endpoint used by the Foundry SDK doesn't currently route embedding requests. What happens if you use it: Fixed: "Service request failed. Status: 404 (Not Found)" Generating Embeddings from a Microsoft Foundry Project. modelis the deployment's name,text-embedding-3-smallhere.new BearerTokenPolicy(new AzureCliCredential(), "https://ai.azure.com/.default")signs every request with a Microsoft Entra ID token for your Azure CLI account, with the scope Microsoft's sample uses. There's no key to store: Microsoft Entra ID is recommended because it avoids storing long-lived credentials.- The two pragma lines are there because this constructor is experimental in the OpenAI library. It still is in version 2.15.0, and without the pragma the build fails: Fixed: OPENAI001 'OpenAI.Embeddings.EmbeddingClient.EmbeddingClient(string, System.ClientModel.Primitives.AuthenticationPolicy, OpenAI.OpenAIClientOptions)' is for evaluation purposes only. Microsoft's sample disables OPENAI001 too.
Step 3: Generate the Embeddings
Add the words and the request below the client:
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 anOpenAIEmbeddingCollection, with one embedding per word.embedding.ToFloats()gives each embedding as aReadOnlyMemory<float>: the vector itself.vectors[0]is the vector for cat.- The
Console.WriteLineprints 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:
// 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.CosineSimilaritycompares 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.InputTokenCountis the number of tokens the request used.
Step 5: Run It
dotnet run
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

- 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
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}");

Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| Using the Foundry project endpoint for embeddings | Service request failed. Status: 404 (Not Found) at the first request | Use the resource's /openai/v1/ endpoint |
| Leaving out the two pragma lines | The build fails with error OPENAI001 on the constructor | Keep them around the statement that creates the client |
Putting the model's name in model when your deployment has another name | A 404, which Microsoft's troubleshooting list traces to the deployment name | Use your deployment's name |
Troubleshooting
Microsoft's embeddings documentation lists what each error status usually means:
| Status | What to check |
|---|---|
401 | Sign 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 |
403 | That your account has the Cognitive Services OpenAI User role on the resource |
404 | That the endpoint includes /openai/v1/ and that model is a valid deployment name |
400 | The 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
- Generate embeddings with Azure OpenAI — Microsoft's C# sample, the limits and the troubleshooting list.
- Microsoft Foundry SDKs and endpoints — which endpoint serves embeddings.
- TensorPrimitives.CosineSimilarity — the method that compares two vectors.
Related
- Fixed: "Service request failed. Status: 404 (Not Found)" Generating Embeddings from a Microsoft Foundry Project
- Fixed: OPENAI001 'OpenAI.Embeddings.EmbeddingClient.EmbeddingClient(string, System.ClientModel.Primitives.AuthenticationPolicy, OpenAI.OpenAIClientOptions)' is for evaluation purposes only
