利用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 编辑代码如下:

cs 复制代码
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后台服务,再运行该代码,运行结果如下:

机器人回复的文本:

cs 复制代码
{
    "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毛钱作为鼓励呗,穷逼一个,就当筹个网费吧

相关推荐
富唯智能1 天前
重新定义“自动化搬运项目”:15分钟部署的复合机器人如何革新柔性生产
人工智能·机器人·自动化
闲人编程1 天前
商品管理与库存系统
服务器·网络·数据库·python·api·数据模型·codecapsule
初次攀爬者1 天前
RAG知识库核心优化|基于语义的智能文本切片方案(对比字符串长度分割)
人工智能·后端
宋情写1 天前
JavaAI05-Chain、MCP
java·人工智能
whaosoft-1431 天前
51c~目标检测~合集3
人工智能
掘金一周1 天前
高德地图与Three.js结合实现3D大屏可视化 | 掘金一周 1.8
前端·人工智能·后端
北京耐用通信1 天前
耐达讯自动化CAN转PROFIBUS网关让软启动器如何让包装线告别“信号迷宫”
人工智能·物联网·网络协议·自动化·信息与通信
ZhuNian的学习乐园1 天前
LLM知识检索增强:RAG_系统化解析与工程实践
人工智能·算法
paopao_wu1 天前
LangChainV1.0[05]-记忆管理
人工智能·python·langchain·ai编程