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
|
@Slf4j @RestController @RequiredArgsConstructor public class AiController {
@Resource private final AIMiddlePlatform aimiddlePlatform;
private final ExecutorService nonBlockingService = Executors.newCachedThreadPool(); @PostMapping(value = "/ai",produces = MediaType.TEXT_EVENT_STREAM_VALUE) public SseEmitter ai(@RequestParam String text) { final SseEmitter sseEmitter = new SseEmitter();
nonBlockingService.execute(() -> { ObjectMapper mapper = new ObjectMapper(); ObjectNode textPart = mapper.createObjectNode().put("text", text);
ArrayNode partsArray = mapper.createArrayNode().add(textPart); ObjectNode contentsObject = mapper.createObjectNode().set("parts", partsArray); ArrayNode contentsArray = mapper.createArrayNode().add(contentsObject); ObjectNode requestBody = mapper.createObjectNode().set("contents", contentsArray);
InputStream result = aimiddlePlatform.intelligentQA(requestBody);
StringBuilder sb = new StringBuilder(); try (BufferedReader br = new BufferedReader(new InputStreamReader(result, "UTF-8")); JsonParser parser = new JsonFactory(mapper).createParser(br)) {
while (!parser.isClosed()) { JsonToken jsonToken = parser.nextToken();
if (jsonToken == null) { break; }
if (JsonToken.FIELD_NAME.equals(jsonToken) && "text".equals(parser.getCurrentName())) { parser.nextToken(); sb.append(parser.getValueAsString()).append("\n"); System.out.println(parser.getValueAsString()); sseEmitter.send(parser.getValueAsString()); } } } catch (Exception e) { e.printStackTrace(); } finally { sseEmitter.complete(); } });
return sseEmitter; } }
|