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

SpringBoot調(diào)用DeepSeek?API的完整操作指南

 更新時(shí)間:2025年02月10日 08:17:48   作者:老大白菜  
這篇文章主要為大家詳細(xì)介紹了SpringBoot調(diào)用DeepSeek?API的完整操作指南,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

1. 項(xiàng)目依賴

在 pom.xml 中添加以下依賴:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>
</dependencies>

2. 項(xiàng)目結(jié)構(gòu)

deepseek-project/
├── src/main/java/com/example/deepseek/
│   ├── DeepSeekApplication.java
│   ├── config/
│   │   └── DeepSeekConfig.java
│   ├── model/
│   │   ├── ChatRequest.java
│   │   ├── ChatResponse.java
│   │   └── Message.java
│   └── service/
│       └── DeepSeekService.java
└── conversation.txt

3. 完整代碼實(shí)現(xiàn)

3.1 配置類 DeepSeekConfig.java

package com.example.deepseek.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Configuration
@Getter
public class DeepSeekConfig {
    @Value("${deepseek.api.url}")
    private String apiUrl;

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

3.2 請求/響應(yīng)模型

Message.java:

package com.example.deepseek.model;

import lombok.Data;

@Data
public class Message {
    private String role;
    private String content;
}

ChatRequest.java:

package com.example.deepseek.model;

import lombok.Data;
import java.util.List;

@Data
public class ChatRequest {
    private String model = "deepseek-ai/DeepSeek-V3";
    private List<Message> messages;
    private boolean stream = true;
    private int max_tokens = 2048;
    private double temperature = 0.7;
    private double top_p = 0.7;
    private int top_k = 50;
    private double frequency_penalty = 0.5;
    private int n = 1;
    private ResponseFormat response_format = new ResponseFormat("text");

    @Data
    public static class ResponseFormat {
        private String type;
        
        public ResponseFormat(String type) {
            this.type = type;
        }
    }
}

ChatResponse.java:

package com.example.deepseek.model;

import lombok.Data;
import java.util.List;

@Data
public class ChatResponse {
    private List<Choice> choices;

    @Data
    public static class Choice {
        private Delta delta;
    }

    @Data
    public static class Delta {
        private String content;
    }
}

3.3 服務(wù)類 DeepSeekService.java

package com.example.deepseek.service;

import com.example.deepseek.config.DeepSeekConfig;
import com.example.deepseek.model.ChatRequest;
import com.example.deepseek.model.ChatResponse;
import com.example.deepseek.model.Message;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.Scanner;

@Service
@RequiredArgsConstructor
public class DeepSeekService {
    private final DeepSeekConfig config;
    private final WebClient.Builder webClientBuilder;
    private final ObjectMapper objectMapper = new ObjectMapper();

    public void startInteractiveChat() {
        try (Scanner scanner = new Scanner(System.in);
             PrintWriter fileWriter = new PrintWriter(new FileWriter("conversation.txt", true))) {

            while (true) {
                System.out.print("\n請輸入您的問題 (輸入 q 退出): ");
                String question = scanner.nextLine().trim();

                if ("q".equalsIgnoreCase(question)) {
                    System.out.println("程序已退出");
                    break;
                }

                // 保存問題
                saveToFile(fileWriter, question, true);

                // 發(fā)起對話請求
                Flux<String> responseFlux = sendChatRequest(question);

                StringBuilder fullResponse = new StringBuilder();
                responseFlux
                    .doOnNext(chunk -> {
                        System.out.print(chunk);
                        fullResponse.append(chunk);
                    })
                    .doOnComplete(() -> {
                        // 保存完整回復(fù)
                        saveToFile(fileWriter, fullResponse.toString(), false);
                        System.out.println("\n----------------------------------------");
                        fileWriter.println("\n----------------------------------------");
                        fileWriter.flush();
                    })
                    .blockLast();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Flux<String> sendChatRequest(String question) {
        ChatRequest request = new ChatRequest();
        Message userMessage = new Message();
        userMessage.setRole("user");
        userMessage.setContent(question);
        request.setMessages(Collections.singletonList(userMessage));

        return webClientBuilder.build()
            .post()
            .uri(config.getApiUrl())
            .header("Authorization", "Bearer " + config.getApiKey())
            .header("Content-Type", "application/json")
            .bodyValue(request)
            .retrieve()
            .bodyToFlux(String.class)
            .filter(line -> line.startsWith("data: ") && !line.equals("data: [DONE]"))
            .map(line -> {
                try {
                    String jsonStr = line.substring(6);
                    ChatResponse response = objectMapper.readValue(jsonStr, ChatResponse.class);
                    return response.getChoices().get(0).getDelta().getContent();
                } catch (Exception e) {
                    return "";
                }
            })
            .filter(content -> !content.isEmpty());
    }

    private void saveToFile(PrintWriter fileWriter, String content, boolean isQuestion) {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        if (isQuestion) {
            fileWriter.printf("\n[%s] Question:\n%s\n\n[%s] Answer:\n", timestamp, content, timestamp);
        } else {
            fileWriter.print(content);
        }
        fileWriter.flush();
    }
}

3.4 主應(yīng)用類 DeepSeekApplication.java

package com.example.deepseek;

import com.example.deepseek.service.DeepSeekService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class DeepSeekApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(DeepSeekApplication.class, args);
        DeepSeekService deepSeekService = context.getBean(DeepSeekService.class);
        deepSeekService.startInteractiveChat();
    }
}

3.5 配置文件 application.properties

deepseek.api.url=https://api.siliconflow.cn/v1/chat/completions
deepseek.api.key=YOUR_API_KEY

4. 代碼詳解

4.1 關(guān)鍵特性

使用 Spring WebFlux 的響應(yīng)式編程模型

流式處理 API 響應(yīng)

文件記錄對話

錯(cuò)誤處理和異常管理

4.2 主要組件

DeepSeekConfig: 管理 API 配置

DeepSeekService: 處理對話邏輯和 API 交互

模型類: 定義請求和響應(yīng)結(jié)構(gòu)

5. 使用方法

替換 application.properties 中的 YOUR_API_KEY

運(yùn)行 DeepSeekApplication

在控制臺輸入問題

輸入 ‘q’ 退出程序

查看 conversation.txt 獲取對話記錄

6. 性能和可擴(kuò)展性

使用響應(yīng)式編程提高并發(fā)性能

靈活的配置管理

易于擴(kuò)展和定制

7. 注意事項(xiàng)

確保正確配置 API Key

處理網(wǎng)絡(luò)異常

注意內(nèi)存使用

總結(jié)

Spring Boot 實(shí)現(xiàn)提供了一個(gè)健壯、可擴(kuò)展的 DeepSeek API 調(diào)用方案,利用響應(yīng)式編程提供高效的流式對話體驗(yàn)。

到此這篇關(guān)于SpringBoot調(diào)用DeepSeek API的完整操作指南的文章就介紹到這了,更多相關(guān)SpringBoot調(diào)用DeepSeek API內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 通過Java實(shí)現(xiàn)中文分詞與文本關(guān)鍵詞提取

