Grt1228 / chatgpt-steam-output

Open AI ChatGPT流式输出。Open AI Stream output. ChatGPT Stream output.GPT-3.5
461 stars 173 forks source link

使用流式输出如何获取返回的内容啊???有大佬指指路吗 #35

Open kiliyxiaohao opened 9 months ago

kiliyxiaohao commented 9 months ago

@Slf4j public class ConsoleEventSourceListener extends EventSourceListener {

@Override
public void onOpen(EventSource eventSource, Response response) {
    log.info("OpenAI建立sse连接...");
}

@Override
public void onEvent(EventSource eventSource, String id, String type, String data) {
    log.info("OpenAI返回数据:{}", data);
    if (data.equals("[DONE]")) {
        log.info("OpenAI返回数据结束了");
        return;
    }
}

@Override
public void onClosed(EventSource eventSource) {
    log.info("OpenAI关闭sse连接...");
}

@SneakyThrows
@Override
public void onFailure(EventSource eventSource, Throwable t, Response response) {
    if(Objects.isNull(response)){
        log.error("OpenAI  sse连接异常:{}", t);
        eventSource.cancel();
        return;
    }
    ResponseBody body = response.body();
    if (Objects.nonNull(body)) {
        log.error("OpenAI  sse连接异常data:{},异常:{}", body.string(), t);
    } else {
        log.error("OpenAI  sse连接异常data:{},异常:{}", response, t);
    }
    eventSource.cancel();
}

}