C# 根据Ollama+DeepSeekR1开发本地AI辅助办公助手

在上一篇《访问DeepSeekR1本地部署API服务搭建自己的AI办公助手》中,我们通过通过Ollama提供的本地API接口用Python实现了一个简易的AI办公助手,但是需要运行Py脚本,还比较麻烦,下面我们用C#依据Ollama提供的API接口开发一个本地AI辅助办公助手.

代码如下:

需要引用Newtonsoft.Json.dll和Winform皮肤插件OwnUI.dll去掉也没什么影响

cs 复制代码
using System;
using System.Net.Http;
using System.Windows.Forms;
using OwnUI;
using Newtonsoft.Json.Linq;

namespace OllamaChat
{
    public partial class Form1 : UIForm
    {
        public Form1()
        {
            InitializeComponent();
        }
        
        private void Form1_Load(object sender, EventArgs e)
        {
            uitb_requesturl.Text = "http://127.0.0.1:11434/api/chat";
            uitb_question.Text = uitb_answers.Text = "";
        }
        
        private void uitb_question_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                string json = "{\"model\":\"deepseek-r1:1.5b\",\"messages\": [{\"role\":\"user\",\"content\":\"" + uitb_question.Text + "\"}],\"stream\":false}";
                string restext = post(uitb_requesturl.Text, json);
                JObject obj = JObject.Parse(restext);
                string message = obj["message"].ToString();
                if (string.IsNullOrEmpty(message) == false)
                {
                    obj = JObject.Parse(message);
                    string content = obj["content"].ToString();
                    uitb_answers.Text = content;
                }
            }
        }
        /// <summary>
        /// https提交
        /// </summary>
        /// <param name="url"></param>
        /// <param name="jsonParas"></param>
        /// <returns></returns>
        public static String post(String url, String jsonParas)
        {
            String responseBody = String.Empty;
            using (HttpClient client = new HttpClient())
            {
                HttpContent httpContent = new StringContent(jsonParas);
                httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                HttpResponseMessage response = client.PostAsync(url, httpContent).GetAwaiter().GetResult();
                response.EnsureSuccessStatusCode();
                responseBody = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
            }
            //Console.WriteLine(responseBody);
            return responseBody;
        }
    }
}
相关推荐
hez201021 小时前
在 .NET 上构建超大托管数组
c#·.net·.net core·gc·clr
雨落倾城夏未凉6 天前
第四章c#方法-参数数组和可选参数(16)
后端·c#
唐青枫7 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫8 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m6258 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户91721561902118 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠9 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫11 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech11 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf13 天前
C#摸鱼实录——IoC与DI案例详解
c#