次の方法で共有


「.NET を使用して AI チャットアプリを構築」

このクイック スタートでは、OpenAI または Azure OpenAI モデルを使用して会話型の .NET コンソール チャット アプリを作成する方法について説明します。 アプリは Microsoft.Extensions.AI ライブラリを使用するため、特定の SDK ではなく AI 抽象化を使用してコードを記述できます。 AI 抽象化を使用すると、最小限のコード変更で基になる AI モデルを変更できます。

前提条件

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

前提条件

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

アプリを作成する

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

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

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

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

    dotnet add package Azure.Identity
    dotnet add package Azure.AI.OpenAI
    dotnet add package Microsoft.Extensions.AI.OpenAI --prerelease
    dotnet add package Microsoft.Extensions.Configuration
    dotnet add package Microsoft.Extensions.Configuration.UserSecrets
    
    dotnet add package OpenAI
    dotnet add package Microsoft.Extensions.AI.OpenAI --prerelease
    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>
    

アプリ コードを追加する

このアプリでは、 Microsoft.Extensions.AI パッケージを使用して、AI モデルへの要求を送受信します。 このアプリは、ハイキングコースに関する情報をユーザーに提供します。

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

    IConfigurationRoot config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
    string endpoint = config["AZURE_OPENAI_ENDPOINT"];
    string deployment = config["AZURE_OPENAI_GPT_NAME"];
    
    IChatClient chatClient =
        new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential())
        .GetChatClient(deployment)
        .AsIChatClient();
    

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

    var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
    string model = config["ModelName"];
    string key = config["OpenAIKey"];
    
    // Create the IChatClient
    IChatClient chatClient =
        new OpenAIClient(key).GetChatClient(model).AsIChatClient();
    
  2. AIモデルにハイキングのおすすめに関する初期の役割のコンテキストと指示を提供するためのシステムプロンプトを作成してください。

    // Start the conversation with context for the AI model
    List<ChatMessage> chatHistory =
        [
            new ChatMessage(ChatRole.System, """
                You are a friendly hiking enthusiast who helps people discover fun hikes in their area.
                You introduce yourself when first saying hello.
                When helping people out, you always ask them for this information
                to inform the hiking recommendation you provide:
    
                1. The location where they would like to hike
                2. What hiking intensity they are looking for
    
                You will then provide three suggestions for nearby hikes that vary in length
                after you get that information. You will also share an interesting fact about
                the local nature on the hikes when making a recommendation. At the end of your
                response, ask if there is anything else you can help with.
            """)
        ];
    
  3. ユーザーからの入力プロンプトを受け取り、そのプロンプトをモデルに送信し、応答の完了を出力する会話ループを作成します。

    // Loop to get user input and stream AI response
    while (true)
    {
        // Get user prompt and add to chat history
        Console.WriteLine("Your prompt:");
        string? userPrompt = Console.ReadLine();
        chatHistory.Add(new ChatMessage(ChatRole.User, userPrompt));
    
        // Stream the AI response and add to chat history
        Console.WriteLine("AI Response:");
        string response = "";
        await foreach (ChatResponseUpdate item in
            chatClient.GetStreamingResponseAsync(chatHistory))
        {
            Console.Write(item.Text);
            response += item.Text;
        }
        chatHistory.Add(new ChatMessage(ChatRole.Assistant, response));
        Console.WriteLine();
    }
    
  4. dotnet run コマンドを使用してアプリを実行します。

    dotnet run
    

    アプリはAIモデルからの完了応答を出力します。 追加のフォローアッププロンプトを送信し、他の質問をしてAIチャット機能を試してみてください。

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

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

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

次のステップ