Includes:
Hosting integration and
Client integration
Azure OpenAI Service provides access to OpenAI's powerful language and embedding models with the security and enterprise promise of Azure. The .NET Aspire Azure OpenAI integration enables you to connect to Azure OpenAI Service or OpenAI's API from your .NET applications.
var builder = DistributedApplication.CreateBuilder(args);
var openai = builder.AddAzureOpenAI("openai");
builder.AddProject<Projects.ExampleProject>()
.WithReference(openai);
// After adding all resources, run the app...
The preceding code adds an Azure OpenAI resource named openai to the app host project. The WithReference method passes the connection information to the ExampleProject project.
var builder = DistributedApplication.CreateBuilder(args);
var openai = builder.AddAzureOpenAI("openai");
openai.AddDeployment(
name: "preview",
modelName: "gpt-4.5-preview",
modelVersion: "2025-02-27");
builder.AddProject<Projects.ExampleProject>()
.WithReference(openai)
.WaitFor(openai);
// After adding all resources, run the app...
The preceding code:
Adds an Azure OpenAI resource named openai.
Adds an Azure OpenAI deployment resource named preview with a model name of gpt-4.5-preview. The model name must correspond to an available model in the Azure OpenAI service.
Provisioning-generated Bicep
If you're new to Bicep, it's a domain-specific language for defining Azure resources. With .NET Aspire, you don't need to write Bicep by-hand, instead the provisioning APIs generate Bicep for you. When you publish your app, the generated Bicep provisions an Azure OpenAI resource with standard defaults.
The preceding Bicep is a module that provisions an Azure Cognitive Services resource. Additionally, role assignments are created for the Azure resource in a separate module:
The generated Bicep is a starting point and is influenced by changes to the provisioning infrastructure in C#. Customizations to the Bicep file directly will be overwritten, so make changes through the C# provisioning APIs to ensure they are reflected in the generated files.
A tag is added to the Cognitive Services resource with a key of ExampleKey and a value of Example value.
Connect to an existing Azure OpenAI service
You might have an existing Azure OpenAI service that you want to connect to. You can chain a call to annotate that your AzureOpenAIResource is an existing resource:
var builder = DistributedApplication.CreateBuilder(args);
var existingOpenAIName = builder.AddParameter("existingOpenAIName");
var existingOpenAIResourceGroup = builder.AddParameter("existingOpenAIResourceGroup");
var openai = builder.AddAzureOpenAI("openai")
.AsExisting(existingOpenAIName, existingOpenAIResourceGroup);
builder.AddProject<Projects.ExampleProject>()
.WithReference(openai);
// After adding all resources, run the app...
For more information on treating Azure OpenAI resources as existing resources, see Use existing Azure resources.
Alternatively, instead of representing an Azure OpenAI resource, you can add a connection string to the app host. Which is a weakly-typed approach that's based solely on a string value. To add a connection to an existing Azure OpenAI service, call the AddConnectionString method:
var builder = DistributedApplication.CreateBuilder(args);
var openai = builder.ExecutionContext.IsPublishMode
? builder.AddAzureOpenAI("openai")
: builder.AddConnectionString("openai");
builder.AddProject<Projects.ExampleProject>()
.WithReference(openai);
// After adding all resources, run the app...
Note
Connection strings are used to represent a wide range of connection information, including database connections, message brokers, endpoint URIs, and other services. In .NET Aspire nomenclature, the term "connection string" is used to represent any kind of connection information.
The connection string is configured in the app host's configuration, typically under User Secrets, under the ConnectionStrings section:
To get started with the .NET Aspire Azure OpenAI client integration, install the 📦 Aspire.Azure.AI.OpenAI NuGet package in the client-consuming project, that is, the project for the application that uses the Azure OpenAI client.
The connectionName parameter must match the name used when adding the Azure OpenAI resource in the app host project. For more information, see Add an Azure OpenAI resource.
After adding the OpenAIClient, you can retrieve the client instance using dependency injection:
public class ExampleService(OpenAIClient client)
{
// Use client...
}
Add Azure OpenAI client with registered IChatClient
If you're interested in using the IChatClient interface, with the OpenAI client, simply chain either of the following APIs to the AddAzureOpenAIClient method:
The .NET Aspire Azure OpenAI library provides a set of settings to configure the Azure OpenAI client. The AddAzureOpenAIClient method exposes an optional configureSettings parameter of type Action<AzureOpenAISettings>?. To configure settings inline, consider the following example:
builder.AddAzureOpenAIClient(
connectionName: "openai",
configureSettings: settings =>
{
settings.DisableTracing = true;
var uriString = builder.Configuration["AZURE_OPENAI_ENDPOINT"]
?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
settings.Endpoint = new Uri(uriString);
});
To configure the AzureOpenAIClientOptions for the client, you can use the AddAzureOpenAIClient method. This method takes an optional configureClientBuilder parameter of type Action<IAzureClientBuilder<OpenAIClient, AzureOpenAIClientOptions>>?. Consider the following example:
If the Endpoint attribute is empty or missing, an OpenAIClient instance is registered using the provided key, for example, Key={key};.
If the IsAzure attribute is true, an AzureOpenAIClient is registered; otherwise, an OpenAIClient is registered, for example, Endpoint={azure_endpoint};Key={key};IsAzure=true registers an AzureOpenAIClient, while Endpoint=https://localhost:18889;Key={key} registers an OpenAIClient.
If the Endpoint attribute contains ".azure.", an AzureOpenAIClient is registered; otherwise, an OpenAIClient is registered, for example, Endpoint=https://{account}.azure.com;Key={key};.
There might be situations where you want to register multiple OpenAIClient instances with different connection names. To register keyed Azure OpenAI clients, call the AddKeyedAzureOpenAIClient method:
The same functionality and rules exist for keyed Azure OpenAI clients as for the nonkeyed clients. You can use the AddKeyedOpenAIClientFromConfiguration(IHostApplicationBuilder, String) extension method to register an OpenAIClient or AzureOpenAIClient instance based on the provided connection string.
The .NET Aspire Azure OpenAI library provides multiple options to configure the Azure OpenAI connection based on the requirements and conventions of your project. Either a Endpoint or a ConnectionString is required to be supplied.
Use a connection string
When using a connection string from the ConnectionStrings configuration section, you can provide the name of the connection string when calling builder.AddAzureOpenAIClient:
builder.AddAzureOpenAIClient("openai");
The connection string is retrieved from the ConnectionStrings configuration section, and there are two supported formats:
Account endpoint
The recommended approach is to use an Endpoint, which works with the AzureOpenAISettings.Credential property to establish a connection. If no credential is configured, the DefaultAzureCredential is used.
In order to connect to the non-Azure OpenAI service, drop the Endpoint property and only set the Key property to set the API key.
Use configuration providers
The .NET Aspire Azure OpenAI integration supports Microsoft.Extensions.Configuration. It loads the AzureOpenAISettings from configuration by using the Aspire:Azure:AI:OpenAI key. Example appsettings.json that configures some of the options:
You can pass the Action<AzureOpenAISettings> configureSettings delegate to set up some or all the options inline, for example to disable tracing from code:
You can also set up the OpenAIClientOptions using the optional Action<IAzureClientBuilder<OpenAIClient, OpenAIClientOptions>> configureClientBuilder parameter of the AddAzureOpenAIClient method. For example, to set the client ID for this client:
.NET Aspire integrations automatically set up Logging, Tracing, and Metrics configurations, which are sometimes known as the pillars of observability. For more information about integration observability and telemetry, see .NET Aspire integrations overview. Depending on the backing service, some integrations may only support some of these features. For example, some integrations support logging and tracing, but not metrics. Telemetry features can also be disabled using the techniques presented in the Configuration section.
Logging
The .NET Aspire Azure OpenAI integration uses the following log categories:
Azure
Azure.Core
Azure.Identity
Tracing
The .NET Aspire Azure OpenAI integration emits tracing activities using OpenTelemetry for operations performed with the OpenAIClient.
Important
Tracing is currently experimental with this integration. To opt-in to it, set either the OPENAI_EXPERIMENTAL_ENABLE_OPEN_TELEMETRY environment variable to true or 1, or call AppContext.SetSwitch("OpenAI.Experimental.EnableOpenTelemetry", true)) during app startup.
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide.
.NET Aspire
feedback
.NET Aspire
is an open source project. Select a link to provide feedback:
Learn how to use the .NET Aspire Ollama hosting and client integration to host Ollama models using the Ollama container and accessing it via the OllamaSharp client.