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>
相关推荐
拉不动的猪9 小时前
移动端调试工具VConsole初始化时的加载阻塞问题
前端·javascript·微信小程序
大金乄11 小时前
封装一个vue2的elementUI 表格组件(包含表格编辑以及多级表头)
前端·javascript
Lee川13 小时前
解锁 JavaScript 的灵魂:深入浅出原型与原型链
javascript·面试
swipe14 小时前
从原理到手写:彻底吃透 call / apply / bind 与 arguments 的底层逻辑
前端·javascript·面试
Lee川16 小时前
探索JavaScript的秘密令牌:独一无二的`Symbol`数据类型
javascript·面试
Lee川16 小时前
深入浅出JavaScript事件机制:从捕获冒泡到事件委托
前端·javascript
光影少年16 小时前
async/await和Promise的区别?
前端·javascript·掘金·金石计划
codingWhat16 小时前
如何实现一个「万能」的通用打印组件?
前端·javascript·vue.js
前端Hardy18 小时前
别再无脑用 `JSON.parse()` 了!这个安全漏洞你可能每天都在触发
前端·javascript·vue.js
前端Hardy18 小时前
别再让 `console.log` 上线了!它正在悄悄拖垮你的生产系统
前端·javascript·vue.js