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

C# 控制台接入DeepSeek

创建控制台应用,替换下边核心代码,或者全替换。记得将apikey 替换为你自己的apikey
 

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;
using System.Threading;
using System.Net.Http.Headers;

class Program
{
    private static readonly string apiKey = "apikey";
    private static readonly string apiUrl = "https://api.deepseek.com/v1/chat/completions";

    static async Task Main(string[] args)
    {
        while (true)
        {
            Console.WriteLine("请输入您的问题:");
            var question = Console.ReadLine();
            if (question.ToLower() == "exit")
            {
                break;
            }
            if (string.IsNullOrEmpty(question.Trim()))
            {
               continue; 
            }
            await SendToDeepSeek(question);
            Console.WriteLine("\n\n");
        }
    }

    static async Task SendToDeepSeek(string question)
    {
        var requestData = new
        {
            model = "deepseek-chat",
            messages = new[]
            {
                new { role = "user", content = question }
            },
            stream = true,  // 添加流式传输参数
            max_tokens = 8192
        };

        try
        {
            await CallDeepSeekAPIStreaming(requestData);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"\nError: {ex.Message}");
        }
    }

    static async Task CallDeepSeekAPIStreaming(object requestData)
    {
        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var jsonContent = JsonConvert.SerializeObject(requestData);
            var httpContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            using (var request = new HttpRequestMessage(HttpMethod.Post, apiUrl)
            {
                Content = httpContent
            })
            using (var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
            using (var stream = await response.Content.ReadAsStreamAsync())
            using (var reader = new StreamReader(stream))
            {
                while (!reader.EndOfStream)
                {
                    var line = await reader.ReadLineAsync();
                    if (string.IsNullOrWhiteSpace(line)) continue;

                    // 处理事件流格式
                    if (line.StartsWith("data: "))
                    {
                        var jsonData = line.Substring(6).Trim();
                        if (jsonData == "[DONE]") break;

                        var chunk = JsonConvert.DeserializeObject<StreamChatResponse>(jsonData);
                        var content = chunk?.choices?.FirstOrDefault()?.delta?.content;

                        if (!string.IsNullOrEmpty(content))
                        {
                            Console.Write(content);
                            // 若需要模拟逐字效果,可添加延迟
                            await Task.Delay(50);
                        }
                    }
                }
            }
        }
    }

    public class StreamChatResponse
    {
        public Choice[] choices { get; set; }
        public class Choice
        {
            public Delta delta { get; set; }
        }
        public class Delta
        {
            public string content { get; set; }
        }
    }
}


http://www.kler.cn/a/537149.html

相关文章:

  • 力扣.270. 最接近的二叉搜索树值(中序遍历思想)
  • H266/VVC 环路滤波中去块滤波 DF 技术
  • k8sollama部署deepseek-R1模型,内网无坑
  • 解决使用python提取word文档中所有的图片时图片丢失的问题
  • Java 面试真题解析与技巧分享
  • IDEA使用Auto-dev+DeepSeek 10分钟快速集成,让java开发起飞
  • 使用ES5和ES6求函数参数的和、解析URL Params为对象
  • STM32 软件I2C读写MPU6050
  • Spring相关知识点
  • Centos挂载镜像制作本地yum源,并补装图形界面
  • 要替换PPT左上角的logo,可以通过几种方法实现‌。
  • 知识库管理系统与ChatGPT:如何用生成式AI打造智能知识助手?
  • TEE笔记
  • 基于SpringBoot和Leaflet的全国省会城市风景区分布分析实践
  • C++ Primer 成员访问运算符
  • 游戏引擎学习第91天
  • ubuntu下nfs使用笔记
  • vscode预览插件
  • 初识C语言、C语言的学习方向总述与入门
  • 华为OD最新机试真题-补种未活胡树-C++-OD统一考试(E卷)
  • 远程调用总结
  • 哪些网站和工具可以用于站点测速和性能分析
  • 深入理解 Java 泛型(Generics)
  • 零基础学习书生.浦语大模型--基础岛
  • Explain 是 SQL 查询优化中非常重要的工具,它用于分析 SQL 查询的执行计划
  • ubuntu20使用tigervnc远程桌面配置记录