Skip to content
Docs Try Aspire
Docs Try

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 OpenAI client integration for automatic dependency injection, health checks, 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 OpenAI client integration. It registers an AzureOpenAIClient through dependency injection and, optionally, registers an IChatClient 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.OpenAI NuGet package in the client-consuming project:

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

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

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

Resolve the client through dependency injection:

C# — ExampleService.cs
public class ExampleService(AzureOpenAIClient client)
{
// Use client...
}

Call AddChatClient after AddAzureOpenAIClient to also register an IChatClient from Microsoft.Extensions.AI. The deployment name is passed as an argument:

C# — Program.cs
builder.AddAzureOpenAIClient("chat")
.AddChatClient("chat");

Use AddKeyedChatClient to register a keyed IChatClient:

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

Resolve the IChatClient through dependency injection:

C# — ExampleService.cs
public class ExampleService(IChatClient chatClient)
{
public async Task<string> GetResponseAsync(string userMessage)
{
var response = await chatClient.CompleteAsync(userMessage);
return response.Message.Text ?? string.Empty;
}
}

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

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

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

Then resolve each instance by key:

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

The Aspire Azure OpenAI 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:

C# — Program.cs
builder.AddAzureOpenAIClient("chat");

The connection string is resolved from the ConnectionStrings section. Two formats are supported:

  • Managed identity (recommended): The endpoint URI only.

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

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

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:

JSON — appsettings.json
{
"Aspire": {
"Azure": {
"AI": {
"OpenAI": {
"DisableTracing": false
}
}
}
}
}

Inline delegates. Configure settings inline using an Action<AzureOpenAISettings>:

C# — Program.cs
builder.AddAzureOpenAIClient(
"chat",
settings => settings.DisableTracing = true);

To configure the AzureOpenAIClientOptions inline:

C# — Program.cs
builder.AddAzureOpenAIClient(
connectionName: "chat",
configureClientBuilder: clientBuilder =>
{
clientBuilder.ConfigureOptions(options =>
{
options.UserAgentApplicationId = "MyApp";
});
});

Add Azure OpenAI client from configuration

Section titled “Add Azure OpenAI client from configuration”

Use AddOpenAIClientFromConfiguration to register an OpenAIClient or AzureOpenAIClient based on the connection string value:

C# — Program.cs
builder.AddOpenAIClientFromConfiguration("chat");

The method selects the client type according to these rules:

Connection string exampleRegistered client type
https://{account}.openai.azure.com/AzureOpenAIClient
Endpoint=https://{account}.openai.azure.com/;Key={key}AzureOpenAIClient
Endpoint=https://{account}.openai.azure.com/;Key={key};IsAzure=falseOpenAIClient
Endpoint=https://localhost:18889;Key={key}OpenAIClient

Aspire client integrations enable health checks by default. The Azure OpenAI client integration participates in the standard Aspire health check pipeline.

The Aspire Azure OpenAI client integration automatically configures logging, tracing, and metrics through OpenTelemetry.

Logging categories:

  • Azure
  • Azure.Core
  • Azure.Identity
  • Azure.AI.OpenAI

Tracing activities:

  • Azure.AI.OpenAI.*
  • gen_ai.system — generic AI system tracing
  • gen_ai.operation.name — operation names for AI calls

Metrics:

The Aspire Azure OpenAI integration currently does not emit metrics by default due to limitations with the Azure SDK for .NET.

Any of these telemetry features can be disabled through the configuration options above.

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:

C# — 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...