springboot接入deepseek深度求索 java

以下是在springboot中接入ai deepseek的过程。官网并没有java的示例。其实java的都可以用。

1. 创建 API key 网址:deepseek API keys

点击创建API key,把创建的key值复制下来,以后就不能再查看了,只能重新创建。

2. 封装询问deepseek的工具方法askDeepSeek()

添加key值和询问路径。API_KEY为你创建的key值。

    private static final String API_URL = "https://api.deepseek.com/chat/completions";
    private static final String API_KEY = "11111111"; // 替换为你的 API Key

工具方法askDeepSeek():

传入的参数question就是要询问的问题。

public String askDeepSeek(String question) throws IOException {
        CloseableHttpClient client = HttpClients.createDefault();

        // 创建 HTTP POST 请求
        HttpPost request = new HttpPost(API_URL);
        request.setHeader("Content-Type", "application/json");
        request.setHeader("Authorization", "Bearer " + API_KEY);

        // 动态构建请求体
        String requestBody = String.format(
                "{\"model\": \"deepseek-chat\", \"messages\": [{\"role\": \"user\", \"content\": \"%s\"}], \"stream\": false}",
                question
        );
        request.setEntity(new StringEntity(requestBody));

        // 发送请求并获取响应
        try (CloseableHttpResponse response = client.execute(request)) {
            // 返回响应内容
            return EntityUtils.toString(response.getEntity());
        }
    }

3. 调用该询问ai的方法

String  question1= "今天是星期几。 " ;
String answer = askDeepSeek(question);
System.out.println("answer = " + answer);

4. 成功返回示例

content里的就是返回的回答。

answer = {"id":"88dbce49-2841-448d-a74f-a2d3180c5672","object":"chat.completion","created":1734525002,"model":"deepseek-chat","choices":[{"index":0,"message":{"role":"assistant","content":"当然,我很高兴!谢谢你的关心。😊"},"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":12,"completion_tokens":11,"total_tokens":23,"prompt_cache_hit_tokens":0,"prompt_cache_miss_tokens":12},"system_fingerprint":"fp_1bcb2de9ac"}

不过我接入之后,他只能回答一些很简单的问题,有没有大佬会用啊~

相关推荐
Kali_07几秒前
StarSpider 星蛛 爬虫 Java框架 可以实现 lazy爬取 实现 HTML 文件的编译,子标签缓存等操作
java·爬虫·html
青云交5 分钟前
Java 大视界 -- 深度洞察 Java 大数据安全多方计算的前沿趋势与应用革新(52)
java·大数据·密码学·安全多方计算·分布式计算·医疗数据·技术融合
雨 子40 分钟前
Idea ⽆ Maven 选项
java·maven·intellij-idea
lihan_freak1 小时前
java中的抽象类和接口
java·开发语言·接口·抽象类
P7进阶路1 小时前
【Rabbitmq篇】高级特性----TTL,死信队列,延迟队列
java·rabbitmq·java-rabbitmq
sjsjsbbsbsn1 小时前
Java Web 开发中的分页与参数校验
java·spring boot·spring·状态模式·hibernate
张声录11 小时前
DeepSeek本地化部署【window下安装】【linux下安装】
linux·运维·服务器
lihan_freak1 小时前
java中equals和hashCode为什么要一起重写
java·面试·哈希算法·equals·hashcode
2013crazy1 小时前
springboot基于微信小程序的仓储管理系统
spring boot·后端·微信小程序·仓储管理
蝴蝶不愿意2 小时前
Java基础学习笔记-static关键字
java·开发语言·学习