Aspire

Connect to Azure OpenAI

Azure OpenAI logo

This page describes how consuming apps connect to an Azure OpenAI resource that’s already modeled in your AppHost. For the AppHost API surface — adding an Azure OpenAI account, deployment resources, managed identity, and infrastructure customization — see Azure OpenAI hosting integration.

When you reference an Azure OpenAI deployment from your AppHost, Aspire injects the connection information into the consuming app as environment variables. Your app can either read those environment variables directly — the pattern works the same from any language — or, in C#, use the Aspire.Azure.AI.Extensions.OpenAI client integration for automatic dependency injection and telemetry.

Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the Uri property of a resource called chat becomes CHAT_URI.

The Azure OpenAI account resource exposes the following connection properties:

Property NameDescription
UriThe endpoint URI for the Azure OpenAI account, for example https://{account-name}.openai.azure.com/

Example connection string:

https://{account-name}.openai.azure.com/

The Azure OpenAI deployment resource inherits all properties from its parent account resource and adds:

Property NameDescription
ModelNameThe name of the deployment, for example chat

Example environment variables for a deployment resource named chat:

CHAT_URI=https://{account-name}.openai.azure.com/
CHAT_MODELNAME=chat

Pick the language your consuming app is written in. Each example assumes your AppHost adds an Azure OpenAI deployment resource named chat and references it from the consuming app.

For C# apps, the recommended approach is the Aspire Azure AI Extensions OpenAI client integration. It registers an OpenAIClient from the standard OpenAI SDK through dependency injection, configured for the account’s /openai/v1/ endpoint, and can also register an IChatClient or embedding generator via Microsoft.Extensions.AI. If you’d rather read environment variables directly, see the Read environment variables section at the end of this tab.

Install the 📦 Aspire.Azure.AI.Extensions.OpenAI NuGet package in the client-consuming project:

.NET CLI — Add Aspire.Azure.AI.Extensions.OpenAI package
dotnet add package Aspire.Azure.AI.Extensions.OpenAI

In Program.cs, call AddAzureOpenAIClient on your IHostApplicationBuilder to register an OpenAIClient:

Program.cs
builder.AddAzureOpenAIClient(connectionName: "chat");

Resolve the client through dependency injection:

ExampleService.cs
using OpenAI;
public class ExampleService(OpenAIClient client)
{
// Use client...
}

Call AddChatClient after AddAzureOpenAIClient to also register an IChatClient from Microsoft.Extensions.AI. When you reference a deployment resource, its connection string includes the deployment name, so you can omit the argument. Pass a deployment name to override it:

Program.cs
builder.AddAzureOpenAIClient("chat")
.AddChatClient();

Use AddKeyedChatClient to register a keyed IChatClient:

Program.cs
builder.AddAzureOpenAIClient("chat")
.AddKeyedChatClient("serviceKey", "chat");

Resolve the IChatClient through dependency injection:

ExampleService.cs
using Microsoft.Extensions.AI;
public class ExampleService(IChatClient chatClient)
{
public async Task<string> GetResponseAsync(string userMessage)
{
var response = await chatClient.GetResponseAsync(userMessage);
return response.Text;
}
}

To register an IEmbeddingGenerator<string, Embedding<float>>, call AddEmbeddingGenerator (or AddKeyedEmbeddingGenerator) instead:

Program.cs
builder.AddAzureOpenAIClient("embeddings")
.AddEmbeddingGenerator();

For more information on IChatClient and Microsoft.Extensions.AI, see Unified AI Building Blocks for .NET.

To register multiple OpenAIClient instances with different connection names, use AddKeyedAzureOpenAIClient:

Program.cs
builder.AddKeyedAzureOpenAIClient(name: "chat");
builder.AddKeyedAzureOpenAIClient(name: "embeddings");

Then resolve each instance by key:

ExampleService.cs
public class ExampleService(
[FromKeyedServices("chat")] OpenAIClient chatClient,
[FromKeyedServices("embeddings")] OpenAIClient embeddingsClient)
{
// Use clients...
}

The client integration offers multiple ways to provide configuration.

Connection strings. When using a connection string from the ConnectionStrings configuration section, pass the connection name to AddAzureOpenAIClient:

Program.cs
builder.AddAzureOpenAIClient("chat");

The connection string is resolved from the ConnectionStrings section. The endpoint must be an HTTPS account endpoint; Aspire normalizes it to the account’s /openai/v1/ route. Two authentication formats are supported:

  • Microsoft Entra ID (recommended): The endpoint, optionally with a default Deployment. A bare endpoint URI is also accepted.

    appsettings.json
    {
    "ConnectionStrings": {
    "chat": "Endpoint=https://{account-name}.openai.azure.com/;Deployment=chat"
    }
    }
  • API key: Endpoint plus key.

    appsettings.json
    {
    "ConnectionStrings": {
    "chat": "Endpoint=https://{account-name}.openai.azure.com/;Key={api-key}"
    }
    }

