包含: - 
Client 集成
Azure OpenAI 服务 提供对 OpenAI强大语言和嵌入模型的访问权限,并提供 Azure的安全和企业承诺。 通过 AspireAzureOpenAI 集成,可以从 Azure 应用程序连接到 OpenAIOpenAI 服务或 .NET的 API。
托管集成
将AspireAzure OpenAI宿主集成资源AzureOpenAI建模为AzureOpenAIResource。 若要访问这些类型和 API 以在 AppHost 项目中表达它们,请安装 。📦AspireHosting.Azure.CognitiveServices NuGet 包:
dotnet add package Aspire.Hosting.Azure.CognitiveServices
有关详细信息,请参阅 dotnet add package 或 管理 .NET 应用中的包依赖项。
添加 AzureOpenAI 资源
若要向 AppHost 项目添加一个 AzureOpenAIResource ,请调用 AddAzureOpenAI 方法:
var builder = DistributedApplication.CreateBuilder(args);
var openai = builder.AddAzureOpenAI("openai");
builder.AddProject<Projects.ExampleProject>()
       .WithReference(openai);
// After adding all resources, run the app...
前面的代码将一个名为 AzureOpenAIopenai AppHost 项目的资源添加到该资源。 
              WithReference 方法将连接信息传递给 ExampleProject 项目。
重要
调用 AddAzureOpenAI时,它会隐式调用 AddAzureProvisioning(IDistributedApplicationBuilder),这增加了在应用启动期间动态生成 Azure 资源的支持。 应用程序必须配置相应的订阅和位置。 有关详细信息,请参阅 本地预配:配置。
添加 AzureOpenAI 部署资源
若要添加 AzureOpenAI 部署资源,请调用 AddDeployment(IResourceBuilder<AzureOpenAIResource>, String, String, String) 方法:
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...
前面的代码:
- 添加一个名为Azure的OpenAIopenai资源。
- 添加一个名为 Azure 、模型名称为 OpenAI的 previewgpt-4.5-preview部署资源。 模型名称必须与 Azure 服务中的 OpenAI 相对应。
连接到现有 AzureOpenAI 服务
你可能有一个现有的 AzureOpenAI 服务需要连接。 可以连续调用来标注 AzureOpenAIResource 是现有资源:
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...
重要
调用RunAsExisting或PublishAsExistingAsExisting处理订阅中Azure已存在的资源的方法时,必须将某些配置值添加到 AppHost,以确保Aspire找到它们。 必要的配置值包括 SubscriptionId、 AllowResourceGroupCreation、 ResourceGroup 和 Location。 如果未设置它们,仪表板中 Aspire 会显示“缺少配置”错误。 有关如何设置它们的详细信息,请参阅 “配置”。
有关将 AzureOpenAI 资源视为现有资源的详细信息,请参阅 使用现有 Azure 资源。
注释
或者,可以向 AppHost 添加连接字符串,而不是表示 AzureOpenAI 资源。 此方法属于弱类型,不适用于角色分配或基础结构自定义。 有关详细信息,请参阅 添加带有连接字符串的现有Azure资源。
由预配生成的 Bicep
如果你不熟悉 Bicep,它是一种领域专用语言,用于定义 Azure 资源。 使用 Aspire时,无需手动编写 Bicep,而是预配 API 会为你生成 Bicep。 发布应用程序时,生成的 Bicep 会配置具有标准默认值的 AzureOpenAI 资源。
@description('The location for the resource(s) to be deployed.')
param location string = resourceGroup().location
resource openai 'Microsoft.CognitiveServices/accounts@2024-10-01' = {
  name: take('openai-${uniqueString(resourceGroup().id)}', 64)
  location: location
  kind: 'OpenAI'
  properties: {
    customSubDomainName: toLower(take(concat('openai', uniqueString(resourceGroup().id)), 24))
    publicNetworkAccess: 'Enabled'
    disableLocalAuth: true
  }
  sku: {
    name: 'S0'
  }
  tags: {
    'aspire-resource-name': 'openai'
  }
}
resource preview 'Microsoft.CognitiveServices/accounts/deployments@2024-10-01' = {
  name: 'preview'
  properties: {
    model: {
      format: 'OpenAI'
      name: 'gpt-4.5-preview'
      version: '2025-02-27'
    }
  }
  sku: {
    name: 'Standard'
    capacity: 8
  }
  parent: openai
}
output connectionString string = 'Endpoint=${openai.properties.endpoint}'
output name string = openai.name
上面的 Bicep 模块负责预配 Azure 认知服务资源。 此外,在单独的模块中为 Azure 资源创建角色分配:
@description('The location for the resource(s) to be deployed.')
param location string = resourceGroup().location
param openai_outputs_name string
param principalType string
param principalId string
resource openai 'Microsoft.CognitiveServices/accounts@2024-10-01' existing = {
  name: openai_outputs_name
}
resource openai_CognitiveServicesOpenAIUser 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
  name: guid(openai.id, principalId, subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '5e0bd9bd-7b93-4f28-af87-19fc36ad61bd'))
  properties: {
    principalId: principalId
    roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '5e0bd9bd-7b93-4f28-af87-19fc36ad61bd')
    principalType: principalType
  }
  scope: openai
}
生成的 Bicep 作为起点,受 C# 中资源配置基础设施更改的影响。 直接对 Bicep 文件的自定义项所做的更改将被覆盖,因此请通过 C# 预配 API 进行更改,以确保它们反映在生成的文件中。
自定义预配基础结构
所有 AspireAzure 资源都是 AzureProvisioningResource 类型的子类。 通过使用 Azure API 提供一个流畅的 API 来配置 ConfigureInfrastructure<T>(IResourceBuilder<T>, Action<AzureResourceInfrastructure>) 资源,从而支持生成 Bicep 的自定义:
builder.AddAzureOpenAI("openai")
    .ConfigureInfrastructure(infra =>
    {
        var resources = infra.GetProvisionableResources();
        var account = resources.OfType<CognitiveServicesAccount>().Single();
        account.Sku = new CognitiveServicesSku
        {
            Tier = CognitiveServicesSkuTier.Enterprise,
            Name = "E0"
        };
        account.Tags.Add("ExampleKey", "Example value");
    });
