C#创建AI项目

文章目录

申请模型

阿里平台申请模型

先登录

创建apikey

这是deepseek所有模型

创建.net8.0的WPF项目

nuget包

Microsoft.SemanticKernel 1.44.0

编写AI类

代码中apikey需要用你自己的

csharp 复制代码
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfApp1
{
    /// <summary>
    /// ai 类
    /// </summary>
    public class AI
    {
        public AI()
        {
            IKernelBuilder kernelBuilder = Kernel.CreateBuilder();
#pragma warning disable SKEXP0010
            kernelBuilder.AddOpenAIChatCompletion("deepseek-v3", new Uri("https://dashscope.aliyuncs.com/compatible-mode/v1"), "apikey");//阿里平台
            Kernel = kernelBuilder.Build();
            ChatHistory = new ChatHistory();
            ChatHistory.AddSystemMessage("你是一个乐于解答各种问题的助手,你的任务是为用户提供专业、准确、有见地的建议。");
        }
        public Kernel Kernel { get; set; }

        /// <summary>
        /// 聊天记录
        /// </summary>
        public ChatHistory ChatHistory { get; set; }

        /// <summary>
        /// 向AI提问
        /// </summary>
        /// <param name="questions">问题</param>
        /// <param name="action">字符流回调函数(委托中string代表的是AI回答的字符)</param>
        /// <returns></returns>
        public async Task<string> AskAIQuestions(string questions, Action<string> action)
        {
            ChatHistory.AddUserMessage(questions);
            return await AskAIQuestions(ChatHistory, action);
        }
        /// <summary>
        /// 向AI提问
        /// </summary>
        /// <param name="chatHistory">聊天记录</param>
        /// <param name="action">字符流回调函数</param>
        /// <returns></returns>
        public async Task<string> AskAIQuestions(ChatHistory chatHistory, Action<string> action)
        {
            //task.Result可以拿值
            var chatService = Kernel.GetRequiredService<IChatCompletionService>();
            string msg = "";
            await foreach (StreamingChatMessageContent chatUpdate in chatService.GetStreamingChatMessageContentsAsync(chatHistory))
            {
                if (chatUpdate.Content is { Length: > 0 })
                {
                    msg += chatUpdate.Content;
                    action(chatUpdate.Content);
                    Thread.Sleep(10);
                }
            }
            return msg;
        }
    }
}

编写一个简单的交互界面

MainWindow.xaml

xml 复制代码
<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition />
        </Grid.RowDefinitions>
        <TextBlock Height="400" x:Name="textBlock1" Text="{Binding Path=Text, Mode=OneWay}" />
        <Grid Grid.Row="1">
            <Grid.ColumnDefinitions>
                <ColumnDefinition />
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>
            <TextBox x:Name="textBox1" Text="{Binding Path=Text, Mode=TwoWay}" />
            <Button Grid.Column="1" x:Name="button1" Content="发送" Click="button1_Click" />
        </Grid>
    </Grid>
</Window>

MainWindow.xaml.cs

csharp 复制代码
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            string text = textBox1.Text;
            textBox1.Text = "";
            textBlock1.Text = "";
            AI aI = new AI();
            aI.AskAIQuestions(text, (string str) =>
            {
                textBlock1.Text += str;
            });
        }
    }
}
相关推荐
冷雨夜中漫步6 小时前
Python快速入门(6)——for/if/while语句
开发语言·经验分享·笔记·python
33三 三like6 小时前
《基于知识图谱和智能推荐的养老志愿服务系统》开发日志
人工智能·知识图谱
芝士爱知识a6 小时前
【工具推荐】2026公考App横向评测:粉笔、华图与智蛙面试App功能对比
人工智能·软件推荐·ai教育·结构化面试·公考app·智蛙面试app·公考上岸
腾讯云开发者7 小时前
港科大熊辉|AI时代的职场新坐标——为什么你应该去“数据稀疏“的地方?
人工智能
工程师老罗7 小时前
YoloV1数据集格式转换,VOC XML→YOLOv1张量
xml·人工智能·yolo
暖馒7 小时前
Modbus应用层协议的深度剖析
网络·网络协议·c#·wpf·智能硬件
m0_736919108 小时前
C++代码风格检查工具
开发语言·c++·算法
Coder_Boy_8 小时前
技术让开发更轻松的底层矛盾
java·大数据·数据库·人工智能·深度学习
2501_944934738 小时前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python