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;
        }
    }
}
相关推荐
会飞的小新2 分钟前
C 标准库之 <fenv.h> 详解与深度解析
c语言·开发语言·microsoft
暗暗别做白日梦1 小时前
Pulsar 消息同步机制
c#·linq
大不点wow1 小时前
Java序列化与反序列化:让对象走出JVM
java·开发语言·jvm
阿里嘎多学长1 小时前
2026-07-22 GitHub 热点项目精选
开发语言·程序员·github·代码托管
海盗12341 小时前
微软技术周报——2026-07-22
microsoft·c#·.net
噢,我明白了1 小时前
Java中日期和字符串的处理
java·开发语言·日期
爱刷碗的苏泓舒1 小时前
C 语言 if-else 与 switch-case 分支语句对比
c语言·开发语言
海盗12341 小时前
微软技术日报 ——2026-07-21
microsoft·c#·.net
-银雾鸢尾-1 小时前
C#中的泛型约束
开发语言·c#
WWJA王文举2 小时前
单片机参数如何掉电保存:Flash、EEPROM和配置存储完整设计
数据库·stm32·mongodb·c#