次の方法で共有


.NET と Semantic Kernel を使用してローカル AI モデルとチャットする

ローカル AI モデルは、AI ソリューションを構築するための強力で柔軟なオプションを提供します。 このクイックスタートでは、.NET と Semantic Kernel SDK を使ってローカル AI モデルを設定して接続する方法について説明します。 この例では、Ollama を使ってローカル AI モデルを実行します。

前提条件

ローカル AI モデルを実行する

デバイスで次の手順を行い、ローカル AI モデルを構成して実行します。 多くの異なる AI モデルをローカル環境で実行でき、コードの生成、画像の分析、生成チャット、埋め込みの作成など、さまざまなタスク用にトレーニングされます。 このクイックスタートでは、Microsoft によって作成された小さいながらも高性能の生成 AI である汎用 phi3:mini モデルを使います。

  1. ターミナル ウィンドウを開き、デバイスで Ollama を使用できることを確認します。

    ollama
    

    Ollama が実行されている場合、使用できるコマンドの一覧が表示されます。

  2. Ollama レジストリから phi3:mini モデルをプルし、ダウンロードされるまで待ちます。

    ollama pull phi3:mini
    
  3. ダウンロードが完了した後、モデルを実行します。

    ollama run phi3:mini
    

    Ollama により phi3:mini モデルが開始され、それとの対話を求めるプロンプトが表示されます。

.NET アプリを作成する

次の手順のようにして、ローカル phi3:mini AI モデルに接続する .NET コンソール アプリを作成します。

  1. ターミナル ウィンドウで、デバイス上の空のディレクトリに移動し、dotnet new コマンドを使って新しいアプリを作成します。

    dotnet new console
    
  2. Semantic Kernel SDK パッケージをアプリに追加します。

    dotnet add package Microsoft.SemanticKernel
    
  3. Visual Studio Code など、任意のエディターで新しいアプリを開きます。

    code .
    

AI モデルに接続してチャットする

Semantic Kernel SDK に含まれる多くのサービスと機能を使って、AI モデルに接続し、対話を管理できます。 以降の手順で作成する簡単なアプリは、ローカル AI に接続し、会話履歴を格納してチャット エクスペリエンスを向上させます。

  1. Program.cs ファイルを開き、ファイルの内容を次のコードに置き換えます。

    using Microsoft.SemanticKernel;
    using Microsoft.SemanticKernel.ChatCompletion;
    
    // Create a kernel with OpenAI chat completion
    #pragma warning disable SKEXP0010
    Kernel kernel = Kernel.CreateBuilder()
                        .AddOpenAIChatCompletion(
                            modelId: "phi3:mini",
                            endpoint: new Uri("http://localhost:11434"),
                            apiKey: "")
                        .Build();
    
    var aiChatService = kernel.GetRequiredService<IChatCompletionService>();
    var chatHistory = new ChatHistory();
    
    while (true)
    {
        // Get user prompt and add to chat history
        Console.WriteLine("Your prompt:");
        var userPrompt = Console.ReadLine();
        chatHistory.Add(new ChatMessageContent(AuthorRole.User, userPrompt));
    
        // Stream the AI response and add to chat history
        Console.WriteLine("AI Response:");
        var response = "";
        await foreach(var item in 
            aiChatService.GetStreamingChatMessageContentsAsync(chatHistory))
        {
            Console.Write(item.Content);
            response += item.Content;
        }
        chatHistory.Add(new ChatMessageContent(AuthorRole.Assistant, response));
        Console.WriteLine();
    }
    

    Note

    #pragma warning disable SKEXP0010 の行が含まれているのは、Semantic Kernel SDK の一部の機能が試験状態であるためです。

    上記のコードでは次のタスクが実行されます。

    • Kernel オブジェクトを作成し、それを使ってチャット完了サービスを取得します。
    • ユーザーと AI モデルの間のメッセージを格納するための ChatHistory オブジェクトを作成します。
    • ユーザーからプロンプトを取得し、それを ChatHistory に格納します。
    • チャット データを AI モデルに送信して応答を生成します。

    Note

    Ollama は既定ではポート 11434 で実行されるため、AI モデルのエンドポイントが http://localhost:11434 に設定されています。

  2. 次のように、アプリを実行し、コンソールにプロンプトを入力して AI からの応答を受け取ります。

    Your prompt:
    Tell me three facts about .NET.
    
    AI response:
    1. **Cross-Platform Development:** One of the significant strengths of .NET, 
    particularly its newer iterations (.NET Core and .NET 5+), is cross-platform support.
    It allows developers to build applications that run on Windows, Linux, macOS,
    and various other operating systems seamlessly, enhancing flexibility and
    reducing barriers for a wider range of users.
    
    2. **Rich Ecosystem and Library Support:** .NET has an incredibly rich ecosystem,
    comprising an extensive collection of libraries (such as those provided by the 
    official NuGet Package Manager), tools, and services. This allows developers 
    to work on web applications (.NET Framework for desktop apps and ASP.NET Core 
    for modern web applications), mobile applications (.NET MAUI or Xamarin.Forms),
    IoT solutions, AI/ML projects, and much more with a vast array of pre-built
    components available at their disposal.
    
    3. **Type Safety:** .NET operates under the Common Language Infrastructure (CLI) 
    model and employs managed code for executing applications. This approach inherently
    offers strong type safety checks which help in preventing many runtime errors that
    are common in languages like C/C++. It also enables features such as garbage collection,
    thus relieving developers from manual memory management. These characteristics enhance
    the reliability of .NET-developed software and improve productivity by catching
    issues early during development.
    
  3. AI からの応答は正確ですが、冗長でもあります。 AI は、保存されたチャット履歴を使って、その応答を修正できます。 提供されたリストを短くするよう AI に指示します。

    Your prompt:
    Shorten the length of each item in the previous response.
    
    AI Response:
     **Cross-platform Capabilities:** .NET allows building for various operating systems
    through platforms like .NET Core, promoting accessibility (Windows, Linux, macOS).
    
    **Extensive Ecosystem:** Offers a vast library selection via NuGet and tools for web
    (.NET Framework), mobile development (Maui/Xamarin.Forms), IoT, AI, providing rich
    capabilities to developers.
    
    **Type Safety & Reliability:** .NET's CLI model enforces strong typing and automatic
    garbage collection, mitigating runtime errors, thus enhancing application stability.
    

    AI からの更新された応答は、2 回目の方がはるかに短くなります。 チャット履歴を利用できるため、AI は以前の結果を評価して、より短い要約を提供できました。

次のステップ