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

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

相关推荐
Demon_Hao12 分钟前
JAVA通过Redis实现Key分区分片聚合点赞、收藏等计数同步数据库,并且通过布隆过滤器防重复点赞
java·数据库·redis
华科易迅23 分钟前
Spring装配对象方法-注解
java·后端·spring
庄周的大鱼1 小时前
分析@TransactionalEventListener注解失效
java·spring·springboot·事务监听器·spring 事件机制·事务注解失效解决
史蒂芬_丁1 小时前
C++深度拷贝例子
java·开发语言·c++
似水এ᭄往昔2 小时前
【Linux】自动化构建-make/Makefile
linux·运维·服务器·ubuntu
云烟成雨TD2 小时前
Spring AI Alibaba 1.x 系列【4】ReAct 范式与 ReactAgent 核心设计
java·人工智能·spring
「QT(C++)开发工程师」2 小时前
C++11三大核心特性深度解析:类型特征、时间库与原子操作
java·c++·算法
顶点多余2 小时前
Linux“信号“从硬件到软件详解
linux·运维·服务器
乐分启航2 小时前
SliMamba:十余K参数量刷新SOTA!高光谱分类的“降维打击“来了
java·人工智能·深度学习·算法·机器学习·分类·数据挖掘
yoothey3 小时前
Java字节流与字符流核心笔记(问答+考点复盘)
java·开发语言·笔记