次の方法で共有


.NET Aspire Azure OpenAI 統合 (プレビュー)

含まれるもの: ホスティング統合と Client 統合

Azure OpenAI サービス は、OpenAIの強力な言語モデルと埋め込みモデルへのアクセスを、Azureのセキュリティとエンタープライズの確約と共に提供します。 .NET Aspire Azure OpenAI 統合により、.NET アプリケーションから AzureOpenAI Service または OpenAI's API に接続できます。

ホスティング統合

ホスティング統合モデル .NET.NET AspireAzure OpenAI は、リソースを AzureOpenAIResourceとして AzureOpenAI します。 アプリ ホスト プロジェクト内でそれらを表現するためにこれらの型と API にアクセスするには、📦Aspire.ホスティング.Azure.CognitiveServices NuGet パッケージをインストールします。

dotnet add package Aspire.Hosting.Azure.CognitiveServices

詳細については、「dotnet パッケージ の追加」または「.NET アプリケーションでのパッケージの依存関係の管理」を参照してください。

Azure OpenAI リソースを追加する

アプリ ホスト プロジェクトに 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 リソースを動的に生成するためのサポートが追加されます。 アプリは、適切なサブスクリプションと場所を構成する必要があります。 詳細については、「ローカル プロビジョニング: 構成」を参照してください。

Azure OpenAI デプロイ リソースを追加する

Azure OpenAI デプロイ リソースを追加するには、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 リソースを追加します。
  • モデル名が gpt-4.5-previewpreview という名前の 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 Cognitive Services リソースを次の既定値でプロビジョニングするモジュールです。

  • location: リソース グループの場所。
  • principalType: Cognitive Services リソースの主なタイプ。
  • principalId: Cognitive Services リソースのプリンシパル ID。
  • openai: Cognitive Services アカウント リソース。
    • kind: リソースの種類。OpenAIに設定されます。
    • properties: リソースのプロパティ。
      • customSubDomainName: リソース グループ ID の一意の文字列に基づく、リソースのカスタム サブドメイン名。
      • publicNetworkAccess: Enabledに設定します。
      • disableLocalAuth: trueに設定します。
    • sku: S0に設定されたリソースの SKU。
  • openai_CognitiveServicesOpenAIContributor: 組み込みAzure Cognitive Services OpenAI Contributorロールに基づいたCognitive Servicesリソース所有者。 詳細については、「Azure Cognitive Services OpenAI Contributor」を参照してください。
  • preview: preview 名に基づくデプロイ リソース。
    • properties: デプロイ リソースのプロパティ。
      • format: OpenAIに設定されたデプロイ リソースの形式。
      • modelName: デプロイ リソースのモデル名。gpt-4.5-previewに設定されます。
      • modelVersion: デプロイ リソースのモデル バージョン。2025-02-27に設定されます。
  • connectionString: Cognitive Services リソースのエンドポイントを含む接続文字列。

生成された Bicep は開始点であり、特定の要件を満たすようにカスタマイズできます。

プロビジョニング インフラストラクチャをカスタマイズする

すべての .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");
    });

上記のコード:

既存の 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...

Azure OpenAI リソースを既存のリソースとして扱う方法の詳細については、「既存の 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 Aspire Azure OpenAI クライアントの統合を開始するには、クライアントを利用するプロジェクト、つまり AzureOpenAI クライアントを使用するアプリケーションのプロジェクトに 📦AspireNuGet パッケージをインストールします。Azure.AI.OpenAI です。

dotnet add package Aspire.Azure.AI.OpenAI

Azure OpenAI クライアントを追加する

クライアントを使用するプロジェクトの Program.cs ファイルで、任意の IHostApplicationBuilderAddAzureOpenAIClient(IHostApplicationBuilder, String, Action<AzureOpenAISettings>, Action<IAzureClientBuilder<AzureOpenAIClient,AzureOpenAIClientOptions>>) メソッドを使用して、依存関係の挿入 (DI) の OpenAIClient を登録します。 AzureOpenAIClientOpenAIClientのサブクラスであり、DI からいずれかの型を要求できます。 これにより、コードがAzure特有の機能に依存せず、一般的な状態を保つことが保証されます。 AddAzureOpenAIClient メソッドには、接続名パラメーターが必要です。

builder.AddAzureOpenAIClient(connectionName: "openai");

ヒント

connectionName パラメーターは、アプリ ホスト プロジェクトに AzureOpenAI リソースを追加するときに使用する名前と一致する必要があります。 詳細については、「AzureOpenAI リソースを追加する」を参照してください。

OpenAIClientを追加した後、依存関係の挿入を使用してクライアント インスタンスを取得できます。

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

詳細については、以下を参照してください。

登録済みの IChatClient である AzureOpenAI クライアントを追加する

OpenAI クライアントで IChatClient インターフェイスを使用する場合は、次のいずれかの API を AddAzureOpenAIClient メソッドにチェーンします。

