PlexPt / chatgpt-java

ChatGPT Java SDK。支持 GPT-4o、 GPT4 API。开箱即用。An unofficial Java SDK for seamless integration with ChatGPT's GPT-3.5 and GPT-4 APIs. Ready-to-use, simple setup, and efficient for building AI-powered applications.
https://chat.plexpt.com/
GNU General Public License v3.0
3.58k stars 704 forks source link

用 SseEmitter 的方式返回,前端显示问号怎么解决。 #102

Closed topcss closed 1 year ago

topcss commented 1 year ago

image

我用的这段代码。 `

@GetMapping("/chat/sse")
@CrossOrigin
public SseEmitter sseEmitter(String prompt) {
   //国内需要代理 国外不需要
   Proxy proxy = Proxys.http("127.0.0.1", 1080);

   ChatGPTStream chatGPTStream = ChatGPTStream.builder()
            .timeout(600)
            .apiKey("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")
            .proxy(proxy)
            .apiHost("https://api.openai.com/")
            .build()
            .init();

    SseEmitter sseEmitter = new SseEmitter(-1L);

    SseStreamListener listener = new SseStreamListener(sseEmitter);
    Message message = Message.of(prompt);

    listener.setOnComplate(msg -> {
        //回答完成,可以做一些事情
    });
    chatGPTStream.streamChatCompletion(Arrays.asList(message), listener);

    return sseEmitter;
}

`

topcss commented 1 year ago

我解决了,重写了这个类。


package com.plexpt.chatgpt.util;

import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.nio.charset.Charset;

public final class SseHelper {
    public static void complete(SseEmitter sseEmitter) {
        try {
            sseEmitter.complete();
        } catch (Exception var2) {
        }

    }

    public static void send(SseEmitter sseEmitter, Object data) {
        try {
            if (data == null) {
                sseEmitter.send("\n");
            } else {
                sseEmitter.send(data.toString().getBytes(Charset.forName("UTF-8")));
            }
        } catch (Exception var3) {
        }

    }

    private SseHelper() {
        throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
    }
}