springboot接入deepseek深度求索 java

以下是在springboot中接入aideepseek的过程。官网并没有java的示例。

1. 创建 API keydeepseek API keys

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

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

添加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

传入的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. 成功返回示例
复制代码
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"}

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

相关推荐
Codebee11 小时前
Qoder CLI 与 OneCode 平台深度整合技术实践:CLI委托驱动的开发范式革新
后端
码事漫谈11 小时前
C++程序执行起点不是main:颠覆你认知的真相
后端
可观测性用观测云11 小时前
玩转 Pipelines 之修正链路错误状态码
后端
码事漫谈11 小时前
C++26:开启新纪元
后端
爱笑的眼睛1111 小时前
PyTorch Lightning:重新定义深度学习工程实践
java·人工智能·python·ai
Kevinyu_11 小时前
责任链模式
java·hadoop·责任链模式
明洞日记12 小时前
【设计模式手册012】责任链模式 - 请求处理的流水线艺术
java·设计模式·责任链模式
q***071412 小时前
Java实战:Spring Boot application.yml配置文件详解
java·网络·spring boot
龙卷风040512 小时前
深入理解Spring AI Alibaba多Agent系统:图结构驱动的智能协作
人工智能·后端
雨中飘荡的记忆12 小时前
Spring Alibaba AI 实战指南
java·ai编程