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"}

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

相关推荐
Lhappy嘻嘻2 小时前
Java IO|File 文件操作 + 字节流 / 字符流完整笔记 + 递归删除文件实战
java·笔记·php
To_OC2 小时前
手写 AI 编程 Agent 的命令执行工具:我被 child_process 坑出来的实战经验
后端·node.js·agent
伊玛目的门徒2 小时前
试用leetcode之典中典 二数之和问题
java·算法·leetcode
逝水无殇4 小时前
C# 异常处理详解
开发语言·后端·c#
懒鸟一枚5 小时前
深入理解 Linux 内存、Swap 交换分区与分页机制的关系
java·linux·数据库
我命由我123456 小时前
执行 Gradle 指令报错,无法将“grep”项识别为 cmdlet、函数、脚本文件或可运行程序的名称
android·java·java-ee·android studio·android jetpack·android-studio·android runtime
考虑考虑6 小时前
Sentinel安装
java·后端·微服务
IT_陈寒6 小时前
SpringBoot自动配置失灵?你可能忘了这个关键注解
前端·人工智能·后端
碎碎念_4927 小时前
SpringBoot + Vue 前后端分离从 0 到 1 完整环境配置流程
vue.js·spring boot·后端
逝水无殇7 小时前
C# 文件的输入与输出详解
开发语言·数据库·后端·c#