.NET AspireAzureOpenAI 集成(预览版)

包含:托管集成已包含 - Client 集成已包含Client 集成

AzureOpenAI 服务 提供对 OpenAI强大语言和嵌入模型的访问权限,并提供 Azure的安全和企业承诺。 通过 .NET AspireAzureOpenAI 集成,可以从 Azure 应用程序连接到 OpenAIOpenAI 服务或 .NET的 API。

托管集成

托管集成模型将 .NET.NET AspireAzure OpenAIAzureOpenAI 资源整合为 AzureOpenAIResource。 若要访问这些类型和 API 以在 应用主机 项目中表达它们,请安装 📦Aspire.Hosting.Azure.CognitiveServices NuGet 包:

dotnet add package Aspire.Hosting.Azure.CognitiveServices

有关详细信息,请参阅 dotnet add package管理 .NET 应用中的包依赖项

添加 AzureOpenAI 资源

若要将 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...

前面的代码将名为 Azure 的 OpenAIopenai 资源添加到应用主机项目中。 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 相对应。

由预配生成的 Bicep

如果你不熟悉 Bicep,它是一种领域专用语言,用于定义 Azure 资源。 使用 .NET.NET 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_CognitiveServicesOpenAIContributor 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
  name: guid(openai.id, principalId, subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'a001fd3d-188f-4b5d-821b-7da978bf7442'))
  properties: {
    principalId: principalId
    roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'a001fd3d-188f-4b5d-821b-7da978bf7442')
    principalType: principalType
  }
  scope: openai
}

生成的 Bicep 作为起点,受 C# 中资源配置基础设施更改的影响。 直接对 Bicep 文件的自定义项所做的更改将被覆盖,因此请通过 C# 预配 API 进行更改,以确保它们反映在生成的文件中。

自定义预配基础结构

所有 .NET 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");
    });

前面的代码:

连接到现有 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...

有关将 AzureOpenAI 资源视为现有资源的详细信息,请参阅 使用现有 Azure 资源

注释

或者,您可以向应用主机添加连接字符串来代替表示 AzureOpenAI 资源。 此方法属于弱类型,不适用于角色分配或基础结构自定义。 有关详细信息,请参阅 添加带有连接字符串的现有Azure资源

Client 集成

若要开始 .NET 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)注册一个 OpenAIClientAzureOpenAIClientOpenAIClient的子类,允许你从 DI 请求任一类型。 这可确保代码不依赖于 Azure的特定功能,从而保持通用性。 AddAzureOpenAIClient 方法需要连接名称参数。

builder.AddAzureOpenAIClient(connectionName: "openai");

小提示

connectionName 参数必须与在应用主机项目中添加 AzureOpenAI 资源时使用的名称匹配。 有关详细信息,请参阅 添加 AzureOpenAI 资源

添加 OpenAIClient后,可以使用依赖项注入检索客户端实例:

public class ExampleService(OpenAIClient client)
{
    // Use client...
}

有关详细信息,请参阅:

添加注册的 AzureOpenAIIChatClient 客户端

如果有兴趣将 IChatClient 接口与 OpenAI 客户端配合使用,只需将以下任一 API 链接到 AddAzureOpenAIClient 方法:

例如,请考虑将 IChatClient 添加到 DI 容器的以下 C# 代码:

builder.AddAzureOpenAIClient(connectionName: "openai")
       .AddChatClient("deploymentName");

同样,可以使用以下 C# 代码添加带键值的项 IChatClient

builder.AddAzureOpenAIClient(connectionName: "openai")
       .AddKeyedChatClient("serviceKey", "deploymentName");

有关 IChatClient 及其相应库的详细信息,请参阅 人工智能 .NET(预览版)

配置 AzureOpenAI 客户端设置

.NET AspireAzureOpenAI 库提供了一组设置来配置 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) 扩展方法,用于根据提供的连接字符串注册 OpenAIClientAzureOpenAIClient 实例。 此方法遵循以下规则:

  • 如果 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");

小提示

有效的连接字符串必须至少包含 EndpointKey

请考虑以下示例连接字符串,以及它们是否注册了 OpenAIClientAzureOpenAIClient

示例连接字符串 已注册的客户端类型
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) 扩展方法根据提供的连接字符串注册 OpenAIClientAzureOpenAIClient 实例。

请考虑以下示例:

builder.AddKeyedOpenAIClientFromConfiguration("openai");

该方法遵循在配置 Azure添加 OpenAI 客户端所详述的规则。

配置

.NET AspireAzureOpenAI 库提供了多个选项,用于根据项目的要求和约定配置 AzureOpenAI 连接。 需要提供 EndpointConnectionString 中的任意一个。

使用连接字符串

使用 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 密钥

使用配置提供程序

.NET AspireAzureOpenAI 集成支持 Microsoft.Extensions.Configuration。 它使用 AzureOpenAISettings 键从配置加载 Aspire:Azure:AI:OpenAI。 配置某些选项的示例 appsettings.json

{
  "Aspire": {
    "Azure": {
      "AI": {
        "OpenAI": {
          "DisableTracing": false
        }
      }
    }
  }
}

有关完整的 AzureOpenAI 客户端集成 JSON 方案,请参阅 Aspire。Azure。AI。OpenAI/ConfigurationSchema.json

使用内联委托

您可以传递 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"));

可观测性和遥测

.NET.NET Aspire 集成会自动设置日志记录、跟踪和指标配置,这些配置有时称为 可观测性的支柱。 有关集成可观测性和遥测的详细信息,请参阅 .NET.NET Aspire 集成概述。 根据支持服务,某些集成可能仅支持其中一些功能。 例如,某些集成支持日志记录和跟踪,但不支持指标。 也可以使用 配置 部分中介绍的技术禁用遥测功能。

伐木

.NET AspireAzureOpenAI 集成使用以下日志类别:

  • Azure
  • Azure.Core
  • Azure.Identity

追踪

.NET AspireAzureOpenAI 集成使用 OpenTelemetry 发出跟踪活动,用于执行与 OpenAIClient相关的操作。

重要

跟踪在此集成中目前处于实验阶段。 若要选择加入,请将 OPENAI_EXPERIMENTAL_ENABLE_OPEN_TELEMETRY 环境变量设置为 true1,或在应用启动期间调用 AppContext.SetSwitch("OpenAI.Experimental.EnableOpenTelemetry", true))

另请参阅