-
Notifications
You must be signed in to change notification settings - Fork 0
[FEAT] Chatbot openapi #8
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
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
49 changes: 49 additions & 0 deletions
49
archive-api/src/main/kotlin/com/alpha/archive/chatbot/ChatbotController.kt
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,49 @@ | ||
| package com.alpha.archive.chatbot | ||
|
|
||
| import com.alpha.archive.auth.security.service.ArchiveUserDetails | ||
| import com.alpha.archive.chatbot.dto.ChatbotMessageRequest | ||
| import com.alpha.archive.chatbot.dto.ChatbotMessageResponse | ||
| import com.alpha.archive.chatbot.service.ChatbotService | ||
| import com.alpha.archive.common.annotations.ArchivePostMapping | ||
| import com.alpha.archive.exception.ErrorTitle | ||
| import com.alpha.archive.exception.annotation.CustomFailResponseAnnotation | ||
| import com.alpha.archive.util.ResponseUtil | ||
| import io.swagger.v3.oas.annotations.Operation | ||
| import io.swagger.v3.oas.annotations.responses.ApiResponse as SwaggerApiResponse | ||
| import io.swagger.v3.oas.annotations.security.SecurityRequirement | ||
| import io.swagger.v3.oas.annotations.tags.Tag | ||
| import jakarta.validation.Valid | ||
| import org.springframework.http.ResponseEntity | ||
| import org.springframework.security.core.annotation.AuthenticationPrincipal | ||
| import org.springframework.web.bind.annotation.RequestBody | ||
| import org.springframework.web.bind.annotation.RequestMapping | ||
| import org.springframework.web.bind.annotation.RestController | ||
| import com.alpha.archive.common.dto.ApiResponse | ||
|
|
||
| @RestController | ||
| @RequestMapping("/api/chatbot") | ||
| @Tag(name = "챗봇 관련 API", description = "사용자 경험 기록을 돕는 챗봇 API 입니다.") | ||
| @SecurityRequirement(name = "bearerAuth") | ||
| class ChatbotController( | ||
| private val chatbotService: ChatbotService | ||
| ) { | ||
| @ArchivePostMapping("/message", authenticated = true) | ||
| @SwaggerApiResponse(responseCode = "200", description = "챗봇 메시지 처리 성공") | ||
| @Operation(summary = "챗봇과 대화하는 API", description = "사용자의 메시지를 받아 챗봇의 응답을 반환합니다. 대화를 통해 활동 기록을 완성합니다.") | ||
| @CustomFailResponseAnnotation(ErrorTitle.BadRequest) | ||
| @CustomFailResponseAnnotation(ErrorTitle.NotFoundUser) | ||
| suspend fun handleMessage( | ||
| @AuthenticationPrincipal userDetails: ArchiveUserDetails, | ||
| @RequestBody @Valid request: ChatbotMessageRequest | ||
| ): ResponseEntity<ApiResponse.Success<ChatbotMessageResponse>> { | ||
| // 인증된 사용자 정보와 메시지를 서비스에 전달. | ||
| val replyMessage = chatbotService.continueConversation(userDetails.getUserId(), request.message) | ||
|
|
||
| // 서비스의 응답을 DTO에 저장. | ||
| val response = ChatbotMessageResponse(reply = replyMessage) | ||
|
|
||
| // 기존 프로젝트의 | ||
| // 응답 형식에 맞춰 성공 응답 반환. | ||
| return ResponseUtil.success("메시지가 성공적으로 처리되었습니다.", response) | ||
| } | ||
| } |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| import org.springframework.boot.gradle.tasks.bundling.BootJar | ||
|
|
||
| plugins { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 이렇게 해야 빌드가 될거야. |
||
| kotlin("jvm") | ||
| } | ||
|
|
||
| version = "0.0.1-SNAPSHOT" | ||
|
|
||
| repositories { | ||
| mavenCentral() | ||
| } | ||
|
|
||
| dependencies { | ||
| api(project(":archive-domain")) | ||
| api("org.springframework.boot:spring-boot-starter-webflux") | ||
| implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor") | ||
| testImplementation(kotlin("test")) | ||
| implementation("org.springframework.boot:spring-boot-starter-data-redis") | ||
| } | ||
|
|
||
| tasks.named<BootJar>("bootJar") { | ||
| enabled = false | ||
| } | ||
|
|
||
| tasks.getByName("jar") { | ||
| enabled = true | ||
| } | ||
|
|
||
| tasks.test { | ||
| useJUnitPlatform() | ||
| } | ||
|
|
||
| kotlin { | ||
| jvmToolchain(17) | ||
| } | ||
76 changes: 76 additions & 0 deletions
76
archive-chatbot/src/main/kotlin/com/alpha/archive/chatbot/SystemPrompt.kt
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,76 @@ | ||
| package com.alpha.archive.chatbot | ||
|
|
||
| import com.alpha.archive.domain.event.enums.EventCategory | ||
|
|
||
| object SystemPrompt { | ||
| // EventCategory enum 값을 동적으로 가져와 프롬프트에 포함 | ||
| private val categories = EventCategory.entries.joinToString(", ") | ||
|
|
||
| val PROMPT: String = """ | ||
| 너는 사용자의 경험을 기록하고 정리해주는 매우 꼼꼼하고 친절한 챗봇 '알파'야. | ||
| 너의 임무는 사용자와의 대화를 통해 다음 JSON 객체를 '완벽하게' 채우는 거야. | ||
|
|
||
| { | ||
| "activityDate": "YYYY-MM-DDTHH:MM:SS", | ||
| "customTitle": "활동 제목", | ||
| "customCategory": "${categories} 중 하나", | ||
| "customLocation": "활동 장소", | ||
| "rating": "1-5 정수", | ||
| "memo": "메모 내용" | ||
| } | ||
|
|
||
| --- | ||
| **[매우 엄격한 대화 흐름(Flow)]** | ||
| 너는 반드시 다음 3단계를 순서대로 따라야 해. | ||
|
|
||
| **[1단계: 정보 수집 (응답: 텍스트)]** | ||
| 1. 사용자의 첫 메시지가 오면, **절대로** JSON을 반환하지 말고 **항상** 추가 질문으로 응답해야 해. | ||
| 2. 대화를 통해 위의 JSON 객체에 있는 모든 항목을 채우기 위해 노력해야 해. | ||
| 3. `activityDate`, `customTitle`, `customCategory` 3개는 **필수 항목**이야. | ||
| 4. `customLocation`, `rating`, `memo` 3개는 **선택 항목**이지만, 사용자가 "없어" 또는 "넘어가"라고 말하기 전까지 **최소 한 번은 꼭 물어봐야 해.** (예: "활동한 장소는 어디인가요?", "이번 경험에 1~5점 사이의 평점을 주시겠어요?") | ||
| 5. 이 단계에서 너의 모든 응답은 **JSON이 아닌 일반 텍스트 질문**이어야 해. | ||
|
|
||
| **[2단계: 정보 확인 (응답: 텍스트)]** | ||
| 1. 모든 필수 항목이 채워지고, 선택 항목에 대해서도 질문을 마쳤다고 판단되면, **절대로 JSON을 출력하면 안 돼.** | ||
| 2. 대신, 지금까지 수집한 모든 정보를 **요약 리스트 (일반 텍스트)**로 만들어서 사용자에게 보여줘야 해. | ||
| 3. 요약 리스트의 마지막에는 **"이 내용으로 기록해 드릴까요? 수정하고 싶은 부분이 있으신가요?"**라고 **반드시** 질문해야 해. | ||
|
|
||
| **[3단계: 저장 또는 수정]** | ||
| 1. [2단계]의 질문에 사용자가 **"응", "맞아", "저장해 줘"** 등 긍정적인 답변을 하면: | ||
| * 너의 다음 응답은 **오직 최종 JSON 객체 하나**여야 해. 다른 설명이나 텍스트 없이 JSON만 출력해야 해. | ||
| 2. [2단계]의 질문에 사용자가 **"아니", "수정할래", "제목 바꿔 줘"** 등 수정 요청을 하면: | ||
| * **절대로** JSON을 출력하지 말고, [1단계]로 돌아가서 수정할 내용을 다시 질문해야 해. (예: "알겠습니다. 제목을 무엇으로 수정할까요?") | ||
| --- | ||
|
|
||
| **[대화 예시]** | ||
| 사용자: 오늘 영화 봤어. | ||
| 너: (1단계) 오, 좋은 시간 보내셨네요! 어떤 영화 보셨어요? | ||
| 사용자: 범죄도시4. | ||
| 너: (1단계) 재미있으셨어요? 그 경험은 'CULTURE' 카테고리로 기록할까요? | ||
| 사용자: 응. | ||
| 너: (1단계) 알겠습니다. 오늘 날짜로 기록해 드릴게요. 혹시 영화 본 장소(customLocation)도 알려주실 수 있나요? | ||
| 사용자: 강남 CGV. | ||
| 너: (1단계) 좋습니다. 이번 경험에 평점(rating)을 주신다면 몇 점이신가요? | ||
| 사용자: 5점. | ||
| 너: (1단계) 마지막으로, 이 경험에 대해 남기고 싶은 메모(memo)가 있으신가요? | ||
| 사용자: 아니 없어. | ||
| 너: (2단계) 알겠습니다! 수집된 정보를 요약해 드릴게요. | ||
| * 날짜: 2025-10-21T18:30:00 (AI가 계산) | ||
| * 제목: 범죄도시4 관람 | ||
| * 카테고리: CULTURE | ||
| * 장소: 강남 CGV | ||
| * 평점: 5 | ||
| * 메모: (없음) | ||
| 이 내용으로 기록해 드릴까요? 수정하고 싶은 부분이 있으신가요? | ||
| 사용자: 응 저장해 줘. | ||
| 너: (3단계 - JSON만 출력) | ||
| { | ||
| "activityDate": "2025-10-21T18:30:00", | ||
| "customTitle": "범죄도시4 관람", | ||
| "customCategory": "CULTURE", | ||
| "customLocation": "강남 CGV", | ||
| "rating": 5, | ||
| "memo": null | ||
| } | ||
| """ | ||
| } |
36 changes: 36 additions & 0 deletions
36
archive-chatbot/src/main/kotlin/com/alpha/archive/chatbot/config/ChatbotRedisConfig.kt
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,36 @@ | ||
| package com.alpha.archive.chatbot.config | ||
|
|
||
| import org.springframework.context.annotation.Bean | ||
| import org.springframework.context.annotation.Configuration | ||
| import org.springframework.data.redis.connection.RedisConnectionFactory | ||
| import org.springframework.data.redis.core.RedisTemplate | ||
| import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer | ||
| import org.springframework.data.redis.serializer.StringRedisSerializer | ||
|
|
||
| @Configuration | ||
| class ChatbotRedisConfig { | ||
|
|
||
| /** | ||
| * 챗봇 모듈 전용 RedisTemplate Bean 생성. | ||
| * Value를 JSON으로 직렬화하여 List<Message> 같은 객체를 저장. | ||
| * * @param connectionFactory - 이 Bean은 'auth' 모듈의 RedisConfig가 | ||
| * 이미 만들어 둔 것을 Spring이 찾아서 자동으로 주입해 줍니다. | ||
| */ | ||
| @Bean | ||
| fun chatbotRedisTemplate(connectionFactory: RedisConnectionFactory): RedisTemplate<String, Any> { | ||
| val template = RedisTemplate<String, Any>() | ||
| template.connectionFactory = connectionFactory | ||
|
|
||
| // Key는 String을 사용 | ||
| template.keySerializer = StringRedisSerializer() | ||
|
|
||
| // Value는 객체를 JSON으로 변환하는 Serializer를 사용 | ||
| template.valueSerializer = GenericJackson2JsonRedisSerializer() | ||
|
|
||
| // Hash용 Serializer도 동일하게 설정 | ||
| template.hashKeySerializer = StringRedisSerializer() | ||
| template.hashValueSerializer = GenericJackson2JsonRedisSerializer() | ||
|
|
||
| return template | ||
| } | ||
| } |
22 changes: 22 additions & 0 deletions
22
archive-chatbot/src/main/kotlin/com/alpha/archive/chatbot/config/OpenAPIConfig.kt
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,22 @@ | ||
| package com.alpha.archive.chatbot.config | ||
|
|
||
| import org.springframework.beans.factory.annotation.Value | ||
| import org.springframework.context.annotation.Configuration | ||
|
|
||
| @Configuration | ||
| class OpenAPIConfig { | ||
|
|
||
| @Value("\${openai.api.key}") | ||
| lateinit var apiKey: String | ||
|
|
||
| companion object { | ||
| const val AUTHORIZATION = "Authorization" | ||
| const val BEARER = "Bearer" | ||
| const val MODEL = "gpt-4o" | ||
| const val MEDIA_TYPE = "application/json; charset=UTF-8" | ||
| const val URL = "https://api.openai.com/v1/chat/completions" | ||
| const val MAX_TOKENS = 300 | ||
| const val TEMPERATURE = 0.7 | ||
| const val TOP_P = 1.0 | ||
| } | ||
| } |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
잘된다면 문제 없을 것 같음