このクイック スタートでは、OpenAI または Azure OpenAI モデルを使用して会話型の .NET コンソール チャット アプリを作成する方法について説明します。 アプリは Microsoft.Extensions.AI ライブラリを使用するため、特定の SDK ではなく AI 抽象化を使用してコードを記述できます。 AI 抽象化を使用すると、最小限のコード変更で基になる AI モデルを変更できます。
[前提条件]
- .NET 8.0 以降をインストールする
- デバイスのローカル環境に Ollama をインストールします
- Visual Studio Code (省略可能)
ローカル AI モデルを実行する
デバイスでローカル AI モデルを構成して実行するには、次の手順を実行します。 多くの異なる AI モデルをローカル環境で実行でき、コードの生成、画像の分析、生成チャット、埋め込みの作成など、さまざまなタスク用にトレーニングされます。 このクイックスタートでは、Microsoft によって作成された小さいながらも高性能の生成 AI である汎用 phi3:mini
モデルを使います。
ターミナル ウィンドウを開き、デバイスで Ollama を使用できることを確認します。
ollama
Ollama が使用可能な場合は、使用可能なコマンドの一覧が表示されます。
Ollama を起動します:
ollama serve
Ollama が実行されている場合、使用できるコマンドの一覧が表示されます。
Ollama レジストリから
phi3:mini
モデルをプルし、ダウンロードされるまで待ちます。ollama pull phi3:mini
ダウンロードが完了した後、モデルを実行します。
ollama run phi3:mini
Ollama により
phi3:mini
モデルが開始され、それとの対話を求めるプロンプトが表示されます。
.NET アプリを作成する
ローカルの phi3:mini
AI モデルに接続する .NET コンソール アプリを作成するには、次の手順を実行します。
ターミナル ウィンドウで、デバイス上の空のディレクトリに移動し、
dotnet new
コマンドを使用して新しいアプリを作成します。dotnet new console -o LocalAI
OllamaSharp パッケージをアプリに追加します。
dotnet add package OllamaSharp
Visual Studio Code など、任意のエディターで新しいアプリを開きます。
code .
AI モデルに接続してチャットする
Semantic Kernel SDK に含まれる多くのサービスと機能を使って、AI モデルに接続し、対話を管理できます。 以降の手順で作成する簡単なアプリは、ローカル AI に接続し、会話履歴を格納してチャット エクスペリエンスを向上させます。
Program.cs ファイルを開き、ファイルの内容を次のコードに置き換えます。
using Microsoft.Extensions.AI; using OllamaSharp; IChatClient chatClient = new OllamaApiClient(new Uri("http://localhost:11434/"), "phi3:mini"); // Start the conversation with context for the AI model List<ChatMessage> chatHistory = new(); while (true) { // Get user prompt and add to chat history Console.WriteLine("Your prompt:"); var userPrompt = Console.ReadLine(); chatHistory.Add(new ChatMessage(ChatRole.User, userPrompt)); // Stream the AI response and add to chat history Console.WriteLine("AI Response:"); var 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(); }
上記のコードでは、次の処理が行われます。
OllamaChatClient
インターフェースを実装するものとして、IChatClient
を作成します。- このインターフェイスは、AI モデルとのチャットに使用できる疎結合の抽象化を提供します。
- 後で、基になるチャット クライアントの実装を、他のコードを変更することなく、Azure OpenAI などの別のモデルに変更できます。
- ユーザーと AI モデルの間のメッセージを格納するための
ChatHistory
オブジェクトを作成します。 - ユーザーからプロンプトを取得し、それを
ChatHistory
に格納します。 - チャット データを AI モデルに送信して応答を生成します。
注
Ollama は既定ではポート 11434 で実行されるため、AI モデルのエンドポイントが
http://localhost:11434
に設定されています。次のように、アプリを実行し、コンソールにプロンプトを入力して 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 a 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 for desktop apps and ASP.NET Core for modern web applications), mobile applications (.NET MAUI), IoT solutions, AI/ML projects, and much more with a vast array of prebuilt 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.
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 (.NET MAUI), 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 は以前の結果を評価して、より短い要約を提供できました。
次のステップ
.NET