From 26d895801329ba7ac77c133dfc2793c07f9ee1cd Mon Sep 17 00:00:00 2001 From: exijn Date: Mon, 16 Nov 2026 17:37:20 +0900 Subject: [PATCH] =?UTF-8?q?feat(ai):=20=EC=B2=B4=ED=97=98=20=EA=B3=B5?= =?UTF-8?q?=EA=B0=84=EC=97=90=20=EB=A7=9E=EC=B6=B0=20AI=20=EC=B4=88?= =?UTF-8?q?=EC=95=88=20=EC=9D=B4=EB=8F=99=20=EA=B1=B0=EB=A6=AC=EB=A5=BC=20?= =?UTF-8?q?=EB=B3=B4=EC=A0=95=ED=95=9C=EB=8B=A4=20(#163)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 공간이 기본(6×6)과 다를 때만, 거리를 말하지 않은 문장은 공간의 기본 이동 거리로, 말한 문장은 1회 최대 이동을 넘는 값만 줄인다. 바꿨으면 설명에 이유를 보인다. 형식 검증 상한은 하드 3 m 로 두고 공간별 상한은 후처리에서 맞춘다. Co-Authored-By: Claude Opus 5.5 --- .../ai/application/AiAssistantService.kt | 6 +- .../ai/application/AiDraftArenaAdjuster.kt | 82 +++++++++++++++++++ .../ai/application/AiDraftStepValidator.kt | 11 ++- .../application/AiDraftArenaAdjusterTest.kt | 59 +++++++++++++ 4 files changed, 151 insertions(+), 7 deletions(-) create mode 100644 src/main/kotlin/team/inreok/poppyserver/domain/ai/application/AiDraftArenaAdjuster.kt create mode 100644 src/test/kotlin/team/inreok/poppyserver/domain/ai/application/AiDraftArenaAdjusterTest.kt diff --git a/src/main/kotlin/team/inreok/poppyserver/domain/ai/application/AiAssistantService.kt b/src/main/kotlin/team/inreok/poppyserver/domain/ai/application/AiAssistantService.kt index 35ba187..33d13be 100644 --- a/src/main/kotlin/team/inreok/poppyserver/domain/ai/application/AiAssistantService.kt +++ b/src/main/kotlin/team/inreok/poppyserver/domain/ai/application/AiAssistantService.kt @@ -10,6 +10,7 @@ class AiAssistantService( private val inferenceClient: AiInferenceClient, private val stepValidator: AiDraftStepValidator, private val textPolicy: AiTextPolicy, + private val arenaAdjuster: AiDraftArenaAdjuster = AiDraftArenaAdjuster(), ) { fun draftProgram(rawUtterance: String): AiProgramDraftResult { val utterance = textPolicy.normalize(rawUtterance) @@ -26,7 +27,10 @@ class AiAssistantService( log.warn("AI draft rejected by contract validation: {}", exception.message) throw ApplicationException(ErrorCode.AI_UNAVAILABLE) } - return AiProgramDraftResult(steps = steps, explanation = safeExplanation(draft.explanation)) + val adjusted = arenaAdjuster.adjust(utterance, steps) + // 거리를 공간에 맞게 바꿨으면 모델 설명(바꾸기 전 거리)이 틀리므로 바꾼 이유로 대신한다. + val explanation = adjusted.note ?: safeExplanation(draft.explanation) + return AiProgramDraftResult(steps = adjusted.steps, explanation = explanation) } fun hint(command: AiHintCommand): String { diff --git a/src/main/kotlin/team/inreok/poppyserver/domain/ai/application/AiDraftArenaAdjuster.kt b/src/main/kotlin/team/inreok/poppyserver/domain/ai/application/AiDraftArenaAdjuster.kt new file mode 100644 index 0000000..590d7fe --- /dev/null +++ b/src/main/kotlin/team/inreok/poppyserver/domain/ai/application/AiDraftArenaAdjuster.kt @@ -0,0 +1,82 @@ +package team.inreok.poppyserver.domain.ai.application + +import org.springframework.stereotype.Component +import team.inreok.poppyserver.domain.arena.application.ArenaSettingsProvider +import team.inreok.poppyserver.domain.arena.application.DefaultArenaSettingsProvider +import team.inreok.poppyserver.domain.arena.model.ArenaPresets +import team.inreok.poppyserver.domain.arena.model.ArenaSettings +import kotlin.math.min +import kotlin.math.roundToLong + +/** + * AI 초안의 이동 거리를 현재 체험 공간에 맞춘다(재학습 없이 후처리). + * + * 모델은 6×6 매트 데이터로 학습돼, 거리를 말하지 않으면 1~2 m 를 만든다. 공간이 기본(6×6)과 다를 때만 + * - 거리를 말하지 않은 문장: 모든 이동을 공간의 기본 이동 거리(3×3 → 0.5 m)로 바꾼다 + * - 거리를 말한 문장: 공간의 1회 최대 이동(3×3 → 1.2 m)을 넘는 값만 줄인다 + * 6×6(기본)에서는 아무것도 바꾸지 않는다 — 지금까지의 동작과 같다. + */ +@Component +class AiDraftArenaAdjuster( + private val arenaSettingsProvider: ArenaSettingsProvider = DefaultArenaSettingsProvider, +) { + fun adjust(utterance: String, steps: List>): AdjustedDraft { + val arena = arenaSettingsProvider.current() + if (sameGeometry(arena, ArenaPresets.DEFAULT)) return AdjustedDraft(steps, note = null) + + val explicit = EXPLICIT_DISTANCE.containsMatchIn(utterance) + var defaulted = false + var clamped = false + fun adjustAll(list: List>): List> = list.map { step -> + when (step["kind"]) { + "moveForward", "move" -> { + val current = (step["distanceM"] as Number).toDouble() + val next = if (explicit) { + min(current, arena.maxMovePerCommandM) + } else { + arena.defaultMoveDistanceM + } + if (next != current) { + if (explicit) clamped = true else defaulted = true + } + step + ("distanceM" to tenths(next)) + } + "repeat" -> { + @Suppress("UNCHECKED_CAST") + val body = step["body"] as List> + step + ("body" to adjustAll(body)) + } + else -> step + } + } + val adjusted = adjustAll(steps) + val note = when { + clamped -> "이 공간에서는 한 번에 ${meters(arena.maxMovePerCommandM)}m 까지 갈 수 있어서 줄였어요." + defaulted -> "거리를 말하지 않아서 이 공간에 맞게 ${meters(arena.defaultMoveDistanceM)}m 씩 가도록 만들었어요." + else -> null + } + return AdjustedDraft(adjusted, note) + } + + private fun sameGeometry(a: ArenaSettings, b: ArenaSettings): Boolean = + a.widthM == b.widthM && a.depthM == b.depthM && a.marginM == b.marginM && + a.startXM == b.startXM && a.startYM == b.startYM && a.startHeading == b.startHeading + + /** 검증기와 같은 숫자 모양: 정수면 Long, 아니면 0.1 단위 Double. */ + private fun tenths(value: Double): Number { + val t = (value * 10).roundToLong() + return if (t % 10 == 0L) t / 10 else t / 10.0 + } + + private fun meters(value: Double): String = tenths(value).toString() + + private companion object { + /** "1미터", "1.5 m", "50cm", "반 미터", "두 미터" 처럼 거리를 직접 말했는지. */ + val EXPLICIT_DISTANCE = Regex( + """(\d+(\.\d+)?|반|한|두|세|네|다섯|일|이|삼|사|오)\s*(미터|m(?![a-z])|센티|센치|cm)""", + RegexOption.IGNORE_CASE, + ) + } +} + +data class AdjustedDraft(val steps: List>, val note: String?) diff --git a/src/main/kotlin/team/inreok/poppyserver/domain/ai/application/AiDraftStepValidator.kt b/src/main/kotlin/team/inreok/poppyserver/domain/ai/application/AiDraftStepValidator.kt index fd892ce..fcc3ade 100644 --- a/src/main/kotlin/team/inreok/poppyserver/domain/ai/application/AiDraftStepValidator.kt +++ b/src/main/kotlin/team/inreok/poppyserver/domain/ai/application/AiDraftStepValidator.kt @@ -1,16 +1,12 @@ package team.inreok.poppyserver.domain.ai.application import org.springframework.stereotype.Component -import team.inreok.poppyserver.domain.arena.application.ArenaSettingsProvider -import team.inreok.poppyserver.domain.arena.application.DefaultArenaSettingsProvider import tools.jackson.databind.JsonNode import kotlin.math.abs import kotlin.math.roundToLong @Component -class AiDraftStepValidator( - private val arenaSettingsProvider: ArenaSettingsProvider = DefaultArenaSettingsProvider, -) { +class AiDraftStepValidator { fun validate(steps: JsonNode?): List> { if (steps == null || !steps.isArray || steps.isEmpty) { throw InvalidAiDraftException("steps must be a non-empty array") @@ -27,7 +23,7 @@ class AiDraftStepValidator( val kind = node.get("kind")?.takeIf { it.isString }?.asString() ?: throw InvalidAiDraftException("kind is required") return when (kind) { - "moveForward", "move" -> mapOf("kind" to kind, "distanceM" to decimal(node.get("distanceM"), MIN_DISTANCE, arenaSettingsProvider.current().maxMovePerCommandM)) + "moveForward", "move" -> mapOf("kind" to kind, "distanceM" to decimal(node.get("distanceM"), MIN_DISTANCE, MAX_DISTANCE)) "rotateLeft", "rotateRight" -> mapOf("kind" to kind, "degrees" to integer(node.get("degrees"), 1, 360)) "wait" -> mapOf("kind" to kind, "seconds" to integer(node.get("seconds"), 1, 10)) in SIMPLE_KINDS -> mapOf("kind" to kind) @@ -73,6 +69,9 @@ class AiDraftStepValidator( private companion object { const val MAX_BLOCKS = 12 const val MIN_DISTANCE = 0.1 + + // 모델 출력 형식 검증은 하드 상한(3 m)으로 한다. 공간별 1회 최대 이동은 AiDraftArenaAdjuster 가 맞춘다. + const val MAX_DISTANCE = 3.0 const val EPSILON = 1e-6 val SIMPLE_KINDS = setOf("stop", "standUp", "greet", "heart", "dance") } diff --git a/src/test/kotlin/team/inreok/poppyserver/domain/ai/application/AiDraftArenaAdjusterTest.kt b/src/test/kotlin/team/inreok/poppyserver/domain/ai/application/AiDraftArenaAdjusterTest.kt new file mode 100644 index 0000000..1a930f1 --- /dev/null +++ b/src/test/kotlin/team/inreok/poppyserver/domain/ai/application/AiDraftArenaAdjusterTest.kt @@ -0,0 +1,59 @@ +package team.inreok.poppyserver.domain.ai.application + +import org.junit.jupiter.api.Test +import team.inreok.poppyserver.domain.arena.application.ArenaSettingsProvider +import team.inreok.poppyserver.domain.arena.model.ArenaPresets +import kotlin.test.assertEquals +import kotlin.test.assertNull + +class AiDraftArenaAdjusterTest { + private val booth = AiDraftArenaAdjuster(ArenaSettingsProvider { ArenaPresets.ALL.getValue(ArenaPresets.BOOTH_3X3) }) + private val expo = AiDraftArenaAdjuster() + + private fun fwd(m: Number) = mapOf("kind" to "moveForward", "distanceM" to m) + private fun back(m: Number) = mapOf("kind" to "move", "distanceM" to m) + private val left = mapOf("kind" to "rotateLeft", "degrees" to 90L) + private fun repeat(count: Long, vararg body: Map) = + mapOf("kind" to "repeat", "count" to count, "body" to body.toList()) + + @Test + fun `6x6 기본 공간에서는 아무것도 바꾸지 않는다`() { + val steps = listOf(fwd(2L), repeat(4, fwd(1L), left)) + val result = expo.adjust("앞으로 가고 네모 모양으로 걸어", steps) + assertEquals(steps, result.steps) + assertNull(result.note) + } + + @Test + fun `3x3 에서 거리를 말하지 않으면 모든 이동이 0_5m 가 된다 - 네모는 0_5m x4`() { + val result = booth.adjust("네모 모양으로 걸어", listOf(repeat(4, fwd(1L), left))) + assertEquals(listOf(repeat(4, fwd(0.5), left)), result.steps) + assertEquals("거리를 말하지 않아서 이 공간에 맞게 0.5m 씩 가도록 만들었어요.", result.note) + + assertEquals(listOf(fwd(0.5)), booth.adjust("앞으로 가", listOf(fwd(2L))).steps) + assertEquals(listOf(back(0.5)), booth.adjust("뒤로 가", listOf(back(1L))).steps) + } + + @Test + fun `3x3 에서 거리를 말했으면 1_2m 를 넘는 값만 줄인다`() { + val kept = booth.adjust("앞으로 1미터 가", listOf(fwd(1L))) + assertEquals(listOf(fwd(1L)), kept.steps) + assertNull(kept.note) + + val clamped = booth.adjust("앞으로 2미터 가", listOf(fwd(2L))) + assertEquals(listOf(fwd(1.2)), clamped.steps) + assertEquals("이 공간에서는 한 번에 1.2m 까지 갈 수 있어서 줄였어요.", clamped.note) + + assertEquals(listOf(fwd(0.5)), booth.adjust("앞으로 50cm 가", listOf(fwd(0.5))).steps) + assertEquals(listOf(fwd(0.5)), booth.adjust("반 미터 앞으로", listOf(fwd(0.5))).steps) + assertEquals(listOf(fwd(1.2)), booth.adjust("앞으로 3 m 가", listOf(fwd(3L))).steps) + } + + @Test + fun `이동이 없는 초안은 그대로다`() { + val steps = listOf(mapOf("kind" to "greet"), left) + val result = booth.adjust("인사하고 왼쪽으로 돌아", steps) + assertEquals(steps, result.steps) + assertNull(result.note) + } +}