Junjie
8 天以前 4898d942bd6e3c1119493cf0314b15f2bd54daf3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.zy.ai.service;
 
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
 
@Slf4j
@Component
public class PythonService {
 
    @Autowired
    private LlmChatService llmChatService;
 
    public boolean runPython(String prompt, String chatId, SseEmitter emitter) {
        try {
            llmChatService.chatStreamRunPython(prompt, chatId, s -> {
                try {
                    String safe = s == null ? "" : s.replace("\r", "").replace("\n", "\\n");
                    if (!safe.isEmpty()) {
                        sse(emitter, safe);
                    }
                } catch (Exception ignore) {
                }
            }, () -> {
                try {
                    sse(emitter, "\\n\\n【AI】运行已停止(正常结束)\\n\\n");
                    log.info("AI MCP diagnose stopped: final end");
                    emitter.complete();
                } catch (Exception ignore) {
                }
            }, e -> {
                sse(emitter, "\\n\\n【AI】分析出错,正在回退...\\n\\n");
            });
            return true;
        } catch (Exception e) {
            try {
                sse(emitter, "\\n\\n【AI】运行已停止(异常)\\n\\n");
                log.error("AI MCP diagnose stopped: error", e);
                emitter.completeWithError(e);
            } catch (Exception ignore) {}
            return true;
        }
    }
 
    private void sse(SseEmitter emitter, String data) {
        if (data == null) return;
        try {
            emitter.send(SseEmitter.event().data(data));
        } catch (Exception e) {
            log.warn("SSE send failed", e);
        }
    }
 
}