Without a key, the client authenticates with Microsoft Entra ID: Aspire uses a development credential locally and managed identity when deployed to Azure. The default token scope is https://ai.azure.com/.default; set TokenScope for other Azure clouds.

Configuration providers. The client integration supports Microsoft.Extensions.Configuration. It loads AzureOpenAISettings from appsettings.json (or any other configuration source) using the Aspire:Azure:AI:OpenAI key, followed by a connection-specific subsection:

appsettings.json
{
"Aspire": {
"Azure": {
"AI": {
"OpenAI": {
"DisableTracing": false,
"DisableMetrics": false,
"EnableSensitiveTelemetryData": false
}
}
}
}
}

Inline delegates. Configure settings inline using an Action<AzureOpenAISettings>, for example to supply a custom credential:

Program.cs
using Azure.Identity;
builder.AddAzureOpenAIClient(
"chat",
settings => settings.Credential = new AzureCliCredential());

To configure the OpenAIClientOptions inline:

Program.cs
using Microsoft.Extensions.Azure;
builder.AddAzureOpenAIClient(
connectionName: "chat",
configureClientBuilder: clientBuilder =>
{
clientBuilder.ConfigureOptions(options =>
{
options.NetworkTimeout = TimeSpan.FromSeconds(60);
});
});

Use AddOpenAIClientFromConfiguration (or AddKeyedOpenAIClientFromConfiguration) when the same app might run against Azure OpenAI or another OpenAI-compatible endpoint. It always registers an OpenAIClient and picks the registration based on the connection string value:

Program.cs
builder.AddOpenAIClientFromConfiguration("chat")
.AddChatClient();
Connection string exampleRegistration
https://{account}.openai.azure.com/Azure OpenAI account, Microsoft Entra ID
Endpoint=https://{account}.openai.azure.com/;Key={key}Azure OpenAI account, API key
Endpoint=https://{account}.services.ai.azure.com/api/projects/{project}Foundry project (see Connect to Microsoft Foundry)
Endpoint=https://{account}.openai.azure.com/;Key={key};IsAzure=falseOpenAI-compatible endpoint, API key
Endpoint=https://localhost:18889;Key={key}OpenAI-compatible endpoint, API key

Endpoints on Azure hosts (such as *.azure.com) are treated as Azure. Use IsAzure=true or IsAzure=false to override detection, for example for custom domains.

The client integration doesn’t register a health check, so it never makes billable inference calls to probe the service.

The chat and embedding helpers register Microsoft.Extensions.AI tracing and metrics through OpenTelemetry, using these activity sources and meters:

  • Experimental.Microsoft.Extensions.AI
  • Microsoft.Extensions.AI

Use DisableTracing and DisableMetrics to turn off each signal independently. Message content isn’t captured unless you set EnableSensitiveTelemetryData to true (or set the OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT environment variable to true). Calls you make directly on OpenAIClient use the OpenAI SDK’s own diagnostics.

To upgrade an app that uses the discontinued Aspire.Azure.AI.OpenAI package:

  1. Replace the Aspire.Azure.AI.OpenAI package reference with Aspire.Azure.AI.Extensions.OpenAI.

  2. Keep your AddAzureOpenAIClient, AddKeyedAzureOpenAIClient, AddOpenAIClientFromConfiguration, AddChatClient, and AddEmbeddingGenerator calls. Settings stay under Aspire:Azure:AI:OpenAI.

  3. Update code that depends on the old types:

    Before (Aspire.Azure.AI.OpenAI)After (Aspire.Azure.AI.Extensions.OpenAI)
    Resolve Azure.AI.OpenAI.AzureOpenAIClientResolve OpenAI.OpenAIClient
    Aspire.Azure.AI.OpenAI.AzureOpenAISettingsAspire.Azure.AI.Extensions.OpenAI.AzureOpenAISettings
    configureClientBuilder customizes AzureOpenAIClientOptionsconfigureClientBuilder customizes OpenAIClientOptions
    Deployment-specific routes/openai/v1/ routes

The new package uses the standard OpenAI SDK’s v1 API, so the registration pattern is compatible but the client types aren’t. For API differences, see the Azure OpenAI SDK migration guide.

If you prefer not to use the Aspire client integration, you can read the Aspire-injected endpoint from the environment and construct an AzureOpenAIClient directly using DefaultAzureCredential for managed identity:

Program.cs
using Azure.AI.OpenAI;
using Azure.Identity;
var endpoint = Environment.GetEnvironmentVariable("CHAT_URI");
var deploymentName = Environment.GetEnvironmentVariable("CHAT_MODELNAME");
var client = new AzureOpenAIClient(
new Uri(endpoint!),
new DefaultAzureCredential());
var chatClient = client.GetChatClient(deploymentName);
// Use chatClient...