Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions archive-api/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ dependencies {
implementation(project(":archive-common"))
implementation(project(":archive-domain"))
implementation(project(":archive-auth"))
implementation(project(":archive-chatbot"))

// Spring Boot Actuator
implementation("org.springframework.boot:spring-boot-starter-actuator")
Expand All @@ -22,6 +23,7 @@ dependencies {
testImplementation("com.h2database:h2")
testImplementation("org.mockito:mockito-core")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")

}

springBoot {
Expand Down
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)
}
}
4 changes: 4 additions & 0 deletions archive-api/src/main/resources/application.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,7 @@ logging:
org.springframework.web.bind: DEBUG
com.alpha.archive: DEBUG
root: INFO

openai:
api:
key: '채우세용' # 오픈 api 시크릿 키
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ import org.springframework.web.cors.CorsConfiguration
import org.springframework.web.cors.CorsConfigurationSource
import org.springframework.web.cors.UrlBasedCorsConfigurationSource
import java.lang.reflect.Method
import jakarta.servlet.DispatcherType
import org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer

@Configuration
@EnableWebSecurity
Expand All @@ -56,12 +58,17 @@ class SecurityConfig(
.csrf { it.disable() }
.cors { it.configurationSource(corsConfigurationSource()) }
.headers { it.frameOptions { fo -> fo.sameOrigin() } }
.applyDynamicUrlSecurity(applicationContext)
.authorizeHttpRequests {
it
.requestMatchers(HttpMethod.POST, "/api/auth/**").permitAll()
.requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()
.anyRequest().permitAll()
.authorizeHttpRequests { auth: AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizationManagerRequestMatcherRegistry ->

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

잘된다면 문제 없을 것 같음

// 비동기 해결 ASYNC 타입 요청을 맨 먼저 허용(chatbot 인증문제)
auth.dispatcherTypeMatchers(DispatcherType.ASYNC).permitAll()

auth.requestMatchers(HttpMethod.POST, "/api/auth/**").permitAll()
auth.requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()

applyDynamicUrlSecurity(applicationContext, auth)

// 여기 이렇게 수정하는게 좋다해서 일단 했는데 확인 부탁
auth.anyRequest().authenticated()
}
.sessionManagement { it.sessionCreationPolicy(SessionCreationPolicy.STATELESS) }
.addFilterBefore(JwtAuthenticationFilter(jwtService), BasicAuthenticationFilter::class.java)
Expand All @@ -87,74 +94,76 @@ class SecurityConfig(
return source
}

fun HttpSecurity.applyDynamicUrlSecurity(applicationContext: ApplicationContext): HttpSecurity {
fun applyDynamicUrlSecurity(
applicationContext: ApplicationContext,
auth: AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizationManagerRequestMatcherRegistry
) {
val controllers = applicationContext.getBeansWithAnnotation(Controller::class.java)

controllers.values.forEach { controller ->
val parentPath = controller.javaClass.getAnnotation(RequestMapping::class.java)?.value?.firstOrNull()

controller.javaClass.declaredMethods.forEach { method ->
handleMapping<ArchiveGetMapping>(method, HttpMethod.GET, parentPath)
handleMapping<ArchivePostMapping>(method, HttpMethod.POST, parentPath)
handleMapping<ArchivePatchMapping>(method, HttpMethod.PATCH, parentPath)
handleMapping<ArchivePutMapping>(method, HttpMethod.PUT, parentPath)
handleMapping<ArchiveDeleteMapping>(method, HttpMethod.DELETE, parentPath)
// 'auth' 객체를 하위 함수로 전달합니다.
handleMapping<ArchiveGetMapping>(method, HttpMethod.GET, parentPath, auth)
handleMapping<ArchivePostMapping>(method, HttpMethod.POST, parentPath, auth)
handleMapping<ArchivePatchMapping>(method, HttpMethod.PATCH, parentPath, auth)
handleMapping<ArchivePutMapping>(method, HttpMethod.PUT, parentPath, auth)
handleMapping<ArchiveDeleteMapping>(method, HttpMethod.DELETE, parentPath, auth)
}
}
return this
}

@Suppress("UNCHECKED_CAST")
private inline fun <reified T : Annotation> HttpSecurity.handleMapping(
private inline fun <reified T : Annotation> handleMapping(
method: Method,
httpMethod: HttpMethod,
parentPath: String?
parentPath: String?,
auth: AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizationManagerRequestMatcherRegistry
) {
method.getAnnotation(T::class.java)?.let { mapping ->
val paths = mapping.javaClass.getMethod("value").invoke(mapping) as Array<String>
val hasRole = mapping.javaClass.getMethod("hasRole").invoke(mapping) as Array<String>
val authenticated = mapping.javaClass.getMethod("authenticated").invoke(mapping) as Boolean

when {
hasRole.isNotEmpty() -> configureHasRole(httpMethod, parentPath, paths, hasRole)
authenticated -> configureAuthenticated(httpMethod, parentPath, paths)
hasRole.isNotEmpty() -> configureHasRole(httpMethod, parentPath, paths, hasRole, auth)
authenticated -> configureAuthenticated(httpMethod, parentPath, paths, auth)
}
}
}

private fun HttpSecurity.configureHasRole(
private fun configureHasRole(
httpMethod: HttpMethod,
parentPath: String?,
paths: Array<String>,
roles: Array<String>
roles: Array<String>,
auth: AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizationManagerRequestMatcherRegistry
) {
authorizeHttpRequests {
if (paths.isEmpty()) {
it.requestMatchers(httpMethod, parentPath).hasAnyRole(*roles)
}
paths.forEach { p ->
it.requestMatchers(httpMethod, formatPath(p, parentPath)).hasAnyRole(*roles)
}
if (paths.isEmpty()) {
auth.requestMatchers(httpMethod, parentPath).hasAnyRole(*roles)
}
paths.forEach { p ->
auth.requestMatchers(httpMethod, formatPath(p, parentPath)).hasAnyRole(*roles)
}
}

private fun HttpSecurity.configureAuthenticated(
private fun configureAuthenticated(
httpMethod: HttpMethod,
parentPath: String?,
paths: Array<String>
paths: Array<String>,
auth: AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizationManagerRequestMatcherRegistry
) {
authorizeHttpRequests {
if (paths.isEmpty()) {
it.requestMatchers(httpMethod, parentPath).authenticated()
}
paths.forEach { p ->
it.requestMatchers(httpMethod, formatPath(p, parentPath)).authenticated()
}
if (paths.isEmpty()) {
auth.requestMatchers(httpMethod, parentPath).authenticated()
}
paths.forEach { p ->
auth.requestMatchers(httpMethod, formatPath(p, parentPath)).authenticated()
}
}

private fun formatPath(path: String, parentPath: String?): String {
val formattedPath = if (!path.startsWith("/")) "/$path" else path
return if (parentPath == null || parentPath == "null") path else parentPath + formattedPath
}
}
}
35 changes: 35 additions & 0 deletions archive-chatbot/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import org.springframework.boot.gradle.tasks.bundling.BootJar

plugins {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
}

이렇게 해야 빌드가 될거야.

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)
}
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
}
"""
}
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
}
}
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
}
}
Loading