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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
@GetMapping(value = "/api/chatgpt/test", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public SseEmitter testChatGpt(@RequestParam String message) throws Exception {
final SseEmitter emitter = new SseEmitter(Long.MAX_VALUE);
executorService.execute(() -> { CompletionRequest request = CompletionRequest.builder() .stream(true) .messages(Collections.singletonList(Message.builder().role(CompletionRequest.Role.USER).content(message).build())) .model(CompletionRequest.Model.CHATGLM_TURBO.getCode()) .build();
CountDownLatch countDownLatch = new CountDownLatch(1);
try { openAiSession.completions(request, new EventSourceListener() { @Override public void onEvent(EventSource eventSource, @Nullable String id, @Nullable String type, String data) { if ("[DONE]".equalsIgnoreCase(data)) { log.info("OpenAI 应答完成"); return; }
CompletionResponse chatCompletionResponse = JSON.parseObject(data, CompletionResponse.class); List<ChatChoice> choices = chatCompletionResponse.getChoices(); for (ChatChoice chatChoice : choices) { Message delta = chatChoice.getDelta(); if (CompletionRequest.Role.ASSISTANT.getCode().equals(delta.getRole())) continue;
String finishReason = chatChoice.getFinishReason(); if (StringUtils.isNoneBlank(finishReason) && "stop".equalsIgnoreCase(finishReason)) { return; } try { emitter.send(data); } catch (IOException e) { throw new RuntimeException(e); } log.info("测试结果:{}", delta.getContent()); } }
@Override public void onClosed(EventSource eventSource) { log.info("对话完成"); emitter.complete(); countDownLatch.countDown(); }
@Override public void onFailure(EventSource eventSource, @Nullable Throwable t, @Nullable Response response) { emitter.completeWithError(t); log.info("对话异常"); countDownLatch.countDown(); } }); } catch (Exception e) { throw new RuntimeException(e); }
try { countDownLatch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } });
return emitter; }
|