使用 .NET 与本地 AI 模型聊天

本快速入门介绍如何使用 OpenAI 或 Azure OpenAI 模型创建聊天 .NET 控制台聊天应用。 应用使用 Microsoft.Extensions.AI 库,因此可以使用 AI 抽象而不是特定 SDK 编写代码。 借助 AI 抽象,你可以通过最少的代码更改来更改基础 AI 模型。

先决条件

运行本地 AI 模型

完成以下步骤,在设备上配置并运行本地 AI 模型。 有许多不同的 AI 模型可用于在本地运行,并可针对不同的任务(例如生成代码、分析图像、生成聊天或创建嵌入内容)对其进行训练。 在本快速入门中,你将使用常规用途 phi3:mini 模型,该模型是 Microsoft 创建的小型但功能强大的生成式 AI。

  1. 打开终端窗口并验证 Ollama 在你的设备上是否可用:

    ollama
    

    如果 Ollama 可用,则会显示可用命令的列表。

  2. 启动 Ollama:

    ollama serve
    

    如果 Ollama 正在运行,则会显示可用命令的列表。

  3. phi3:mini会从 Ollama 注册表拉取模型并等待其下载:

    ollama pull phi3:mini
    
  4. 下载完成后,运行模型:

    ollama run phi3:mini
    

    Ollama 会启动 phi3:mini 模型,并提示你与之交互。

创建 .NET 应用

完成以下步骤,创建连接到本地 phi3:mini AI 模型的 .NET 控制台应用。

  1. 在终端窗口中,导航到设备上的空目录,并使用 dotnet new 命令创建新应用:

    dotnet new console -o LocalAI
    
  2. OllamaSharp 包添加到应用:

    dotnet add package OllamaSharp
    
  3. 在所选编辑器中打开新应用,例如 Visual Studio Code。

    code .
    

连接到 AI 模型并与其聊天

语义内核 SDK 提供了许多服务和功能,用于连接到 AI 模型和管理交互。 在后续步骤中,你将创建一个简单的应用,用于连接到本地 AI 并存储对话历史记录,以提高聊天体验。

  1. 打开 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),而无需更改任何其他代码。
    • 创建一个 ChatHistory 对象,用于在用户和 AI 模型之间存储消息。
    • 从用户检索提示并将其存储在 ChatHistory 中。
    • 将聊天数据发送到 AI 模型以生成响应。

    注释

    默认情况下,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 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.
    
  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 (.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 的第二次更新响应要短得多。 由于可用的聊天历史记录,AI 能够评估以前的结果并提供较短的摘要。

后续步骤