SpringBoot 调用deepseek

发布于:2025-04-19 ⋅ 阅读:(21) ⋅ 点赞:(0)

个人学习心得,仅供参考

软件环境:

 JDK  17  你用JDK 11 无法支持SpringBoot 3
 
SpringBoot 3 版本以上才支持spring ai

mavan 3.6.1

1.获取Deepseek官网的API-key

官网:https://platform.deepseek.com/api_keys

在这里插入图片描述

2.创建项目

这样创建
在这里插入图片描述
添加依赖
在这里插入图片描述

项目结构
在这里插入图片描述
下面是源码
application.properties配置文件

spring.ai.openai.api-key=  你复制的API key
spring.ai.openai.base-url=https://api.deepseek.com
spring.ai.openai.chat.options.model=deepseek-chat
spring.ai.openai.chat.options.temperature=0.7

service类


import org.springframework.ai.chat.model.ChatResponse;
import reactor.core.publisher.Flux;

public interface DeepSeekService {

    /* 根据消息直接输出回答 */
    String chat(String message);

    /* 根据消息直接输出回答 流式输出 */
    Flux<ChatResponse> chatFlux(String message);

}

service实现类

import com.hpl.service.DeepSeekService;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;


@Service
public class DeepSeekServiceImpl implements DeepSeekService {

    @Resource
    private OpenAiChatModel  chatModel;


    @Override
    public String chat(String message) {
        return chatModel.call(message);
    }

    @Override
    public Flux<ChatResponse> chatFlux(String message) {
        Prompt prompt = new Prompt(new UserMessage(message));
        return chatModel.stream(prompt);
    }

}

controller类

import jakarta.annotation.Resource;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.http.MediaType;
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 reactor.core.publisher.Flux;

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

    @Resource
    private DeepSeekService deepSeekService;

    @GetMapping(value = "/chat", produces = MediaType.APPLICATION_JSON_VALUE)
    public String chat(@RequestParam(value = "message") String message) {
        return deepSeekService.chat(message);
    }

    @GetMapping(value = "/chatFlux", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ChatResponse> chatFlux(@RequestParam(value = "message") String message) {
        return deepSeekService.chatFlux(message);
    }
}

然后启动SpringBoot
去postman测试

http://localhost:8080/ai/chat?message=你是谁

在这里插入图片描述

参考文档

spring-ai 官网:https://docs.spring.io/spring-ai/reference/api/chat/deepseek-chat.html
deepseek 官方文档:https://api-docs.deepseek.com/zh-cn/


网站公告

今日签到

点亮在社区的每一天
去签到