SpringBoot接入DeepSeekAPI接口

(前排提示!!!!!!!!!!!!这几天模型调用很卡有时候会失败)
1、首先需要进入DeepSeek官网的发放平台https://platform.deepseek.com/usage,然后需要在该平台申请一个APIKEY
在这里插入图片描述
需要注意的是调用这个东西是需要钱的,它刚开始会免费送你十块钱(有期限大概是一个月),你要是只是玩玩可以不充钱,充钱也只需要支付宝微信很方便快捷。
2、创建配置类

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
@Configuration
public class DeepSeekConfig {
    @Value("${deepseek.api.key}")
    private String apiKey;

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getInterceptors().add((request, body, execution) -> {
            request.getHeaders().add("Authorization", "Bearer " + apiKey);
            request.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return execution.execute(request, body);
        });
        return restTemplate;
    }
}

3、创建Service服务


import com.ruoyi.dto.ChatRequest;
import com.ruoyi.dto.ChatResponse;
import com.ruoyi.service.DeepSeekService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;

/**
 * DeepSeekAPI调用服务实现类
 */
@Log4j2
@Service
public class DeepSeekServiceImpl implements DeepSeekService {
    private static final String ERROR_MESSAGE = "请求出现异常,请稍后再试";
    private static final String OUT_TOKEN_LOG = "本次OUT_TOKEN: ";
    private static final String IN_TOKEN_LOG = "本次IN_TOKEN: ";
    @Value("${deepseek.api.model}")
    private String model;
    private final RestTemplate restTemplate;
    private final String apiUrl;

    public DeepSeekServiceImpl(RestTemplate restTemplate,
                           @Value("${deepseek.api.url}") String apiUrl) {
        this.restTemplate = restTemplate;
        this.apiUrl = apiUrl;
    }

    /**
     * 生成回复
     *
     * @param userMessage 用户消息
     * @return 回复
     */
    public String generateResponse(String userMessage) {
        try {
            ChatRequest request = new ChatRequest(
                    model,
                    Arrays.asList(new ChatRequest.Message("user", userMessage))
            );

            ChatResponse response = restTemplate.postForObject(apiUrl, request, ChatResponse.class);

            if (response == null || response.getChoices() == null || response.getChoices().isEmpty()) {
                log.error(ERROR_MESSAGE + ": 空响应");
                return null;
            }

            String result = response.getChoices().get(0).getMessage().getContent();
            log.info(OUT_TOKEN_LOG + countTokens(result));
            log.info(IN_TOKEN_LOG + countTokens(userMessage));

            return result;
        } catch (RestClientException e) {
            log.error(ERROR_MESSAGE + ": API 请求失败", e);
            return null;
        } catch (Exception e) {
            log.error(ERROR_MESSAGE + ": 发生未知异常", e);
            return null;
        }
    }

    /**
     * 计算Token数量
     * @param text
     * @return
     */
    private int countTokens(String text) {
        // 这里实现Token统计逻辑
        // 例如,可以根据空格、标点符号等来统计Token数量
        return text==null?0:text.split("\\s+").length;
    }

    /**
     * 记录Token使用情况
     * @param tokenCount
     */
    private void logTokenUsage(int tokenCount) {
        // 这里实现Token使用情况的日志记录
        System.out.println("Token used: " + tokenCount);
    }

}


4、配置文件内容如下

deepseek:
  api:
    key: #自己申请一个
    url: https://api.deepseek.com/chat/completions #这个url有时候会更新,所以报了错需要考虑一下这个地方
    model: deepseek-chat # deepseek-reasoner() ,两个模型二选一 用的是V3,贵的这个是R1

5、完事

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值