前面的代码:
- 将一个调用链接至 ConfigureInfrastructure API:- 
              infra参数是 AzureResourceInfrastructure 类型的实例。
- 通过调用 GetProvisionableResources() 方法检索可预配资源。
- 已检索单个 CognitiveServicesAccount 资源。
- 
              CognitiveServicesAccount.Sku 属性分配给具有 CognitiveServicesSku 名称和 E0层的新 CognitiveServicesSkuTier.Enterprise 实例。
- 在认知服务资源上添加了一个标记,键为 ExampleKey,值为Example value。
 
- 
              
Client 集成
若要开始 AspireAzureOpenAI 客户端集成,请在使用客户端的项目中安装 📦Aspire、Azure、AI 和OpenAI 的 NuGet 包,也就是使用 AzureOpenAI 客户端的应用程序的项目。
dotnet add package Aspire.Azure.AI.OpenAI
添加 AzureOpenAI 客户端
在你客户端使用的项目的 Program.cs 文件中,在任何 AddAzureOpenAIClient(IHostApplicationBuilder, String, Action<AzureOpenAISettings>,
 Action<IAzureClientBuilder<AzureOpenAIClient,AzureOpenAIClientOptions>>) 上使用 IHostApplicationBuilder 方法为依赖注入(DI)注册一个 OpenAIClient。 
              AzureOpenAIClient 是 OpenAIClient的子类,允许你从 DI 请求任一类型。 这可确保代码不依赖于 Azure的特定功能,从而保持通用性。 
              AddAzureOpenAIClient 方法需要连接名称参数。
builder.AddAzureOpenAIClient(connectionName: "openai");
小提示
参数 connectionName 必须与在 AppHost 项目中添加 AzureOpenAI 资源时使用的名称匹配。 有关详细信息,请参阅 添加 AzureOpenAI 资源。
添加 OpenAIClient后,可以使用依赖项注入检索客户端实例:
public class ExampleService(OpenAIClient client)
{
    // Use client...
}
有关详细信息,请参阅:
- 
              
              Azure.人工智能。OpenAI 文档 中有关使用 OpenAIClient的示例。
