Connect to Azure OpenAI
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.
Connection properties
Section titled “Connection properties”Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the Uri property of a resource called chat becomes CHAT_URI.
Azure OpenAI account resource
Section titled “Azure OpenAI account resource”The Azure OpenAI account resource exposes the following connection properties:
| Property Name | Description |
|---|---|
Uri | The endpoint URI for the Azure OpenAI account, for example https://{account-name}.openai.azure.com/ |
Example connection string:
https://{account-name}.openai.azure.com/Azure OpenAI deployment resource
Section titled “Azure OpenAI deployment resource”The Azure OpenAI deployment resource inherits all properties from its parent account resource and adds:
| Property Name | Description |
|---|---|
ModelName | The 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=chatConnect from your app
Section titled “Connect from your app”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 client integration
Section titled “Install the client integration”Install the 📦 Aspire.Azure.AI.Extensions.OpenAI NuGet package in the client-consuming project:
dotnet add package Aspire.Azure.AI.Extensions.OpenAI#:package Aspire.Azure.AI.Extensions.OpenAI@*<PackageReference Include="Aspire.Azure.AI.Extensions.OpenAI" Version="*" />Add an Azure OpenAI client
Section titled “Add an Azure OpenAI client”In Program.cs, call AddAzureOpenAIClient on your IHostApplicationBuilder to register an OpenAIClient:
builder.AddAzureOpenAIClient(connectionName: "chat");Resolve the client through dependency injection:
using OpenAI;
public class ExampleService(OpenAIClient client){ // Use client...}Add a chat client
Section titled “Add a chat 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:
builder.AddAzureOpenAIClient("chat") .AddChatClient();Use AddKeyedChatClient to register a keyed IChatClient:
builder.AddAzureOpenAIClient("chat") .AddKeyedChatClient("serviceKey", "chat");Resolve the IChatClient through dependency injection:
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:
builder.AddAzureOpenAIClient("embeddings") .AddEmbeddingGenerator();For more information on IChatClient and Microsoft.Extensions.AI, see Unified AI Building Blocks for .NET.
Add keyed Azure OpenAI clients
Section titled “Add keyed Azure OpenAI clients”To register multiple OpenAIClient instances with different connection names, use AddKeyedAzureOpenAIClient:
builder.AddKeyedAzureOpenAIClient(name: "chat");builder.AddKeyedAzureOpenAIClient(name: "embeddings");Then resolve each instance by key:
public class ExampleService( [FromKeyedServices("chat")] OpenAIClient chatClient, [FromKeyedServices("embeddings")] OpenAIClient embeddingsClient){ // Use clients...}Configuration
Section titled “Configuration”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:
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:
{ "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:
using Azure.Identity;
builder.AddAzureOpenAIClient( "chat", settings => settings.Credential = new AzureCliCredential());To configure the OpenAIClientOptions inline:
using Microsoft.Extensions.Azure;
builder.AddAzureOpenAIClient( connectionName: "chat", configureClientBuilder: clientBuilder => { clientBuilder.ConfigureOptions(options => { options.NetworkTimeout = TimeSpan.FromSeconds(60); }); });Add an OpenAI client from configuration
Section titled “Add an OpenAI client from configuration”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:
builder.AddOpenAIClientFromConfiguration("chat") .AddChatClient();| Connection string example | Registration |
|---|---|
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=false | OpenAI-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.
Client integration health checks
Section titled “Client integration health checks”The client integration doesn’t register a health check, so it never makes billable inference calls to probe the service.
Observability and telemetry
Section titled “Observability and telemetry”The chat and embedding helpers register Microsoft.Extensions.AI tracing and metrics through OpenTelemetry, using these activity sources and meters:
Experimental.Microsoft.Extensions.AIMicrosoft.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.
Migrate from Aspire.Azure.AI.OpenAI
Section titled “Migrate from Aspire.Azure.AI.OpenAI”To upgrade an app that uses the discontinued Aspire.Azure.AI.OpenAI package:
-
Replace the
Aspire.Azure.AI.OpenAIpackage reference withAspire.Azure.AI.Extensions.OpenAI. -
Keep your
AddAzureOpenAIClient,AddKeyedAzureOpenAIClient,AddOpenAIClientFromConfiguration,AddChatClient, andAddEmbeddingGeneratorcalls. Settings stay underAspire:Azure:AI:OpenAI. -
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.OpenAIClientAspire.Azure.AI.OpenAI.AzureOpenAISettingsAspire.Azure.AI.Extensions.OpenAI.AzureOpenAISettingsconfigureClientBuildercustomizesAzureOpenAIClientOptionsconfigureClientBuildercustomizesOpenAIClientOptionsDeployment-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.
Read environment variables in C#
Section titled “Read environment variables in C#”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:
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...Use the Azure SDK for Go OpenAI client:
go get github.com/Azure/azure-sdk-for-go/sdk/ai/azopenaigo get github.com/Azure/azure-sdk-for-go/sdk/azidentityRead the injected environment variables and connect using managed identity:
package main
import ( "context" "fmt" "os"
"github.com/Azure/azure-sdk-for-go/sdk/ai/azopenai" "github.com/Azure/azure-sdk-for-go/sdk/azidentity")
func main() { // Read the Aspire-injected connection properties endpoint := os.Getenv("CHAT_URI") deploymentName := os.Getenv("CHAT_MODELNAME")
credential, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { panic(err) }
client, err := azopenai.NewClient(endpoint, credential, nil) if err != nil { panic(err) }
resp, err := client.GetChatCompletions( context.Background(), azopenai.ChatCompletionsOptions{ DeploymentName: &deploymentName, Messages: []azopenai.ChatRequestMessageClassification{ &azopenai.ChatRequestUserMessage{ Content: azopenai.NewChatRequestUserMessageContent("Hello!"), }, }, }, nil, ) if err != nil { panic(err) }
fmt.Println(*resp.Choices[0].Message.Content)}Install the official OpenAI Python library and the Azure Identity library:
pip install openai azure-identityRead the injected environment variables and connect using managed identity:
import osfrom openai import AzureOpenAIfrom azure.identity import DefaultAzureCredential, get_bearer_token_provider
# Read the Aspire-injected connection propertiesendpoint = os.environ["CHAT_URI"]deployment_name = os.environ["CHAT_MODELNAME"]
# Obtain a token provider for managed identitytoken_provider = get_bearer_token_provider( DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default")
client = AzureOpenAI( azure_endpoint=endpoint, azure_ad_token_provider=token_provider, api_version="2024-10-21",)
response = client.chat.completions.create( model=deployment_name, messages=[{"role": "user", "content": "Hello!"}],)
print(response.choices[0].message.content)Install the official Azure OpenAI TypeScript library:
npm install @azure/openai @azure/identityRead the injected environment variables and connect using managed identity:
import { AzureOpenAI } from '@azure/openai';import { DefaultAzureCredential, getBearerTokenProvider } from '@azure/identity';
// Read Aspire-injected connection propertiesconst endpoint = process.env.CHAT_URI!;const deploymentName = process.env.CHAT_MODELNAME ?? 'chat';
const credential = new DefaultAzureCredential();const tokenProvider = getBearerTokenProvider( credential, 'https://cognitiveservices.azure.com/.default');
const client = new AzureOpenAI({ endpoint, azureADTokenProvider: tokenProvider, apiVersion: '2024-10-21', deployment: deploymentName,});
const response = await client.chat.completions.create({ model: deploymentName, messages: [{ role: 'user', content: 'Hello!' }],});
console.log(response.choices[0].message.content);