news 2026/5/1 8:33:07

利用C#对接BotSharp本地大模型AI Agent示例(2)

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
利用C#对接BotSharp本地大模型AI Agent示例(2)

上一篇博文已经介绍了怎么搭建BotSharp本地大模型环境

https://blog.csdn.net/zxy13826134783/article/details/156653773?spm=1001.2014.3001.5501

本文运行环境:

win11

visual studio 2022

本文利用C#对接BotSharp本地大模型的Api,废话不多说,先上代码及运行结果

1 在Vistual Studio中新建名为POSTDemo1的控制台项目,选择.net framework 4.7

2 利用nuget安装Newtonsoft.Json及System.Text.Json,直接安装最新版就行

3 编辑代码如下:

using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Text.Json; using System.Threading.Tasks; namespace POSTDemo1 { internal class Program { static void Main(string[] args) { var base_url = $"http://localhost:5500"; string userName = "admin@gmail.com"; string password = "123456"; string token = GetToken(base_url,userName, password); if (string.IsNullOrEmpty(token)) { Console.WriteLine("获取token失败"); return; } //解析token JsonDocument doc = JsonDocument.Parse(token); string accessToken = doc.RootElement .GetProperty("access_token") .GetString(); if(string.IsNullOrEmpty(accessToken)) { Console.WriteLine("获取access_token失败"); return; } Console.WriteLine($"获取到的token{accessToken}"); //输入的问题 string question = "hello"; //发送对话 PostConverSation(base_url, accessToken, question); Console.WriteLine("运行完毕"); Console.ReadLine(); } private static void SetClientHeader(HttpClient client,string authorization) { client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authorization); } private static void PostConverSation(string base_url,string token,string question) { var client = new HttpClient(); string agentId = "01e2fc5c-2c89-4ec7-8470-7688608b496c"; //会话Id string conversationId = "abc"; string converSationUrl = $"{base_url}/conversation/{agentId}/{conversationId}"; SetClientHeader(client, token); var data = new { text = question, provider = "llama-sharp", model = "llama-2-7b-chat.Q8_0.gguf" }; Console.WriteLine($"输入的问题:{question}"); string ret=PostJsonData(client, converSationUrl, data, 3); Console.WriteLine($"机器人回复:{ret}"); } private static string PostJsonData(HttpClient client,string url,object data,int timeOut) { string jsonContent = ""; if (data != null) { jsonContent= JsonConvert.SerializeObject(data); } var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); string result = ""; try { client.Timeout = TimeSpan.FromMinutes(timeOut); // 设置超时时间 var response = client.PostAsync(url, content).Result; if (response.IsSuccessStatusCode) { var responseJson = response.Content.ReadAsStringAsync().Result; result= responseJson; } else { Console.WriteLine($"Error: {response.StatusCode}"); } } catch (HttpRequestException e) { Console.WriteLine($"Network error: {e.Message}"); } return result; } private static string GetToken(string base_url,string userName,string password) { string credentials=Convert.ToBase64String(Encoding.UTF8.GetBytes($"{userName}:{password}")); string authorization = $"Basic {credentials}"; var client = new HttpClient(); string tokenUrl = $"{base_url}/token"; SetClientHeader(client, authorization); return PostJsonData(client, tokenUrl, null, 1); } } }

先启动BotSharp后台服务,再运行该代码,运行结果如下:

机器人回复的文本:

{ "conversation_id": "abc", "sender": { "id": "", "user_name": "", "first_name": "", "last_name": null, "email": null, "phone": null, "type": "client", "role": "user", "full_name": "", "source": null, "external_id": null, "avatar": "/user/avatar", "permissions": [ ], "create_date": "0001-01-01T00:00:00", "update_date": "0001-01-01T00:00:00", "regionCode": "CN" }, "function": null, "rich_content": { "recipient": { "id": "abc" }, "messaging_type": "RESPONSE", "message": { "rich_type": "text", "text": "\uD83D\uDE0A Hello there! *chuckles* I'm here to help you with any questions or tasks you may have. Is there something specific you'd like to chat about or ask?" }, "fill_postback": false, "editor": "text" }, "has_message_files": false, "is_streaming": false, "created_at": "2026-01-07T05:09:14.5500535Z", "message_id": "59b97608-bcd7-4df7-b659-69304524f7b2", "text": "\uD83D\uDE0A Hello there! *chuckles* I'm here to help you with any questions or tasks you may have. Is there something specific you'd like to chat about or ask?", "data": null, "template": null, "states": { "prompt_total": "0", "temperature": "0", "model": "llama-2-7b-chat.Q8_0.gguf", "sampling_factor": "0", "use_stream_message": "false", "provider": "llama-sharp", "llm_total_cost": "0", "channel": "openapi", "completion_total": "0" }, "log_id": null }

同时也可以看到BotSharp的控制台日志有输出回复:

不知道是不是电脑配置问题,输入问题后,要很久才获取到回复,有时候3分钟都没回复就报错了

先要获取到token,token信息从前端BotSharp-UI中的代码中获取到启发

模型的代理agentId是固定的

会话conversationId是唯一的,自己定义,我这里为了偷懒,正常来说还得再调用一个接口(在BotSharp-UI前端界面新建会话时会调用),相当于设置会话Id,直接运行上述代码也会创建会话,但第一次可能返回的结果不是需要的结果,运行第二次就正常了

代理agentId及conversationId可以通过这里直接获取到:

点击上台右边chat小图标,直接进入会话,如下图:

看上图中的浏览器地址栏这里,已经标注AgentId及conversationId

好了,本文到此结束,如果本文对你有帮助,资助2毛钱作为鼓励呗,穷逼一个,就当筹个网费吧

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/18 11:28:06

基于A星算法的无人机三维路径规划算法研究附Matlab代码

✅作者简介:热爱科研的Matlab仿真开发者,擅长数据处理、建模仿真、程序设计、完整代码获取、论文复现及科研仿真。🍎 往期回顾关注个人主页:Matlab科研工作室🍊个人信条:格物致知,完整Matlab代码及仿真咨询…

作者头像 李华
网站建设 2026/5/1 0:59:50

Qt学习记录

1.打印2.LABEL3信号槽(Signal & Slot)(信号回调函数)4.自定义信号槽:5.不用UI6.对象树7.添加资源:8.样式表QSS

作者头像 李华
网站建设 2026/5/1 7:19:01

大数据领域Doris与MongoDB的集成方案

大数据领域Doris与MongoDB的集成方案:从业务痛点到实时分析的完美闭环 1. 引入:当“灵活存储”遇到“实时分析”的两难 凌晨2点,电商运营小李盯着电脑屏幕皱起眉头——他要统计“618大促期间,华南地区18-25岁用户的商品浏览→加购…

作者头像 李华
网站建设 2026/4/26 3:04:09

Claude Code 国内使用2026年最新完整教程分享

适用 Windows / macOS / Linux,并包含 国内网络环境可用方案与常见问题排查。Claude Code 是 Anthropic 官方的终端 AI 编程助手,可用于:写代码、解释代码、重构、生成脚本、审查 PR、运行测试、维护项目记忆(CLAUDE.md&#xff0…

作者头像 李华
网站建设 2026/5/1 7:16:51

Mosaic:面向超长序列的多GPU注意力分片方案

Transformer的"二次方注意力瓶颈"的问题是老生常谈了。这个瓶颈到底卡在哪实际工程里怎么绕过去?本文从一个具体问题出发,介绍Mosaic这套多轴注意力分片方案的设计思路。 注意力的内存困境 注意力机制的计算公式: Attention(Q, …

作者头像 李华
网站建设 2026/5/1 6:08:40

微信小程序 PHP_uniapp的农产品质量追溯系统_gkm0juhi

微信小程序 PHPUniapp 农产品质量追溯系统摘要 该系统基于微信小程序开发,采用PHP后端与Uniapp前端框架结合,实现农产品从生产到销售的全流程质量追溯。系统通过区块链技术确保数据不可篡改,提升消费者对农产品安全的信任度。 核心功能模块 生…

作者头像 李华