当前位置: 首页 > news >正文

利用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毛钱作为鼓励呗,穷逼一个,就当筹个网费吧

http://www.jsqmd.com/news/211762/

相关文章:

  • 亲测好用9个一键生成论文工具,自考学生轻松搞定论文!
  • 基于A星算法的无人机三维路径规划算法研究附Matlab代码
  • 基于A星算法的无人机三维路径规划算法研究附Matlab代码
  • 实验数据处理的AI加速:架构师的分布式训练
  • Symbol不是摆设:前端老铁们怎么用它解决实际问题
  • 论文挂科崩溃救命!2026年知网AIGC检测高达62%,这三款论文去AI痕迹神器帮你降重降AI率,秒过查重不掉线!
  • 人工智能代理的10种常见故障模式及其修复方法
  • 华为openEuler 欧拉操作系统安装Docker方法和步骤
  • 技术学习:构建知识体系与提升实践能力
  • 告别重复造轮子!MCP 协议科普:给大模型装上“USB-C”万能接口
  • 2025年12月 GESP CCF编程能力等级认证Python三级真题
  • 基于ILP的最优PMU放置优化研究附Matlab代码
  • 强烈安利!继续教育必用TOP8 AI论文工具测评
  • 洁诚新能源:践行双碳战略的绿色行动派
  • 2025年12月 GESP CCF编程能力等级认证Python四级真题
  • Docker Compose UI:让容器管理告别命令行,小白也能轻松上手
  • 最近在折腾一个高性能C#服务端轮子,目标是搞个能同时扛住各种网络协议的瑞士军刀。咱这轮子就得自己撸底层,从Socket开始造轮子。先上个核心架构图镇楼
  • pkill -15 monkey命令及信号15解释
  • 大数据数据工程中的存储格式选择:Parquet vs ORC
  • 2025年12月 GESP CCF编程能力等级认证Python二级真题
  • conda虚拟环境备份与安装
  • 全网最全9个一键生成论文工具,专科生毕业论文轻松搞定!
  • Qt学习记录
  • java: 找不到符号,零基础入门到精通,收藏这篇就够了
  • 一文看懂Java内存模型(JMM)收藏这篇就够了
  • 【免费开源文本编辑器】轻量级文本编辑器——Notepad++ 下载安装教程
  • LeetCode 468 验证 IP 地址
  • DeepSeek对于DuckDB on LoongArch一文的总结
  • 状态管理:Flutter 为什么走上了和前端一样的“百家争鸣”?
  • 学长亲荐2026自考AI论文工具TOP10:选对工具轻松过关