- 请参阅 .NET中的依赖项注入以获取有关依赖项注入的详细信息。
- 快速入门:通过 AzureOpenAI 服务开始使用 GPT-35-Turbo 和 GPT-4。
添加注册的 AzureOpenAIIChatClient 客户端
如果有兴趣将 IChatClient 接口与 OpenAI 客户端配合使用,只需将以下任一 API 链接到 AddAzureOpenAIClient 方法:
- 
              AddChatClient(AspireOpenAIClientBuilder, String):在 IChatClient提供的服务中注册单例 AspireOpenAIClientBuilder。
- 
              AddKeyedChatClient(AspireOpenAIClientBuilder, String, String):在 IChatClient提供的服务中注册带键的单例 AspireOpenAIClientBuilder。
例如,请考虑将 IChatClient 添加到 DI 容器的以下 C# 代码:
builder.AddAzureOpenAIClient(connectionName: "openai")
       .AddChatClient("deploymentName");
同样,可以使用以下 C# 代码添加带键值的项 IChatClient:
builder.AddAzureOpenAIClient(connectionName: "openai")
       .AddKeyedChatClient("serviceKey", "deploymentName");
添加 IChatClient后,可以使用依赖项注入检索客户端实例:
public class ExampleService(IChatClient chatClient)
{
    public async Task<string> GetResponseAsync(string userMessage)
    {
        var response = await chatClient.CompleteAsync(userMessage);
        return response.Message.Text ?? string.Empty;
    }
}
有关 IChatClient 及其相应库的详细信息,请参阅 人工智能 .NET(预览版)。
配置 AzureOpenAI 客户端设置
              Aspire
              Azure
              OpenAI 库提供了一组设置来配置 AzureOpenAI 客户端。 
              AddAzureOpenAIClient 方法公开了一个类型为 configureSettings的可选 Action<AzureOpenAISettings>? 参数。 若要在行内配置设置,请考虑以下示例:
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);
    });
前面的代码将 AzureOpenAISettings.DisableTracing 属性设置为 true,并将 AzureOpenAISettings.Endpoint 属性设置为 AzureOpenAI 终结点。
配置 AzureOpenAI 客户端生成器选项
若要为客户端配置 AzureOpenAIClientOptions,可以使用 AddAzureOpenAIClient 方法。 此方法接受一个类型为 configureClientBuilder的可选参数 Action<IAzureClientBuilder<OpenAIClient, AzureOpenAIClientOptions>>?。 请考虑以下示例:
builder.AddAzureOpenAIClient(
    connectionName: "openai",
    configureClientBuilder: clientBuilder =>
    {
        clientBuilder.ConfigureOptions(options =>
        {
            options.UserAgentApplicationId = "CLIENT_ID";
        });
    });
