spring boot 实现接入 deepseek gpt接口 流式输出

controller

复制代码
package com.xmkjsoft.ssegpt;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@CrossOrigin
@RestController
@RequestMapping("/chat")
public class ChatController {

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

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

    // 简单保存 prompt 用,实际可优化
    private final ConcurrentHashMap<String, String> promptMap = new ConcurrentHashMap<>();

    @PostMapping("/start")
    public StartResponse startChat(@RequestBody ChatRequest userRequest) {
        String id = UUID.randomUUID().toString();
        promptMap.put(id, userRequest.getPrompt());
        return new StartResponse(id);
    }

    @GetMapping("/stream")
    public SseEmitter stream(@RequestParam String id) {
        SseEmitter emitter = new SseEmitter(0L);
        String prompt = promptMap.get(id);
        if (prompt == null) {
            emitter.completeWithError(new IllegalArgumentException("无效的id"));
            return emitter;
        }

        new Thread(() -> {
            try {
                String json = """
                    {
                      "model": "deepseek-chat",
                      "stream": true,
                      "messages": [
                        { "role": "system", "content": "You are a helpful assistant." },
                        { "role": "user", "content": "%s" }
                      ]
                    }
                    """.formatted(prompt);

                URL url = new URL(apiUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setRequestProperty("Authorization", "Bearer " + apiKey);
                conn.setDoOutput(true);
                conn.getOutputStream().write(json.getBytes());

                try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        if (line.startsWith("data: ")) {
                            String data = line.substring("data: ".length());
                            if ("[DONE]".equals(data)) break;
                            emitter.send(data);
                        }
                    }
                }
                emitter.complete();
                promptMap.remove(id);
            } catch (Exception e) {
                emitter.completeWithError(e);
            }
        }).start();

        return emitter;
    }

    @Data
    public static class ChatRequest {
        private String prompt;
    }

    @Data
    public static class StartResponse {
        private final String id;
    }
}

application.properties

复制代码
spring.application.name=ssegpt
#deepseek.model=deepseek-reasoner
deepseek.model=deepseek-chat
deepseek.api.key=自己去获取
deepseek.api.url=https://api.deepseek.com/v1/chat/completions

index.html

复制代码
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8" />
    <title>SSE Chat Demo</title>
</head>
<body>
<textarea id="input" rows="3" cols="40" placeholder="输入你的问题"></textarea><br/>
<button id="sendBtn">发送</button>

<div id="output" style="white-space: pre-wrap; border: 1px solid #ccc; padding: 10px; margin-top: 10px;"></div>

<script>
    document.getElementById('sendBtn').onclick = () => {
        const prompt = document.getElementById('input').value.trim();
        if (!prompt) return alert("请输入内容");

        fetch('/chat/start', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ prompt })
        }).then(res => res.json())
            .then(data => {
                if (!data.id) throw new Error("启动失败");
                listenSSE(data.id);
            }).catch(err => alert("启动错误:" + err));
    };

    function listenSSE(id) {
        const evtSource = new EventSource('/chat/stream?id=' + encodeURIComponent(id));
        const output = document.getElementById('output');
        output.textContent = '';  // 清空之前内容

        evtSource.onmessage = (e) => {
            if (e.data === '[DONE]') {
                evtSource.close();
                return;
            }
            try {
                const json = JSON.parse(e.data);
                const content = json.choices && json.choices[0] && json.choices[0].delta && json.choices[0].delta.content;
                if (content !== undefined) {
                    output.textContent += content;
                }
            } catch (err) {
                output.textContent += e.data;
            }
        };

        evtSource.onerror = (e) => {
            console.error("连接错误", e);
            evtSource.close();
        };
    }
</script>

</body>
</html>

maven 依赖

复制代码
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
 </dependency>

 <dependency>
    <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
相关推荐
Q_Q19632884751 小时前
python+springboot+uniapp基于微信小程序的校园二手闲置二手交易公益系统 二手交易+公益捐赠
spring boot·python·django·flask·uni-app·node.js·php
悟能不能悟1 小时前
springboot用jar启动能访问,但是打成war,部署到tomcat却访问不到
spring boot·tomcat·jar
Q_Q19632884753 小时前
python+spring boot洪涝灾害应急信息管理系统 灾情上报 预警发布 应急资源调度 灾情图表展示系统
开发语言·spring boot·python·django·flask·node.js·php
卡布叻_星星4 小时前
前端JavaScript笔记之父子组件数据传递,watch用法之对象形式监听器的核心handler函数
前端·javascript·笔记
徐小夕@趣谈前端7 小时前
如何实现多人协同文档编辑器
javascript·vue.js·设计模式·前端框架·开源·编辑器·github
小白呀白7 小时前
【uni-app】树形结构数据选择框
前端·javascript·uni-app
李昊哲小课8 小时前
Spring Boot 基础教程
java·大数据·spring boot·后端
Swift社区8 小时前
Spring Boot 3.x + Security + OpenFeign:如何避免内部服务调用被重复拦截?
java·spring boot·后端
开发者小天9 小时前
uniapp中封装底部跳转方法
前端·javascript·uni-app