含まれているもの: ホスティング統合 —および—
Client 統合
AzureOpenAI サービス は、OpenAIの強力な言語モデルと埋め込みモデルへのアクセスを、Azureのセキュリティとエンタープライズの確約と共に提供します。 .NET AspireAzureOpenAI 統合により、Azure アプリケーションから OpenAIOpenAI Service または .NET's API に接続できます。
ホスティング統合
ホスティング統合モデル .NET.NET AspireAzure OpenAI は、リソースを Azureとして OpenAIAzureOpenAIResource します。 アプリ ホスト プロジェクト内でそれらを表現するためにこれらの型と API にアクセスするには、📦Aspire.ホスティング.Azure.CognitiveServices NuGet パッケージをインストールします。
dotnet add package Aspire.Hosting.Azure.CognitiveServices
詳細については、「dotnet パッケージ の追加」または「.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という名前の OpenAI
openai
リソースを追加します。 - モデル名が Azureの OpenAI という名前の
preview
gpt-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 Cognitive Services リソースをプロビジョニングするモジュールです。 さらに、ロールの割り当ては、別のモジュールで 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 型のサブクラスです。 これにより、生成されたBicepをカスタマイズするために、Azureリソースを構成する流暢なAPIを提供することが、ConfigureInfrastructure<T>(IResourceBuilder<T>, Action<AzureResourceInfrastructure>) APIを使用して可能になります。
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 の新しいインスタンスに割り当てられます。 - Cognitive Services リソースに、キーが
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 です。
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
パラメーターは、アプリ ホスト プロジェクトに AzureOpenAI リソースを追加するときに使用する名前と一致する必要があります。 詳細については、「AzureOpenAI リソースを追加する」を参照してください。
OpenAIClient
を追加した後、依存関係の挿入を使用してクライアント インスタンスを取得できます。
public class ExampleService(OpenAIClient client)
{
// Use client...
}
詳細については、以下を参照してください。
- Azure.AI.OpenAI 用ドキュメント にある例を参考に、
OpenAIClient
を使用する方法を示します。 - 依存性注入の詳細については、.NETの依存性注入を参照してください。
- クイック スタート: AzureOpenAI Serviceで GPT-35-Turbo と GPT-4 の使用を開始します。
登録済みの Azure である OpenAIIChatClient
クライアントを追加する
IChatClient クライアントで OpenAI インターフェイスを使用する場合は、次のいずれかの API を AddAzureOpenAIClient
メソッドにチェーンします。
- AddChatClient(AspireOpenAIClientBuilder, String):
IChatClient
によって提供されるサービスにシングルトン AspireOpenAIClientBuilder を登録します。 - AddKeyedChatClient(AspireOpenAIClientBuilder, String, String):
IChatClient
によって提供されるサービスにキー付きシングルトン AspireOpenAIClientBuilder を登録します。
たとえば、DI コンテナーに IChatClient
を追加する次の 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";
});
});
クライアント ビルダーは、クライアント オプションを構成するための fluent API を提供する、IAzureClientBuilder<TClient,TOptions> 型のインスタンスです。 上記のコードは、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 リソースで 2 つの名前付き接続 (1 つは chat
用、1 つは 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 AspireAzureOpenAI ライブラリには、プロジェクトの要件と規則に基づいて AzureOpenAI 接続を構成するための複数のオプションが用意されています。 Endpoint
または ConnectionString
を指定する必要があります。
接続文字列を使用する
ConnectionStrings
構成セクションの接続文字列を使用する場合は、builder.AddAzureOpenAIClient
を呼び出すときに接続文字列の名前を指定できます。
builder.AddAzureOpenAIClient("openai");
接続文字列は ConnectionStrings
構成セクションから取得され、次の 2 つの形式がサポートされています。
アカウント エンドポイント
推奨される方法は、エンドポイントを使用することです。これは、AzureOpenAISettings.Credential
プロパティと連携して接続を確立します。 資格情報が構成されていない場合は、DefaultAzureCredential が使用されます。
{
"ConnectionStrings": {
"openai": "https://{account_name}.openai.azure.com/"
}
}
詳細については、「Azureせずに OpenAI を使用する」を参照してください。
接続文字列
または、カスタム接続文字列を使用できます。
{
"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.人工知能。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 AspireAzureOpenAI 統合では、次のログ カテゴリが使用されます。
Azure
Azure.Core
Azure.Identity
追跡
.NET AspireAzureOpenAI 統合は、OpenTelemetryで実行された操作に対して OpenAIClient
を使用してトレース アクティビティを出力します。
重要
トレースは現在、この統合によって試験段階にあります。 オプトインするには、OPENAI_EXPERIMENTAL_ENABLE_OPEN_TELEMETRY
環境変数を true
または 1
に設定するか、アプリの起動時に AppContext.SetSwitch("OpenAI.Experimental.EnableOpenTelemetry", true))
を呼び出します。
参照
.NET Aspire