C#与AI的交互(以DeepSeek为例)

C#与ai的交互

与AI的交互使用的Http请求的方式,通过发送请求,服务器响应ai生成的文本

下面是完整的代码,我这里使用的是Ollama本地部署的deepseek,在联网调用api时,则url会有不同

csharp 复制代码
public class OllamaRequester
{
    [Serializable]
    public class RequestData
    {
        public string model;	//模型名称
        public string prompt;	//对话文本
        public int[] context;	//上下文
        public bool stream;	//是否使用流式传输
    }

    [Serializable]
    public class ResponseData
    {
        public string model;
        public string created_at;
        public string response;	//相应内容
        public bool done;	//生成是否结束
        public string done_reason;	//结束的状态
        public int[] context;	//上下文
        public long total_duration;
        public long load_duration;
    }

    private static OllamaRequester instance;
    public static OllamaRequester Instance
    {
        get
        {
            if(instance == null)
            {
                instance = new OllamaRequester();
                instance.Init();
            }
            return instance;
        }
    }


    private int[] context;
    private HttpClient client;

    private void Init()
    {
        client = new HttpClient();
    }

    public async Task SendReq(string str, Action<ResponseData> onResOnce)
    {
    	//注意!这里是本地Ollama的地址,如果你是联网调用ai接口的的话,需要改成官网提供的url
        string url = "http://localhost:11434/api/generate"; //ollama端口默认11434

		//如果使用联网调用ai接口,则请求的参数会有不同,我这使用的是本地部署的请求参数
        RequestData data = new RequestData()
        {
            model = "deepseek-r1:7b",
            prompt = str,
            context = context,
            stream = true, //建议用流式传输,不然响应比较慢
        };
        string json = JsonUtility.ToJson(data);
        HttpContent content = new StringContent(json);
        content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
        Debug.Log("发送请求..");
        try
        {
            var request = new HttpRequestMessage(HttpMethod.Post, url);
            request.Content = content;
            
            //这个HttpCompletionOption.ResponseHeadersRead至关重要,流式传输必须使用这个
            HttpResponseMessage msg = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
            try
            {
                //不是200则直接报错
                if (msg.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    Debug.LogError($"错误!statusCode=={msg.StatusCode}, 错误消息=={msg.Content}");
                    return;
                }
                Stream stream = await msg.Content.ReadAsStreamAsync();

                StreamReader reader = new StreamReader(stream);
                while (true)
                {
                    string resStr = await reader.ReadLineAsync();
                    Debug.Log("str==" + resStr);
                    ResponseData res = JsonUtility.FromJson<ResponseData>(resStr);
                    onResOnce?.Invoke(res);
                    if (res.done)
                    {
                        break;
                    }
                }
                reader.Dispose();
                stream.Dispose();
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
        }
        catch(Exception e)
        {
            Debug.LogError(e);
        }
    }
}

注意代码中SendAynsc时,使用了HttpCompletionOption.ResponseHeadersRead ,这个枚举表示的是读取响应头部信息,并且允许你从响应流中逐步读取信息。

默认情况下,Http会等待整个响应体全部下载完,才会返回响应,这样在文本很长时响应会非常慢!所以通常建议开启流式传输

下面是ai响应的数据格式示例

lua 复制代码
--api返回的数据格式是json(因为csdn没有json格式的代码段,所以我用了lua表示)
{
    "model": "deepseek-r1:7b",	--模型
    "created_at": "2025-02-24T02:03:41.8641806Z",
    "response": "",	--响应内容,我这里因为已经结束生成了,所以resposne是空
    "done": true,	--done==true,表示结束生成
    "done_reason": "stop",	--done_reason==stop,表示正常结束,会有其他非正常结束的情况
    "context": [	--上下文,在下次发送请求的时候,需要发送context,可以让ai保持连续对话
        151644,
        108386,
        151645,
        151648,
        271,
        151649,
        271,
        108386,
        6313,
        112169,
        104639,
        56568,
        3837,
        104139,
        109944,
        106128,
        9370,
        101037,
        11319,
        102215,
        86119,
        5373,
        101898,
        99998,
        100836,
        100281,
        3837,
        35946,
        102070,
        108896,
        101036,
        6313,
        144236
    ],
    "total_duration": 4234560000,
    "load_duration": 18329400,
    "prompt_eval_count": 4,
    "prompt_eval_duration": 274000000,
    "eval_count": 31,
    "eval_duration": 3941000000
}
相关推荐
寻道码路4 分钟前
深度剖析 Video-RAG:厦门大学和罗切斯特大学联合推出的一种用于长视频理解的检索增强生成技术
人工智能·语言模型·开源·aigc·音视频·ai编程
一只蜗牛儿5 分钟前
C# 版 OpenCV:OpenCVSharp 最详细最全面教程(万字详细总结)
开发语言·opencv·c#
哥不是小萝莉10 分钟前
使用 DeepSeek R1 和 Ollama 开发 RAG 系统
ai·deepseek
cly021624 分钟前
12个大语言模型平台对比测试-搜索视角
人工智能·语言模型·自然语言处理
学海无涯,行者无疆43 分钟前
使用Jenkins实现Windows服务器下C#应用程序发布
windows·c#·jenkins·.net·cicd·自动发布·一键发布
tnnnnt3 小时前
今天锐评一下C#
开发语言·c#
gange5743 小时前
AI将会取代生活的方方面面吗?
人工智能·ai·ai作画·生活·ai编程·ai写作·百度云
春末的南方城市4 小时前
CineMaster: 用于电影文本到视频生成的 3D 感知且可控的框架。
人工智能·数码相机·计算机视觉·语言模型·aigc·图像生成
FIT2CLOUD飞致云5 小时前
MaxKB上架至阿里云轻量应用服务器镜像市场
ai·开源·大模型·知识库·maxkb·问答