欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot兩種方式接入DeepSeek的實現(xiàn)

 更新時間:2025年03月24日 10:27:08   作者:赤橙紅的黃  
本文主要介紹了SpringBoot兩種方式接入DeepSeek的實現(xiàn),包括HttpClient方式和基于spring-ai-openai的方式,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

方式一:基于HttpClient

步驟 1:準備工作

獲取 DeepSeek API 密鑰:訪問 DeepSeek 的開發(fā)者平臺,注冊并獲取 API 密鑰。

步驟 2:引入依賴

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

步驟 3:配置 DeepSeek API

配置參數(shù):在 application.yml 文件里,把 DeepSeek 的 API 端點和密鑰寫進去:

在 application.properties 或 application.yml 中配置 DeepSeek 的 API 密鑰和端點:

deepseek.api.key=sk-xxxxxxxxxx
deepseek.api.url=https://api.deepseek.com/v1/chat/completions

步驟 4:自定義  DeepSeek Client Service

(1)自定義請求頭

public record DeepSeekRequest(
        String model,
        List<Message> messages,
        double temperature,
        int max_tokens
) {
    public record Message(String role, String content) {}
}

(2)自定義響應體

public record DeepSeekResponse(
        String id,
        String object,
        long created,
        String model,
        List<Choice> choices
) {
    public record Choice(
            int index,
            Message message,
            String finish_reason
    ) {
        public record Message(String role, String content) {}
    }
}

(3)service

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Service
public class DeepSeekService {

    @Value("${deepseek.api.url}")
    private String apiUrl;

    @Value("${deepseek.api.key}")
    private String apiKey;

    private final RestTemplate restTemplate;

    public DeepSeekService(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
    }

    public String getChatResponse(String userMessage) {
        // 構造請求體
        DeepSeekRequest request = new DeepSeekRequest(
                "deepseek-chat",
                List.of(new DeepSeekRequest.Message("user", userMessage)),
                0.7,
                1000
        );

        // 設置請求頭
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(apiKey);

        HttpEntity<DeepSeekRequest> entity = new HttpEntity<>(request, headers);

        // 發(fā)送請求
        ResponseEntity<DeepSeekResponse> response = restTemplate.exchange(
                apiUrl,
                HttpMethod.POST,
                entity,
                DeepSeekResponse.class
        );

        // 處理響應
        if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
            return response.getBody().choices().get(0).message().content();
        }
        throw new RuntimeException("API請求失敗: " + response.getStatusCode());
    }
}

請求體中可以指定:調整模型、溫度、最大 token 數(shù)等

什么是溫度(Temperature)?

溫度是控制模型生成文本的“創(chuàng)造力”或“隨機性”的一個參數(shù)。你可以把它想象成調節(jié)模型的“腦洞大小”。

  • 溫度低(比如 0.1)

模型會變得非常保守,傾向于選擇最確定、最安全的答案。

適合需要準確性和一致性的任務,比如回答事實性問題。

例子:問“1+1等于幾?”,模型會回答“2”,不會瞎編。

  • 溫度高(比如 1.0 或更高)

模型會變得更有創(chuàng)造力,可能會給出一些意想不到的回答。

適合需要創(chuàng)意或多樣性的任務,比如寫故事、生成詩歌。

例子:問“寫一首關于秋天的詩”,模型可能會生成一些充滿想象力的句子。

  • 溫度適中(比如 0.7)

模型會在保守和創(chuàng)意之間找到一個平衡點。

適合大多數(shù)任務,既能保證一定的準確性,又能有一些變化。

總結

  • 溫度低 → 模型像“學霸”,回答嚴謹?shù)赡軣o聊。

  • 溫度高 → 模型像“藝術家”,回答有趣但可能不靠譜。

  • 溫度適中 → 模型像“聰明人”,回答既靠譜又有趣。

最大 token 數(shù)(Max Tokens)

token 是模型處理文本的基本單位,可以理解為一個詞或一部分詞。

比如:

  • 英文單詞“hello”是一個 token。

  • 中文“你好”可能是兩個 token(每個字一個 token)。

  • 長單詞或復雜字符可能會被拆成多個 token。

最大 token 數(shù)就是限制模型生成的文本長度??梢园阉胂蟪山o模型一個“字數(shù)限制”。

  • 設置較小的最大 token 數(shù)(比如 50)

模型生成的文本會非常短,可能只回答問題的核心部分。

例子:問“介紹一下太陽系”,模型可能只回答“太陽系包括太陽和八大行星”。

  • 設置較大的最大 token 數(shù)(比如 500)

模型生成的文本會更長,可能會包含更多細節(jié)。

例子:問“介紹一下太陽系”,模型可能會詳細描述每顆行星的特點。

  • 不設置最大 token 數(shù)

模型可能會一直生成文本,直到達到它的內部限制(通常是幾千個 token)。

這可能會導致生成的文本過長,甚至跑題。

總結

  • 最大 token 數(shù)小 → 模型像“話少的人”,回答簡短。

  • 最大 token 數(shù)大 → 模型像“話多的人”,回答詳細。

  • 不設置最大 token 數(shù) → 模型像“話癆”,可能會一直說個不停。

步驟 5:創(chuàng)建控制器

@RestController
@RequestMapping("/deepseek/chat")
public class DeepSeekController {
    private final DeepSeekService deepSeekService;

    public DeepSeekController(DeepSeekService deepSeekService) {
        this.deepSeekService = deepSeekService;
    }

