forked from Blaybus212/backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConversationService.java
More file actions
240 lines (198 loc) · 8.44 KB
/
ConversationService.java
File metadata and controls
240 lines (198 loc) · 8.44 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
package com.blaybus.backend.service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Slice;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.blaybus.backend.domain.alignment.Component;
import com.blaybus.backend.domain.conversation.Conversation;
import com.blaybus.backend.domain.conversation.Message;
import com.blaybus.backend.domain.conversation.Reference;
import com.blaybus.backend.domain.conversation.Sender;
import com.blaybus.backend.domain.user.User;
import com.blaybus.backend.dto.ConversationDto.ComponentInfo;
import com.blaybus.backend.dto.ConversationDto.ConversationResponse;
import com.blaybus.backend.dto.ConversationDto.ConversationSummaryResponse;
import com.blaybus.backend.dto.ConversationDto.MessageResponse;
import com.blaybus.backend.dto.ConversationDto.PageInfo;
import com.blaybus.backend.dto.ConversationDto.SendMessageRequest;
import com.blaybus.backend.dto.ConversationDto.SendMessageResponse;
import com.blaybus.backend.dto.OpenAiDto.AssistantResponse;
import com.blaybus.backend.dto.OpenAiDto.SummaryResponse;
import com.blaybus.backend.exception.BusinessException;
import com.blaybus.backend.exception.CommonErrorCode;
import com.blaybus.backend.repository.ComponentRepository;
import com.blaybus.backend.repository.ConversationRepository;
import com.blaybus.backend.repository.MessageRepository;
import com.blaybus.backend.repository.ReferenceRepository;
import com.blaybus.backend.repository.SceneInformationRepository;
import lombok.RequiredArgsConstructor;
@Service
@RequiredArgsConstructor
public class ConversationService {
private final ConversationRepository conversationRepository;
private final MessageRepository messageRepository;
private final ComponentRepository componentRepository;
private final ReferenceRepository referenceRepository;
private final SceneInformationRepository sceneInformationRepository;
private final OpenAiService openAiService;
private final PromptService promptService;
@Transactional(readOnly = true)
public ConversationResponse getConversation(User user, Long sceneId, Long cursor, int limit) {
Conversation conversation = conversationRepository.findByUserAndSceneId(user, sceneId)
.orElse(null);
if (conversation == null) {
return new ConversationResponse(List.of(), emptyPageInfo(limit));
}
Slice<Message> messageSlice;
if (cursor != null) {
messageSlice = messageRepository.findByConversationAndIdLessThanOrderByIdDesc(
conversation, cursor, PageRequest.of(0, limit + 1));
} else {
messageSlice = messageRepository.findByConversationOrderByIdDesc(
conversation, PageRequest.of(0, limit + 1));
}
List<Message> messages = messageSlice.getContent();
boolean hasNext = messages.size() > limit;
if (hasNext) {
messages = messages.subList(0, limit);
}
List<Long> messageIds = messages.stream().map(Message::getId).toList();
Map<Long, List<Reference>> referencesByMessageId = loadReferences(messageIds);
List<MessageResponse> messageResponses = messages.stream()
.map(msg -> MessageResponse.from(msg, buildComponentInfoMap(referencesByMessageId.get(msg.getId()))))
.toList();
List<MessageResponse> reversedMessages = new ArrayList<>(messageResponses);
Collections.reverse(reversedMessages);
String prevCursor = messages.isEmpty() ? null : String.valueOf(messages.get(0).getId());
String nextCursor = hasNext ? String.valueOf(messages.get(messages.size() - 1).getId()) : null;
PageInfo pageInfo = new PageInfo(
prevCursor,
nextCursor,
cursor != null,
hasNext,
limit);
return new ConversationResponse(reversedMessages, pageInfo);
}
@Transactional
public SendMessageResponse sendMessage(User user, Long sceneId, SendMessageRequest request) {
Conversation conversation = conversationRepository.findByUserAndSceneId(user, sceneId)
.orElseGet(() -> {
var scene = sceneInformationRepository.findById(sceneId)
.orElseThrow(() -> new BusinessException(CommonErrorCode.SCENE_NOT_FOUND));
return conversationRepository.save(
Conversation.builder()
.user(user)
.scene(scene)
.build());
});
List<Component> components = loadComponents(request.getComponentIds());
Map<String, ComponentInfo> componentInfoMap = components.stream()
.collect(Collectors.toMap(
c -> String.valueOf(c.getId()),
ComponentInfo::from));
Message userMessage = Message.builder()
.conversation(conversation)
.sender(Sender.USER)
.content(request.content())
.postedAt(java.time.LocalDateTime.now())
.build();
messageRepository.save(userMessage);
for (Component component : components) {
Reference reference = Reference.builder()
.message(userMessage)
.component(component)
.build();
referenceRepository.save(reference);
}
String systemPrompt = promptService.buildSystemPrompt(sceneId, user);
String userPrompt = promptService.buildUserPrompt(
conversation.getSummary(),
components,
request.content());
AssistantResponse aiResponse = openAiService.chat(systemPrompt, userPrompt);
Message assistantMessage = Message.builder()
.conversation(conversation)
.sender(Sender.ASSISTANT)
.content(aiResponse.answer())
.postedAt(java.time.LocalDateTime.now())
.build();
messageRepository.save(assistantMessage);
conversation.updateSummary(aiResponse.summary());
return SendMessageResponse.from(assistantMessage, componentInfoMap);
}
private List<Component> loadComponents(List<Long> componentIds) {
if (componentIds == null || componentIds.isEmpty()) {
return List.of();
}
List<Component> components = componentRepository.findByIdIn(componentIds);
if (components.size() != componentIds.size()) {
throw new BusinessException(CommonErrorCode.COMPONENT_NOT_FOUND);
}
return components;
}
private Map<Long, List<Reference>> loadReferences(List<Long> messageIds) {
if (messageIds.isEmpty()) {
return Map.of();
}
List<Reference> references = referenceRepository.findByMessageIdInWithComponent(messageIds);
return references.stream()
.collect(Collectors.groupingBy(ref -> ref.getMessage().getId()));
}
private Map<String, ComponentInfo> buildComponentInfoMap(List<Reference> references) {
if (references == null || references.isEmpty()) {
return Map.of();
}
Map<String, ComponentInfo> result = new HashMap<>();
for (Reference ref : references) {
Component component = ref.getComponent();
result.put(String.valueOf(component.getId()), ComponentInfo.from(component));
}
return result;
}
@Transactional(readOnly = true)
public ConversationSummaryResponse summarizeAllConversations(User user) {
List<Conversation> conversations = conversationRepository.findByUser(user);
if (conversations.isEmpty()) {
return new ConversationSummaryResponse("대화 내역이 없습니다.", 0, 0);
}
List<Message> allMessages = messageRepository.findByConversationInOrderByPostedAtAsc(conversations);
if (allMessages.isEmpty()) {
return new ConversationSummaryResponse("대화 내역이 없습니다.", conversations.size(), 0);
}
String conversationText = buildConversationText(allMessages);
String systemPrompt = """
당신은 대화 내역을 요약하는 AI입니다.
사용자와 AI 어시스턴트 간의 전체 대화 내역을 분석하여 핵심 내용을 종합적으로 요약해주세요.
## 규칙
1. 한국어로 요약합니다.
2. 주요 학습 주제, 질문한 내용, AI가 설명한 핵심 개념을 포함합니다.
3. 시간순으로 대화 흐름을 반영합니다.
4. 요약은 2~3문단으로 작성합니다.
""";
SummaryResponse summaryResponse = openAiService.summarize(systemPrompt, conversationText);
return new ConversationSummaryResponse(
summaryResponse.summary(),
conversations.size(),
allMessages.size());
}
private String buildConversationText(List<Message> messages) {
StringBuilder sb = new StringBuilder();
for (Message message : messages) {
String role = message.getSender() == Sender.USER ? "사용자" : "AI";
sb.append(String.format("[%s] %s: %s\n",
message.getPostedAt().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")),
role,
message.getContent()));
}
return sb.toString();
}
private PageInfo emptyPageInfo(int limit) {
return new PageInfo(null, null, false, false, limit);
}
}