次の方法で共有


OpenAI.Images.ImageClient を使用してイメージを生成する

このクイック スタートでは、 OpenAI.Images.ImageClient を使用して OpenAI または Azure OpenAI DALL-E AI モデルを使用してイメージを生成する .NET コンソール アプリを作成します。 これらのモデルは、テキスト プロンプトから画像を生成します。

前提条件

  • .NET 8.0 SDK 以降 - .NET 8.0 SDKをインストールします。
  • このサンプルを実行できるように、OpenAI API キー。

前提条件

セマンティック カーネルを使用して、この記事のタスクを実行することもできます。 セマンティック カーネルは、AI エージェントを構築し、最新の AI モデルを .NET アプリに統合できる軽量のオープンソース SDK です。

アプリを作成する

AI モデルに接続する .NET コンソール アプリを作成するには、次の手順を実行します。

  1. コンピューター上の空のディレクトリで、dotnet new コマンドを使用して新しいコンソール アプリを作成します。

    dotnet new console -o ImagesAI
    
  2. ディレクトリをアプリ フォルダーに変更します。

    cd ImagesAI
    
  3. 必要なパッケージをインストールします。

    dotnet add package Azure.AI.OpenAI
    dotnet add package Azure.Identity
    dotnet add package Microsoft.Extensions.Configuration
    dotnet add package Microsoft.Extensions.Configuration.UserSecrets
    
    dotnet add package OpenAI
    dotnet add package Microsoft.Extensions.Configuration
    dotnet add package Microsoft.Extensions.Configuration.UserSecrets
    
  4. Visual Studio Code または任意のエディターでアプリを開きます。

    code .
    

AI サービスを作成する

  1. Azure OpenAI サービスとモデルをプロビジョニングするには、 Azure OpenAI サービス リソースの作成とデプロイ に関する記事の手順を完了します。

  2. ターミナルまたはコマンド プロンプトから、プロジェクト ディレクトリのルートに移動します。

  3. 次のコマンドを実行して、サンプル アプリの Azure OpenAI エンドポイントとモデル名を構成します。

    dotnet user-secrets init
    dotnet user-secrets set AZURE_OPENAI_ENDPOINT <your-Azure-OpenAI-endpoint>
    dotnet user-secrets set AZURE_OPENAI_GPT_NAME <your-Azure-OpenAI-model-name>
    dotnet user-secrets set AZURE_OPENAI_API_KEY <your-Azure-OpenAI-key>
    

アプリを設定する

  1. ターミナルまたはコマンド プロンプトから .NET プロジェクトのルートに移動します。

  2. 次のコマンドを実行して、OpenAI API キーをサンプル アプリのシークレットとして構成します。

    dotnet user-secrets init
    dotnet user-secrets set OpenAIKey <your-OpenAI-key>
    dotnet user-secrets set ModelName <your-OpenAI-model-name>
    

アプリ コードを追加する

  1. Program.cs ファイルに、AI モデルに接続して認証するための次のコードを追加します。

    using Microsoft.Extensions.Configuration;
    using OpenAI.Images;
    using System.ClientModel;
    using Azure.AI.OpenAI;
    using Azure.Identity;
    
    // Retrieve the local secrets saved during the Azure deployment. If you skipped the deployment
    // because you already have an Azure OpenAI available, edit the following lines to use your information,
    // e.g. string openAIEndpoint = "https://cog-demo123.openai.azure.com/";
    var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
    string endpoint = config["AZURE_OPENAI_ENDPOINT"];
    string deployment = config["AZURE_OPENAI_DALLE_NAME"];
    
    // Create the Azure OpenAI ImageClient
    ImageClient client =
        new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential())
            .GetImageClient(deployment);
    
    // Generate the image
    GeneratedImage generatedImage = await client.GenerateImageAsync("""
        A postal card with an happy hiker waving and a beautiful mountain in the background.
        There is a trail visible in the foreground.
        The postal card has text in red saying: 'You are invited for a hike!'
        """, new ImageGenerationOptions { Size = GeneratedImageSize.W1024xH1024 });
    
    Console.WriteLine($"The generated image is ready at:\n{generatedImage.ImageUri}");
    

    DefaultAzureCredential は、ローカル ツールから認証資格情報を検索します。 azd テンプレートを使用して Azure OpenAI リソースをプロビジョニングしていない場合は、Visual Studio または Azure CLI へのサインインに使用したアカウントにAzure AI Developer ロールを割り当てる必要があります。 詳細については、「.NET を使用して Azure AI サービスに対する認証をする」を参照してください。

    // Licensed to the .NET Foundation under one or more agreements.
    // The .NET Foundation licenses this file to you under the MIT license.
    // See the LICENSE file in the project root for more information.
    using Microsoft.Extensions.Configuration;
    using OpenAI.Images;
    // Retrieve the local secrets that were set from the command line, using:
    // dotnet user-secrets init
    // dotnet user-secrets set OpenAIKey <your-openai-key>
    var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
    string key = config["OpenAIKey"];
    string modelName = config["ModelName"];
    
    // Create the OpenAI ImageClient
    ImageClient client = new(modelName, key);
    
    // Generate the image
    GeneratedImage generatedImage = await client.GenerateImageAsync("""
        A postal card with a happy hiker waving and a beautiful mountain in the background.
        There is a trail visible in the foreground.
        The postal card has text in red saying: 'You are invited for a hike!'
        """,
        new ImageGenerationOptions 
        {
            Size = GeneratedImageSize.W1024xH1024 
        });
    
    Console.WriteLine($"The generated image is ready at:\n{generatedImage.ImageUri}");
    

    前述のコード:

    • AI モデルに接続するために、プロジェクト ユーザー シークレットから重要な構成値を読み取ります。
    • AI モデルに接続するための OpenAI.Images.ImageClient を作成します。
    • 目的のイメージを説明するプロンプトをモデルに送信します。
    • 生成されたイメージの URL をコンソール出力に出力します。
  2. アプリを実行します。

    dotnet run
    

    コンソール出力のイメージ URL に移動して、生成されたイメージを表示します。 プロンプトのテキスト コンテンツをカスタマイズして、新しいイメージを作成したり、元のイメージを変更したりします。

リソースをクリーンアップする

不要になった場合は、Azure OpenAI リソースと GPT-4 モデルのデプロイを削除します。

  1. Azure Portalで、Azure OpenAI リソースに移動します。
  2. Azure OpenAI リソースを選択し、[削除] を選択します。

次のステップ