たとえば、DI コンテナーに IChatClient を追加する次の 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";
        });
    });

クライアント ビルダーは、クライアント オプションを構成するための fluent API を提供する、IAzureClientBuilder<TClient,TOptions> 型のインスタンスです。 上記のコードは、AzureOpenAIClientOptions.UserAgentApplicationId プロパティを CLIENT_IDに設定します。 詳細については、ConfigureOptions(ChatClientBuilder, Action<ChatOptions>)を参照してください。

構成からクライアント AzureOpenAI 追加する

さらに、パッケージには、指定された接続文字列に基づいて OpenAIClient または AzureOpenAIClient インスタンスを登録する AddOpenAIClientFromConfiguration(IHostApplicationBuilder, String) 拡張メソッドが用意されています。 このメソッドは、次の規則に従います。

  • Endpoint 属性が空または不足している場合、OpenAIClient インスタンスは、指定されたキー (例: Key={key};) を使用して登録されます。
  • IsAzure 属性が trueされている場合は、AzureOpenAIClient が登録されます。それ以外の場合は、OpenAIClient が登録されます。たとえば、Endpoint={azure_endpoint};Key={key};IsAzure=trueAzureOpenAIClientを登録し、Endpoint=https://localhost:18889;Key={key}OpenAIClientを登録します。
  • Endpoint 属性に ".azure."が含まれている場合は、AzureOpenAIClient が登録されます。それ以外の場合は、OpenAIClient が登録されます (例: Endpoint=https://{account}.azure.com;Key={key};)。

次の例を確認してください。

builder.AddOpenAIClientFromConfiguration("openai");

ヒント

有効な接続文字列には、少なくとも Endpoint または Keyが含まれている必要があります。

次の接続文字列の例と、接続文字列が 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 リソースで 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 Aspire Azure OpenAI ライブラリには、プロジェクトの要件と規則に基づいて AzureOpenAI 接続を構成するための複数のオプションが用意されています。 Endpoint または ConnectionString を指定する必要があります。

接続文字列を使用する

ConnectionStrings 構成セクションの接続文字列を使用する場合は、builder.AddAzureOpenAIClientを呼び出すときに接続文字列の名前を指定できます。

builder.AddAzureOpenAIClient("openai");

接続文字列は ConnectionStrings 構成セクションから取得され、次の 2 つの形式がサポートされています。

アカウント エンドポイント

推奨される方法は、エンドポイントを使用することです。これは、AzureOpenAISettings.Credential プロパティと連携して接続を確立します。 資格情報が構成されていない場合は、DefaultAzureCredential が使用されます。

{
  "ConnectionStrings": {
    "openai": "https://{account_name}.openai.azure.com/"
  }
}

詳細については、「キーをせずに AzureOpenAI を使用する」を参照してください。

接続文字列

または、カスタム接続文字列を使用できます。

{
  "ConnectionStrings": {
    "openai": "Endpoint=https://{account_name}.openai.azure.com/;Key={account_key};"
  }
}

Azure OpenAI 以外のサービスに接続するには、Endpoint プロパティを削除し、key プロパティのみを設定して、API キー設定します。

構成プロバイダーを使用する

.NET Aspire Azure OpenAI 統合では、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);

AddAzureOpenAIClient メソッドの省略可能な Action<IAzureClientBuilder<OpenAIClient, OpenAIClientOptions>> configureClientBuilder パラメーターを使用して、OpenAIClientOptions を設定することもできます。 たとえば、このクライアントのクライアント ID を設定するには、次のようにします。

builder.AddAzureOpenAIClient(
    "openai",
    configureClientBuilder: builder => builder.ConfigureOptions(
        options => options.Diagnostics.ApplicationId = "CLIENT_ID"));

可観測性とテレメトリ

統合により、ログ記録、トレース、メトリックの構成が自動的に設定されます。これは、監視の柱 とも呼ばれます。 統合の可観測性とテレメトリの詳細については、統合の概要 参照してください。 バッキング サービスによっては、一部の統合でこれらの機能の一部のみがサポートされる場合があります。 たとえば、一部の統合ではログ記録とトレースがサポートされますが、メトリックはサポートされません。 テレメトリ機能は、「構成」セクションに記載されている手法を使用して無効にすることもできます。

伐採

.NET Aspire Azure OpenAI 統合では、次のログ カテゴリが使用されます。

  • Azure
  • Azure.Core
  • Azure.Identity

追跡

.NET Aspire Azure OpenAI 統合は、OpenAIClientで実行された操作に対して OpenTelemetry を使用してトレース アクティビティを出力します。

重要

トレースは現在、この統合によって試験段階にあります。 オプトインするには、OPENAI_EXPERIMENTAL_ENABLE_OPEN_TELEMETRY 環境変数を true または 1に設定するか、アプリの起動時に AppContext.SetSwitch("OpenAI.Experimental.EnableOpenTelemetry", true)) を呼び出します。

参照