.NET Aspire Azure OpenAI 集成(预览版)
包括: 托管集成和
Client 集成
Azure OpenAI 服务 提供对 OpenAI强大语言和嵌入模型的访问权限,并提供 Azure的安全和企业承诺。 通过 .NET AspireAzureOpenAI 集成,可以从 .NET 应用程序连接到 AzureOpenAI 服务或 OpenAI的 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...
前面的代码将名为 openai
的 AzureOpenAI 资源添加到应用主机项目中。
WithReference 方法将连接信息传递给 ExampleProject
项目。
重要
调用 AddAzureOpenAI时,它会隐式调用 AddAzureProvisioning(IDistributedApplicationBuilder),这增加了在应用启动期间动态生成 Azure 资源的支持。 应用程序必须配置相应的订阅和位置。 有关详细信息,请参阅 本地预配:配置。
添加 AzureOpenAI 部署资源
若要添加 AzureOpenAI 部署资源,请调用 AddDeployment(IResourceBuilder<AzureOpenAIResource>, AzureOpenAIDeployment) 方法:
var builder = DistributedApplication.CreateBuilder(args);
var openai = builder.AddAzureOpenAI("openai");
openai.AddDeployment(
new AzureOpenAIDeployment(
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...
前面的代码:
- 添加名为
openai
的 AzureOpenAI 资源。 - 添加一个名为
preview
、模型名称为gpt-4.5-preview
的 AzureOpenAI 部署资源。 模型名称必须与 AzureOpenAI 服务中的 可用模型 相对应。
生成的配置脚本 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
param principalType string
param principalId string
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 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
}
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}'
前面的 Bicep 是一个模块,它使用以下默认值预配 Azure 认知服务资源:
-
location
:资源组的位置。 -
principalType
:认知服务资源的主体类型。 -
principalId
:认知服务资源的主体 ID。 -
openai
:认知服务帐户资源。-
kind
:资源类型,设置为OpenAI
。 -
properties
:资源的属性。-
customSubDomainName
:针对某个资源的自定义子域名,基于资源组 ID 的唯一字符串。 -
publicNetworkAccess
:设置为Enabled
。 -
disableLocalAuth
:设置为true
。
-
-
sku
:资源的 SKU,设置为S0
。
-
-
openai_CognitiveServicesOpenAIContributor
:基于内置Azure Cognitive Services OpenAI Contributor
角色的认知服务资源所有者。 有关更多信息,请参阅 Azure 认知服务 OpenAI 贡献者。 -
preview
:基于preview
的名称的部署资源。-
properties
:部署资源的属性。-
format
:部署资源的格式,设置为OpenAI
。 -
modelName
:部署资源的模型名称,设置为gpt-4.5-preview
。 -
modelVersion
:部署资源的模型版本,设置为2025-02-27
。
-
-
-
connectionString
:连接字符串,包含认知服务资源的终结点。
生成的 Bicep 是一个起始点,可以根据您的具体需求进行自定义。
自定义预配基础结构
所有 .NET AspireAzure 资源都是 AzureProvisioningResource 类型的子类。 通过使用 ConfigureInfrastructure<T>(IResourceBuilder<T>, Action<AzureResourceInfrastructure>) API 提供一个流畅的 API 来配置 Azure 资源,从而支持生成 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 属性分配给具有
E0
名称和 CognitiveServicesSkuTier.Enterprise 层的新 CognitiveServicesSku 实例。 - 在认知服务资源上添加了一个标记,键为
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 资源。 这是一种仅依赖于 string
值的弱类型化方法。 若要向现有 AzureOpenAI 服务添加连接,请调用 AddConnectionString 方法:
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...
注释
连接字符串用于表示各种连接信息,包括数据库连接、消息代理、终结点 URI 和其他服务。 在 .NET.NET Aspire 名词中,术语“连接字符串”用于表示任何类型的连接信息。
连接字符串在应用主机的配置(通常位于用户机密)的 ConnectionStrings
部分下进行配置:
{
"ConnectionStrings": {
"openai": "https://{account_name}.openai.azure.com/"
}
}
有关详细信息,请参阅 使用连接字符串添加现有 Azure 资源。
Client 集成
若要开始 .NET AspireAzureOpenAI 客户端集成,请在使用客户端的项目中安装 📦Aspire、Azure、AI 和OpenAI 的 NuGet 包,也就是使用 AzureOpenAI 客户端的应用程序的项目。
dotnet add package Aspire.Azure.AI.OpenAI
添加 AzureOpenAI 客户端
在你客户端使用的项目的 Program.cs 文件中,在任何 IHostApplicationBuilder 上使用 AddAzureOpenAIClient(IHostApplicationBuilder, String, Action<AzureOpenAISettings>,
Action<IAzureClientBuilder<AzureOpenAIClient,AzureOpenAIClientOptions>>) 方法为依赖注入(DI)注册一个 OpenAIClient
。
AzureOpenAIClient
是 OpenAIClient
的子类,允许你从 DI 请求任一类型。 这可确保代码不依赖于 Azure的特定功能,从而保持通用性。
AddAzureOpenAIClient
方法需要连接名称参数。
builder.AddAzureOpenAIClient(connectionName: "openai");
小提示
connectionName
参数必须与在应用主机项目中添加 AzureOpenAI 资源时使用的名称匹配。 有关详细信息,请参阅 添加 AzureOpenAI 资源。
添加 OpenAIClient
后,可以使用依赖项注入检索客户端实例:
public class ExampleService(OpenAIClient client)
{
// Use client...
}
有关详细信息,请参阅:
-
Azure.人工智能。OpenAI 文档 中有关使用
OpenAIClient
的示例。 - 请参阅 .NET中的依赖项注入以获取有关依赖项注入的详细信息。
- 快速入门:通过 AzureOpenAI 服务开始使用 GPT-35-Turbo 和 GPT-4。
使用已注册的 IChatClient
添加 AzureOpenAI 客户端
如果有兴趣将 IChatClient 接口与 OpenAI 客户端配合使用,只需将以下任一 API 链接到 AddAzureOpenAIClient
方法:
-
AddChatClient(AspireOpenAIClientBuilder, String):在 AspireOpenAIClientBuilder提供的服务中注册单一实例
IChatClient
。 -
AddKeyedChatClient(AspireOpenAIClientBuilder, String, String):在 AspireOpenAIClientBuilder提供的服务中注册带键的单例
IChatClient
。
例如,请考虑将 IChatClient
添加到 DI 容器的以下 C# 代码:
builder.AddAzureOpenAIClient(connectionName: "openai")
.AddChatClient("deploymentName");
同样,可以使用以下 C# 代码添加带键值的项 IChatClient
:
builder.AddAzureOpenAIClient(connectionName: "openai")
.AddKeyedChatClient("serviceKey", "deploymentName");
有关 IChatClient
及其相应库的详细信息,请参阅 人工智能 .NET(预览版)。
配置 AzureOpenAI 客户端设置
.NET Aspire
Azure
OpenAI 库提供了一组设置来配置 AzureOpenAI 客户端。
AddAzureOpenAIClient
方法公开了一个类型为 Action<AzureOpenAISettings>?
的可选 configureSettings
参数。 若要在行内配置设置,请考虑以下示例:
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 方法。 此方法接受一个类型为 Action<IAzureClientBuilder<OpenAIClient, AzureOpenAIClientOptions>>?
的可选参数 configureClientBuilder
。 请考虑以下示例:
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");
该方法遵循在配置 中添加 AzureOpenAI 客户端所详述的规则。
配置
.NET 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 密钥。
使用配置提供程序
.NET Aspire
Azure
OpenAI 集成支持 Microsoft.Extensions.Configuration。 它使用 Aspire:Azure:AI:OpenAI
键从配置加载 AzureOpenAISettings
。 配置某些选项的示例 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);
可以通过 AddAzureOpenAIClient
方法的可选 Action<IAzureClientBuilder<OpenAIClient, OpenAIClientOptions>> configureClientBuilder
参数设置 OpenAIClientOptions。 例如,若要设置此客户端的客户端 ID:
builder.AddAzureOpenAIClient(
"openai",
configureClientBuilder: builder => builder.ConfigureOptions(
options => options.Diagnostics.ApplicationId = "CLIENT_ID"));
可观测性和遥测
.NET .NET Aspire 集成会自动设置日志记录、跟踪和指标配置,这些配置有时称为 可观测性的支柱。 有关集成可观测性和遥测的详细信息,请参阅 .NET.NET Aspire 集成概述。 根据支持服务,某些集成可能仅支持其中一些功能。 例如,某些集成支持日志记录和跟踪,但不支持指标。 也可以使用 配置 部分中介绍的技术禁用遥测功能。
伐木
.NET Aspire Azure OpenAI 集成使用以下日志类别:
Azure
Azure.Core
Azure.Identity
追踪
.NET Aspire
Azure
OpenAI 集成使用 OpenTelemetry 发出跟踪活动,用于执行与 OpenAIClient
相关的操作。
重要
跟踪在此集成中目前处于实验阶段。 若要选择加入,请将 OPENAI_EXPERIMENTAL_ENABLE_OPEN_TELEMETRY
环境变量设置为 true
或 1
,或在应用启动期间调用 AppContext.SetSwitch("OpenAI.Experimental.EnableOpenTelemetry", true))
。