【.NET】创建一个ai聊天应用

文章目录

      • [🚀 使用 .NET 构建 AI 聊天应用](#🚀 使用 .NET 构建 AI 聊天应用)
        • [🛠️ 先决条件](#🛠️ 先决条件)
        • [📂 创建应用](#📂 创建应用)
        • [⚙️ 配置应用](#⚙️ 配置应用)
        • [💻 添加应用代码](#💻 添加应用代码)
        • [🧹 清理资源](#🧹 清理资源)

🚀 使用 .NET 构建 AI 聊天应用

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

🛠️ 先决条件

根据你的目标平台(OpenAI 或 Azure OpenAI),请确保满足以下先决条件:

通用要求:

针对 OpenAI:

针对 Azure OpenAI:


📂 创建应用

完成以下步骤,创建 .NET 控制台应用以连接到 AI 模型。

  1. 在计算机上的空目录中,使用 dotnet new 命令创建新的控制台应用:

    bash 复制代码
    dotnet new console -o ChatAppAI
  2. 将目录更改为应用文件夹:

    bash 复制代码
    cd ChatAppAI
  3. 安装所需的包:

    针对 Azure OpenAI:

    bash 复制代码
    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

    针对 OpenAI:

    bash 复制代码
    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 中打开应用(或所选编辑器):

    bash 复制代码
    code .

⚙️ 配置应用

根据你的选择,配置相应的服务凭据。

创建 AI 服务 (Azure OpenAI)

  1. 若要预配 Azure OpenAI 服务和模型,请完成 创建和部署 Azure OpenAI 服务资源 文章中的步骤。

  2. 在终端或命令提示符下,导航到项目目录的根目录。

  3. 运行以下命令为示例应用配置 Azure OpenAI 终结点和模型名称:

    bash 复制代码
    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>

配置应用 (OpenAI)

  1. 从终端或命令提示符导航到 .NET 项目的根目录。

  2. 运行以下命令,将 OpenAI API 密钥配置为示例应用的机密:

    bash 复制代码
    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. 连接并向 AI 模型进行身份验证

Program.cs 文件中,添加以下代码:

针对 Azure OpenAI:

csharp 复制代码
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 资源,则需要将 Azure AI Developer 角色分配给用于登录到 Visual Studio 或 Azure CLI 的帐户。

针对 OpenAI:

csharp 复制代码
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 模型提供初始角色上下文和有关徒步旅行建议的说明:

csharp 复制代码
// 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. 创建对话循环

该循环接受来自用户的输入提示,将提示发送到模型,并输出响应完成:

csharp 复制代码
// 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 命令运行应用:

bash 复制代码
dotnet run

应用从 AI 模型输出完成响应。发送其他后续提示,并询问其他问题以试验 AI 聊天功能。


🧹 清理资源

如果不再需要它们,请删除 Azure OpenAI 资源和 GPT模型部署。

  1. Azure 门户中,导航到 Azure OpenAI 资源。
  2. 选择 Azure OpenAI 资源,然后选择 删除
相关推荐
武汉唯众智创4 分钟前
边缘端部署 AI 心理分析:自研边缘主机跑通人脸 + 语音双模态推理,不用云端算力详解
人工智能·ai心理健康·校园心理健康·多模态推理·人脸情绪识别·语音情感分析·心理健康信息化平台
IT_陈寒9 分钟前
Python的线程池把我坑惨了,原来异步不是万能的
前端·人工智能·后端
水木流年追梦16 分钟前
大模型入门-大模型优化方法12-YaRN 长文本外推技术
人工智能·分布式·算法·正则表达式·prompt
Litluecat20 分钟前
2026年6月6日科技热点新闻
人工智能·科技·热点·每日
小旭952720 分钟前
Spring AI Alibaba 从入门到实战:一站式掌握企业级 AI 应用开发
java·人工智能·spring
tianxiaxue131 分钟前
企微如何使用AI生成推荐话术?
人工智能·企业微信
团象科技33 分钟前
梳理中小出海独立站落地阶段关于WordPress 海外主机的实操参考路径
人工智能·深度学习
朴马丁43 分钟前
构建日化数字创新平台:PLM如何融合AI、物联网数据,驱动智能研发与精准营销
人工智能·物联网·流程行业plm·日化行业
我不介意孤独43 分钟前
04-记忆系统为什么向量数据库不够用
数据库·人工智能·资源隔离·agent infra
小程故事多_801 小时前
从人工编写到自主迭代进化,SkillEvolver重构大模型智能体技能生成新范式
人工智能·重构