    通過Java實(shí)現(xiàn)中文分詞與文本關(guān)鍵詞提取

    這篇文章主要為大家詳細(xì)介紹了如何利用Java實(shí)現(xiàn)中文分詞以及文本關(guān)鍵詞提取功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)學(xué)習(xí)
    2023-06-06
  • 基于ArrayList源碼解析(基于JDK1.8)

    基于ArrayList源碼解析(基于JDK1.8)

    這篇文章主要介紹了關(guān)于ArrayList源碼解析(基于JDK1.8),具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • logback TimeBasedRollingPolicy按天生成日志源碼解析

    logback TimeBasedRollingPolicy按天生成日志源碼解析

    這篇文章主要為大家介紹了logback TimeBasedRollingPolicy按天生成日志源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-11-11
  • 解決spring boot2集成activiti6踩過的坑

    解決spring boot2集成activiti6踩過的坑

    這篇文章主要介紹了解決spring boot2集成activiti6踩過的坑,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • 不調(diào)用方法實(shí)現(xiàn)hutool導(dǎo)出excel圖片示例詳解

    不調(diào)用方法實(shí)現(xiàn)hutool導(dǎo)出excel圖片示例詳解

    這篇文章主要為大家介紹了不調(diào)用方法實(shí)現(xiàn)hutool導(dǎo)出excel圖片示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-08-08
  • java基于包結(jié)構(gòu)的請求路由實(shí)現(xiàn)實(shí)例分享

    java基于包結(jié)構(gòu)的請求路由實(shí)現(xiàn)實(shí)例分享

    基于包結(jié)構(gòu)的請求路由簡單實(shí)現(xiàn)實(shí)例分享,大家參考使用吧
    2013-12-12
  • Feign 使用HttpClient和OkHttp方式

    Feign 使用HttpClient和OkHttp方式

    這篇文章主要介紹了Feign 使用HttpClient和OkHttp方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • Java線程中Thread方法下的Join方法詳解

    Java線程中Thread方法下的Join方法詳解

    這篇文章主要介紹了Java線程中Thread方法下的Join方法詳解,在項(xiàng)目中往往會(huì)遇到這樣一個(gè)場景,就是需要等待幾件事情都給做完后才能走下面的事情,這個(gè)時(shí)候就需要用到Thread方法下的Join方法,join方法是無參且沒有返回值的,需要的朋友可以參考下
    2024-01-01
  • 基于SpringBoot實(shí)現(xiàn)防盜鏈功能

    基于SpringBoot實(shí)現(xiàn)防盜鏈功能

    防盜鏈?zhǔn)潜Wo(hù)資源服務(wù)器的常用方法,旨在防止未經(jīng)授權(quán)的外部鏈接直接訪問服務(wù)器上的資源,如圖片、音頻和視頻文件,在本文中,我們將探討防盜鏈的概念和原理,并結(jié)合 Spring Boot 提供一個(gè)完整的可運(yùn)行示例,需要的朋友可以參考下
    2024-12-12
  • java Socket實(shí)現(xiàn)網(wǎng)頁版在線聊天

    java Socket實(shí)現(xiàn)網(wǎng)頁版在線聊天

    這篇文章主要為大家詳細(xì)介紹了java Socket實(shí)現(xiàn)網(wǎng)頁版在線聊天具體代碼,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2016-05-05

最新評論