客户端生成器是 IAzureClientBuilder<TClient,TOptions> 类型的实例,它提供用于配置客户端选项的 Fluent API。 前面的代码将 AzureOpenAIClientOptions.UserAgentApplicationId 属性设置为 CLIENT_ID。 有关详细信息,请参阅 ConfigureOptions(ChatClientBuilder, Action<ChatOptions>)。
从配置中添加 AzureOpenAI 客户端
此外,包还提供 AddOpenAIClientFromConfiguration(IHostApplicationBuilder, String) 扩展方法,用于根据提供的连接字符串注册 OpenAIClient 或 AzureOpenAIClient 实例。 此方法遵循以下规则:
- 如果 Endpoint属性为空或缺失,则使用提供的密钥注册OpenAIClient实例,例如Key={key};。
- 如果 IsAzure属性true,则注册AzureOpenAIClient;否则,注册OpenAIClient,例如,Endpoint={azure_endpoint};Key={key};IsAzure=true注册AzureOpenAIClient,而Endpoint=https://localhost:18889;Key={key}注册OpenAIClient。
- 如果 Endpoint属性包含".azure.",则注册AzureOpenAIClient;否则,将注册OpenAIClient,例如Endpoint=https://{account}.azure.com;Key={key};。
请考虑以下示例:
builder.AddOpenAIClientFromConfiguration("openai");
小提示
有效的连接字符串必须至少包含 Endpoint 或 Key。
请考虑以下示例连接字符串,以及它们是否注册了 OpenAIClient 或 AzureOpenAIClient:
| 示例连接字符串 | 已注册的客户端类型 | 
|---|---|
| Endpoint=https://{account_name}.openai.azure.com/;Key={account_key} | AzureOpenAIClient | 
| Endpoint=https://{account_name}.openai.azure.com/;Key={account_key};IsAzure=false | OpenAIClient | 
| Endpoint=https://{account_name}.openai.azure.com/;Key={account_key};IsAzure=true | AzureOpenAIClient | 
| Endpoint=https://localhost:18889;Key={account_key} | OpenAIClient | 
添加具有特定密钥的AzureOpenAI客户端
在某些情况下,可能需要使用不同的连接名称注册多个 OpenAIClient 实例。 若要注册密钥 AzureOpenAI 客户端,请调用 AddKeyedAzureOpenAIClient 方法:
builder.AddKeyedAzureOpenAIClient(name: "chat");
builder.AddKeyedAzureOpenAIClient(name: "code");
重要
使用密钥服务时,请确保 AzureOpenAI 资源配置两个命名连接,一个用于 chat,一个用于 code。
然后,可以使用依赖项注入检索客户端实例。 例如,若要从服务检索客户:
public class ExampleService(
    [KeyedService("chat")] OpenAIClient chatClient,
    [KeyedService("code")] OpenAIClient codeClient)
{
    // Use clients...
}
有关详细信息,请参阅 .NET中的键控服务。
从配置中添加标记 AzureOpenAI 的客户端
密钥 AzureOpenAI 客户端与非密钥客户端存在相同的功能和规则。 可以使用 AddKeyedOpenAIClientFromConfiguration(IHostApplicationBuilder, String) 扩展方法根据提供的连接字符串注册 OpenAIClient 或 AzureOpenAIClient 实例。
请考虑以下示例:
builder.AddKeyedOpenAIClientFromConfiguration("openai");
该方法遵循在配置 Azure添加 OpenAI 客户端所详述的规则。
配置
              Aspire
              Azure
              OpenAI 库提供了多个选项,用于根据项目的要求和约定配置 AzureOpenAI 连接。 需要提供 Endpoint 或 ConnectionString 中的任意一个。
使用连接字符串
使用 ConnectionStrings 配置部分中的连接字符串时,可以在调用 builder.AddAzureOpenAIClient时提供连接字符串的名称:
builder.AddAzureOpenAIClient("openai");
连接字符串是从 ConnectionStrings 配置部分检索的,并且有两种受支持的格式:
帐户终结点
建议的方法是使用 端点,该端点与 AzureOpenAISettings.Credential 属性一起使用来建立连接。 如果未配置凭据,则使用 DefaultAzureCredential。
{
  "ConnectionStrings": {
    "openai": "https://{account_name}.openai.azure.com/"
  }
}
有关详细信息,请参阅 在无钥情况下使用 AzureOpenAI。
连接字符串
或者,可以使用自定义连接字符串:
{
  "ConnectionStrings": {
    "openai": "Endpoint=https://{account_name}.openai.azure.com/;Key={account_key};"
  }
}
若要连接到非AzureOpenAI 服务,请删除 Endpoint 属性,仅设置 Key 属性以设置 API 密钥。
使用配置提供程序
              Aspire
              Azure
              OpenAI 集成支持 Microsoft.Extensions.Configuration。 它使用 AzureOpenAISettings 键从配置加载 Aspire:Azure:AI:OpenAI。 配置某些选项的示例 appsettings.json:
{
  "Aspire": {
    "Azure": {
      "AI": {
        "OpenAI": {
          "DisableTracing": false,
          "EnableSensitiveTelemetryData": false
        }
      }
    }
  }
}
有关完整的 AzureOpenAI 客户端集成 JSON 方案,请参阅 Aspire。Azure。AI。OpenAI/ConfigurationSchema.json。
使用命名配置
集成 AspireAzureOpenAI 支持命名配置,通过该配置,可以使用不同的设置来配置同一资源类型的多个实例。 命名配置使用连接名称作为主配置部分下的密钥。
{
  "Aspire": {
    "Azure": {
      "AI": {
        "OpenAI": {
          "openai1": {
            "Endpoint": "https://account1.openai.azure.com/",
            "DisableTracing": false
          },
          "openai2": {
            "Endpoint": "https://account2.openai.azure.com/",
            "DisableTracing": true
          }
        }
      }
    }
  }
}
在此示例中,当调用openai1时,可以使用openai2和AddAzureOpenAIClient作为连接名称。
builder.AddAzureOpenAIClient("openai1");
builder.AddAzureOpenAIClient("openai2");
命名配置优先于顶级配置。 如果同时提供这两种设置,则命名配置中的设置将替代顶级设置。
使用内联委托
您可以传递 Action<AzureOpenAISettings> configureSettings 委托,以内联方式设置部分或全部选项,例如在代码中禁用跟踪功能:
builder.AddAzureOpenAIClient(
    "openai",
    static settings => settings.DisableTracing = true);
