Skip to content

Commit

Permalink
refactor: 예외처리 및 코드 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
osoohynn committed Nov 28, 2024
1 parent 133d91a commit 0db0d4b
Showing 1 changed file with 18 additions and 13 deletions.
31 changes: 18 additions & 13 deletions src/main/java/com/project/oof/gpt/service/ChatGPTServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
@RequiredArgsConstructor
public class ChatGPTServiceImpl implements ChatGPTService {


private final ChatGPTConfig chatGPTConfig;
private final ChatHistoryService chatHistoryService;

Expand All @@ -30,6 +29,8 @@ public class ChatGPTServiceImpl implements ChatGPTService {
@Override
public String prompt(String userMessage) {
log.debug("[+] 신규 프롬프트를 수행합니다.");
System.out.println(chatHistoryService.getChatHistory());

chatHistoryService.addMessage("user", userMessage);

List<Map<String, String>> messages = chatHistoryService.getChatHistory();
Expand All @@ -49,18 +50,22 @@ public String prompt(String userMessage) {
.exchange(promptUrl, HttpMethod.POST, requestEntity, Map.class);

// OpenAI API의 응답을 처리
Map<String, Object> responseBody = response.getBody();

List<Map<String, Object>> choices = (List<Map<String, Object>>) responseBody.get("choices");

Map<String, Object> firstChoice = choices.get(0);
Map<String, Object> message = (Map<String, Object>) firstChoice.get("message");

String assistantMessage = message.get("content").toString();

System.out.println("Assistant response: " + assistantMessage);
chatHistoryService.addMessage("assistant", assistantMessage);
return assistantMessage;
try {
Map<String, Object> responseBody = response.getBody();
String assistantMessage = ((List<Map<String, Object>>) responseBody.get("choices"))
.stream()
.findFirst()
.map(choice -> (Map<String, Object>) choice.get("message"))
.map(message -> (String) message.get("content"))
.orElse("No response from assistant.");

System.out.println("Assistant response: " + assistantMessage);
chatHistoryService.addMessage("assistant", assistantMessage);
return assistantMessage;
} catch (Exception e) {
System.err.println("Error processing assistant response: " + e.getMessage());
return "An error occurred while processing the response.";
}
}

}

0 comments on commit 0db0d4b

Please sign in to comment.