-
Notifications
You must be signed in to change notification settings - Fork 0
채팅 답변 생성 및 취소 API 구현 #127
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
채팅 답변 생성 및 취소 API 구현 #127
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
33 changes: 33 additions & 0 deletions
33
src/main/java/com/sofa/linkiving/domain/chat/controller/MockAiController.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| package com.sofa.linkiving.domain.chat.controller; | ||
|
|
||
| import java.time.Duration; | ||
| import java.util.Map; | ||
|
|
||
| import org.springframework.http.MediaType; | ||
| import org.springframework.web.bind.annotation.PostMapping; | ||
| import org.springframework.web.bind.annotation.RequestBody; | ||
| import org.springframework.web.bind.annotation.RequestMapping; | ||
| import org.springframework.web.bind.annotation.RestController; | ||
|
|
||
| import reactor.core.publisher.Flux; | ||
|
|
||
| @RestController | ||
| @RequestMapping("/mock/ai") | ||
| public class MockAiController { | ||
|
|
||
| @PostMapping(value = "/generate", produces = MediaType.APPLICATION_NDJSON_VALUE) // 또는 TEXT_EVENT_STREAM_VALUE | ||
| public Flux<String> generateAnswer(@RequestBody Map<String, String> request) { | ||
| String userPrompt = request.get("prompt"); | ||
|
|
||
| String fakeResponse = """ | ||
| 안녕하세요! 저는 임시 AI 봇입니다. 🤖 | ||
| 현재 AI 서버가 구축되지 않아서 테스트용 답변을 드리고 있어요. | ||
| 질문하신 내용인 "%s"에 대해 답변을 생성하는 척 하고 있습니다. | ||
| 취소 기능을 테스트하시려면 지금 바로 취소 버튼을 눌러보세요! | ||
| 타이핑 효과를 위해 천천히 답변을 보내고 있습니다... | ||
| """.formatted(userPrompt); | ||
|
|
||
| return Flux.fromArray(fakeResponse.split("")) | ||
| .delayElements(Duration.ofMillis(100)); | ||
| } | ||
| } |
20 changes: 20 additions & 0 deletions
20
src/main/java/com/sofa/linkiving/domain/chat/error/ChatErrorCode.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| package com.sofa.linkiving.domain.chat.error; | ||
|
|
||
| import org.springframework.http.HttpStatus; | ||
|
|
||
| import com.sofa.linkiving.global.error.code.ErrorCode; | ||
|
|
||
| import lombok.Getter; | ||
| import lombok.RequiredArgsConstructor; | ||
|
|
||
| @Getter | ||
| @RequiredArgsConstructor | ||
| public enum ChatErrorCode implements ErrorCode { | ||
|
|
||
| CHAT_NOT_FOUND(HttpStatus.NOT_FOUND, "C-001", "채팅을 찾을 수 없습니다."), | ||
| ALREADY_GENERATING(HttpStatus.BAD_REQUEST, "C-002", "현재 답변이 생성 중입니다. 잠시만 기다려주세요."); | ||
|
|
||
| private final HttpStatus status; | ||
| private final String code; | ||
| private final String message; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
39 changes: 39 additions & 0 deletions
39
src/main/java/com/sofa/linkiving/domain/chat/manager/SubscriptionManager.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| package com.sofa.linkiving.domain.chat.manager; | ||
|
|
||
| import java.util.Map; | ||
| import java.util.concurrent.ConcurrentHashMap; | ||
|
|
||
| import org.springframework.stereotype.Component; | ||
|
|
||
| import reactor.core.Disposable; | ||
|
|
||
| @Component | ||
| public class SubscriptionManager { | ||
|
|
||
| private final Map<String, Disposable> activeSubscriptions = new ConcurrentHashMap<>(); | ||
|
|
||
| /** | ||
| * 구독 추가 (기존 작업이 있다면 취소 후 등록) | ||
| */ | ||
| public void add(String key, Disposable subscription) { | ||
| cancel(key); // 안전하게 기존 작업 정리 | ||
| activeSubscriptions.put(key, subscription); | ||
| } | ||
|
|
||
| /** | ||
| * 구독 취소 및 자원 해제 | ||
| */ | ||
| public void cancel(String key) { | ||
| Disposable subscription = activeSubscriptions.remove(key); | ||
| if (subscription != null && !subscription.isDisposed()) { | ||
| subscription.dispose(); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * 완료된 구독 제거 (자원 해제 없이 Map에서만 삭제) | ||
| */ | ||
| public void remove(String key) { | ||
| activeSubscriptions.remove(key); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
76 changes: 76 additions & 0 deletions
76
src/main/java/com/sofa/linkiving/domain/chat/service/MessageService.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,12 +1,88 @@ | ||
| package com.sofa.linkiving.domain.chat.service; | ||
|
|
||
| import java.util.Map; | ||
| import java.util.concurrent.ConcurrentHashMap; | ||
|
|
||
| import org.springframework.messaging.simp.SimpMessagingTemplate; | ||
| import org.springframework.stereotype.Service; | ||
| import org.springframework.web.reactive.function.client.WebClient; | ||
|
|
||
| import com.sofa.linkiving.domain.chat.entity.Chat; | ||
| import com.sofa.linkiving.domain.chat.entity.Message; | ||
| import com.sofa.linkiving.domain.chat.enums.Type; | ||
| import com.sofa.linkiving.domain.chat.manager.SubscriptionManager; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
| import reactor.core.Disposable; | ||
|
|
||
| @Service | ||
| @RequiredArgsConstructor | ||
| public class MessageService { | ||
| private final MessageCommandService messageCommandService; | ||
| private final MessageQueryService messageQueryService; | ||
|
|
||
| private final SimpMessagingTemplate messagingTemplate; | ||
| private final SubscriptionManager subscriptionManager; | ||
|
|
||
| private final WebClient webClient = WebClient.create("http://localhost:8080/mock/ai"); | ||
| private final Map<String, StringBuilder> messageBuffers = new ConcurrentHashMap<>(); | ||
|
|
||
| public void generateAnswer(Chat chat, String userMessage) { | ||
|
|
||
| String roomId = chat.getId().toString(); | ||
|
|
||
| if (messageBuffers.containsKey(roomId)) { | ||
| return; | ||
| } | ||
|
|
||
| messageBuffers.put(roomId, new StringBuilder()); | ||
|
|
||
| Disposable subscription = webClient.post() | ||
| .uri("/generate") | ||
| .bodyValue(Map.of("prompt", userMessage)) | ||
| .retrieve() | ||
| .bodyToFlux(String.class) | ||
| .doOnComplete(() -> { | ||
| String fullAnswer = messageBuffers.remove(roomId).toString(); | ||
|
|
||
| saveMessage(chat, Type.USER, userMessage); | ||
| saveMessage(chat, Type.AI, fullAnswer); | ||
|
|
||
| subscriptionManager.remove(roomId); | ||
| messagingTemplate.convertAndSend("/topic/chat/" + roomId, "END_OF_STREAM"); | ||
| }) | ||
| .doOnError(e -> { | ||
| subscriptionManager.remove(roomId); | ||
| messagingTemplate.convertAndSend("/topic/chat/" + roomId, "ERROR: " + e.getMessage()); | ||
| }) | ||
| .subscribe(token -> { | ||
| StringBuilder buffer = messageBuffers.get(roomId); | ||
| if (buffer != null) { | ||
| buffer.append(token); | ||
| } | ||
|
|
||
| messagingTemplate.convertAndSend("/topic/chat/" + roomId, token); | ||
| }); | ||
|
|
||
| subscriptionManager.add(roomId, subscription); | ||
| } | ||
|
|
||
| public void cancelAnswer(Chat chat) { | ||
| String roomId = chat.getId().toString(); | ||
|
|
||
| subscriptionManager.cancel(roomId); | ||
| messageBuffers.remove(roomId); | ||
|
|
||
| messagingTemplate.convertAndSend("/topic/chat/" + roomId, "GENERATION_CANCELLED"); | ||
| } | ||
|
|
||
| private void saveMessage(Chat chat, Type type, String content) { | ||
| Message message = Message.builder() | ||
| .chat(chat) | ||
| .type(type) | ||
| .content(content) | ||
| .build(); | ||
|
|
||
| messageCommandService.saveMessage(message); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.