可以通过 Action<IAzureClientBuilder<OpenAIClient, OpenAIClientOptions>> configureClientBuilder 方法的可选 AddAzureOpenAIClient 参数设置 OpenAIClientOptions。 例如,若要设置此客户端的客户端 ID:
builder.AddAzureOpenAIClient(
    "openai",
    configureClientBuilder: builder => builder.ConfigureOptions(
        options => options.Diagnostics.ApplicationId = "CLIENT_ID"));
可观测性和遥测
Aspire 集成会自动设置日志记录、跟踪和指标配置,这些配置有时称为 可观测性支柱。 有关集成可观测性和遥测的详细信息,请参阅 Aspire 集成概述。 根据支持服务,某些集成可能仅支持其中一些功能。 例如,某些集成支持日志记录和跟踪,但不支持指标。 也可以使用 配置 部分中介绍的技术禁用遥测功能。
伐木
Aspire Azure OpenAI 集成使用以下日志类别:
- Azure
- Azure.Core
- Azure.Identity
追踪
Aspire Azure OpenAI 集成将使用 OpenTelemetry 发出以下跟踪活动:
- 
              Experimental.Microsoft.Extensions.AI— Microsoft.Extensions.AI 用于记录 AI 操作
重要
仅当使用来自 Microsoft.Extensions.AI 的 IChatClient 接口时,才会默认记录遥测数据。 原始 OpenAIClient 调用不会自动生成遥测。
在遥测中配置敏感数据
默认情况下,遥测包括令牌计数等元数据,但不包括原始输入和输出(如消息内容)。 若要在遥测中包括潜在的敏感信息,请设置 EnableSensitiveTelemetryData 配置选项:
builder.AddAzureOpenAIClient(
    connectionName: "openai",
    configureSettings: settings =>
    {
        settings.EnableSensitiveTelemetryData = true;
    })
    .AddChatClient("deploymentName");
或通过配置:
{
  "Aspire": {
    "Azure": {
      "AI": {
        "OpenAI": {
          "EnableSensitiveTelemetryData": true
        }
      }
    }
  }
}
或者,可以通过设置环境变量来启用敏感数据捕获:
OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=true
使用基础库遥测
如果需要直接从基础 OpenAI 库访问遥测数据,可以手动将相应的活动源和计量添加到 OpenTelemetry 配置:
builder.Services.AddOpenTelemetry()
    .WithTracing(tracing => tracing.AddSource("OpenAI.*"))
    .WithMetrics(metrics => metrics.AddMeter("OpenAI.*"));
但是,你需要通过在应用启动期间将环境变量OpenAI设置为OPENAI_EXPERIMENTAL_ENABLE_OPEN_TELEMETRY或调用true来启用AppContext.SetSwitch("OpenAI.Experimental.EnableOpenTelemetry", true)库中的实验遥测支持。