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;
        }
    }
}
相关推荐
晨星shine3 天前
GC、Dispose、Unmanaged Resource 和 Managed Resource
后端·c#
用户298698530144 天前
.NET 文档自动化:Spire.Doc 设置奇偶页页眉/页脚的最佳实践
后端·c#·.net
用户3667462526744 天前
接口文档汇总 - 2.设备状态管理
c#
用户3667462526744 天前
接口文档汇总 - 3.PLC通信管理
c#
Ray Liang5 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
Scout-leaf8 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户298698530148 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
mudtools9 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的9 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21889 天前
.NET 本地Db数据库-技术方案选型
windows·c#