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

1. 创建 API key   网址:deepseek API keys 
点击创建API key,把创建的key值复制下来,以后就不能再查看了,只能重新创建。

2. 创建springboot工程,代码如下:

pom.xml添加依赖项

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.14</version>
</dependency>

DeepSeekController

package com.example.Controller;

import com.example.Wrapper.DeepSeekServiceWrapper;
import com.example.Wrapper.OpenAiServiceWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/api")
public class DeepSeekController {

    private static final Logger logger = LoggerFactory.getLogger(DeepSeekController.class);

    @Autowired
    private DeepSeekServiceWrapper deepSeekServiceWrapper;

    @GetMapping("/askDeepSeek")
    public String askDeepSeek(@RequestParam String question) {

        logger.info("AI模型调用:DeepSeekServiceWrapper log");

        // 返回响应内容
        try {
            return deepSeekServiceWrapper.generateText(question);
        } catch (IOException e) {
            e.printStackTrace();
            return "Error askDeepSeek question";
        }
    }
}

DeepSeekServiceWrapper

package com.example.Wrapper;

import com.theokanning.openai.service.OpenAiService;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class DeepSeekServiceWrapper {

    private String apiKey = "sk-b0c309055d51431b9747e8a3ed0XXXXX";
    private String apiUrl = "https://api.deepseek.com/chat/completions";

    private OpenAiService openAiService;

    public String generateText(String question) throws IOException {

        CloseableHttpClient client = HttpClients.createDefault();

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

        // 动态构建请求体
        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());
        } catch (Exception e) {
            e.printStackTrace();
            return "Error generating text";
        }
    }
}

注意:apiKey需要替换成自己申请的key。

Demo1Application

package com.example.demo1;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = "com.example")
public class Demo1Application {

    public static void main(String[] args) {

       SpringApplication.run(Demo1Application.class, args);
    }
}

编译启动后就可以访问试试看了。

3. 访问并返回示例

访问地址:http://localhost:8080/api/askDeepSeek?question=how%20are%20you
content里的就是返回的回答。

{"id":"66bf706b-ec00-44f6-8370-6c84af4389a6","object":"chat.completion","created":1738976658,"model":"deepseek-chat","choices":[{"index":0,"message":{"role":"assistant","content":"I'm just a computer program, so I don't have feelings, but I'm here and ready to help you with whatever you need! How can I assist you today? 😊"},"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":6,"completion_tokens":37,"total_tokens":43,"prompt_tokens_details":{"cached_tokens":0},"prompt_cache_hit_tokens":0,"prompt_cache_miss_tokens":6},"system_fingerprint":"fp_3a5770e1b4"}

到这里基本算是接入deepseek了,后面可以进行更加深入的学习调查了。

Logo

欢迎加入DeepSeek 技术社区。在这里,你可以找到志同道合的朋友,共同探索AI技术的奥秘。

更多推荐