    @PostMapping
    public ResponseEntity<?> chat(@RequestBody Map<String, String> request) {
        try {
            String response = deepSeekService.getChatResponse(request.get("message"));
            return ResponseEntity.ok(Collections.singletonMap("response", response));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Collections.singletonMap("error", e.getMessage()));
        }
    }
}

方式二:基于spring-ai-openai

步驟基本一致,這里羅列幾處實現(xiàn)代碼

依賴:

<properties>
     <java.version>17</java.version>
     <spring-ai.version>1.0.0-M5</spring-ai.version>
</properties>
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>
<dependencyManagement>
    <dependencies>
        <dependency>
             <groupId>org.springframework.ai</groupId>
             <artifactId>spring-ai-bom</artifactId>
             <version>${spring-ai.version}</version>
             <type>pom</type>
             <scope>import</scope>
       </dependency>
    </dependencies>
</dependencyManagement>

DeepSeekConfig:

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DeepSeekConfig {
    @Bean
    public ChatClient chatClient(OpenAiChatModel openAiChatModel) {
        return ChatClient.builder(openAiChatModel).build();
    }
}

DeepSeekController:

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.ai.chat.model.ChatResponse;

import java.util.ArrayList;
import java.util.List;


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

    @Resource
    private OpenAiChatModel chatModel;

    private final List<Message> chatHistoryList = new ArrayList<>();

    @PostConstruct
    public void init() {
        chatHistoryList.add(new SystemMessage("You are a helpful assistant."));
    }

    @PostMapping("/chat")
    public ChatResponse test(@RequestBody String message) {
        chatHistoryList.add(new UserMessage(message));
        Prompt prompt = new Prompt(chatHistoryList);
        ChatResponse chatResponse = chatModel.call(prompt);
        if (chatResponse.getResult() != null && chatResponse.getResult().getOutput() != null) {
            chatHistoryList.add(chatResponse.getResult().getOutput());
        }
        return chatResponse;
    }

}

到此這篇關于SpringBoot兩種方式接入DeepSeek的實現(xiàn)的文章就介紹到這了,更多相關SpringBoot接入DeepSeek內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家! 

相關文章

  • java實現(xiàn)乘地鐵方案的最優(yōu)選擇(票價,距離)

    java實現(xiàn)乘地鐵方案的最優(yōu)選擇(票價,距離)

    這篇文章主要介紹了java實現(xiàn)乘地鐵方案的最優(yōu)選擇(票價,距離),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-07-07
  • Spring Eureka 未授權訪問漏洞修復問題小結

    Spring Eureka 未授權訪問漏洞修復問題小結

    項目組使用的 Spring Boot 比較老,是 1.5.4.RELEASE ,最近被檢測出 Spring Eureka 未授權訪問漏洞,這篇文章主要介紹了Spring Eureka 未授權訪問漏洞修復問題小結,需要的朋友可以參考下
    2024-04-04
  • 在Java中去除字符串末尾的換行符的常用方法小結

    在Java中去除字符串末尾的換行符的常用方法小結

    在日常開發(fā)中,字符串操作是非常常見的需求,其中去除字符串末尾的換行符(\n)是一個很有代表性的場景,本文將從 Java 的幾種常用方法著手,全面解析如何去除字符串末尾的換行符,并結合代碼示例和實際使用場景,幫助大家掌握這一技巧,需要的朋友可以參考下
    2024-12-12
  • Java的JSON處理器fastjson使用方法詳解

    Java的JSON處理器fastjson使用方法詳解

    下面小編就為大家?guī)硪黄狫ava的JSON處理器fastjson使用方法詳解。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-08-08
  • 利用Java反射機制實現(xiàn)對象相同字段的復制操作

    利用Java反射機制實現(xiàn)對象相同字段的復制操作

    這篇文章主要介紹了利用Java反射機制實現(xiàn)對象相同字段的復制操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-08-08
  • Spring AOP如何在注解上使用SPEL表達式注入對象

    Spring AOP如何在注解上使用SPEL表達式注入對象

    這篇文章主要介紹了Spring AOP如何在注解上使用SPEL表達式注入對象,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-02-02
  • 快速入手IntelliJ IDEA基本配置

    快速入手IntelliJ IDEA基本配置

    IntelliJ IDEA是java編程語言開發(fā)的集成環(huán)境,本篇主要介紹了對它的安裝、配置maven倉庫、調試方法、常用的插件推薦、快捷鍵大全與常用快捷鍵說明,感興趣的朋友一起看看吧
    2021-10-10
  • MybatisPlus BaseMapper 中的方法全部 Invalid bound statement (not found Error處理)

    MybatisPlus BaseMapper 中的方法全部 Invalid bound statement (not f

    這篇文章主要介紹了MybatisPlus BaseMapper 中的方法全部 Invalid bound statement (not found)的Error處理方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-09-09
  • Java對象轉json JsonFormat注解

    Java對象轉json JsonFormat注解

    這篇文章主要介紹了Java對象轉json JsonFormat注解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-05-05
  • java使用淘寶API讀寫json實現(xiàn)手機歸屬地查詢功能代碼

    java使用淘寶API讀寫json實現(xiàn)手機歸屬地查詢功能代碼

    本文介紹java使用淘寶API讀寫json實現(xiàn)手機歸屬地查詢功能,代碼簡單,大家可以參考使用
    2013-11-11

最新評論