-
Notifications
You must be signed in to change notification settings - Fork 0
feat: AI 가정통신문 전체 분석 응답 저장 연동 #64
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
3 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
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,26 @@ | ||
| # 가정통신문 AI 전체 분석 응답 저장 연동 | ||
|
|
||
| 이 문서는 BE가 AI 서버의 가정통신문 전체 분석 응답을 저장 모델에 반영하는 구현 결정을 정리한다. 상세 API 명세는 노션을 기준으로 관리한다. | ||
|
|
||
| ## 결정 사항 | ||
|
|
||
| - BE는 가정통신문 파이프라인의 AI 분석 단계에서 `POST /ai/newsletters/analyze`를 호출한다. | ||
| - AI 서버 응답의 top-level `title`, `summary`를 `newsletter.title`, `newsletter.summary`에 저장한다. | ||
| - AI 서버 응답의 `items`는 기존 checklist 저장 흐름에 연결한다. | ||
| - `dateCandidates` 요청 형식과 `items` 응답 형식은 기존 `extract-items` 계약을 유지한다. | ||
| - `meta`는 운영 보조 정보로 받고, 현재 BE 저장 모델에는 직접 저장하지 않는다. | ||
| - AI 서버 호출 실패 정책은 `docs/newsletter-ai-failure-policy.md`를 따른다. | ||
|
|
||
| ## 저장 정책 | ||
|
|
||
| - `title`: AI 응답 제목을 우선 저장한다. 빈 값이면 기존 BE fallback 제목을 사용한다. | ||
| - `summary`: AI 응답 요약을 우선 저장한다. 빈 값이면 기존 BE fallback 요약을 사용한다. | ||
| - `items`: `title`이 비어 있지 않은 항목만 checklist로 저장한다. | ||
| - `datetime`: TODO 저장 시 `targetDate`, `targetDateLabel` 생성에 사용한다. 파싱 실패 시 날짜 없이 저장한다. | ||
| - `dateStatus`: 현재 저장 모델에는 별도 컬럼이 없으므로 직접 저장하지 않는다. 날짜 확정 여부가 필요한 후속 정책은 calendar preview 저장 구조와 함께 별도 이슈에서 다룬다. | ||
|
|
||
| ## 호환 정책 | ||
|
|
||
| - AI 서버의 `extract-items` baseline API는 유지하지만, BE 파이프라인은 `analyze`를 우선 사용한다. | ||
| - AI 서버가 `items`를 빈 배열로 반환해도 `title`, `summary`는 저장할 수 있다. | ||
| - AI 서버 장애 시에는 OCR/번역/dateCandidates 스냅샷을 보존하고 newsletter 상태를 `FAILED`로 둔다. |
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
161 changes: 161 additions & 0 deletions
161
src/test/java/com/gachi/be/domain/newsletter/pipeline/AiNewsletterClientTest.java
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,161 @@ | ||
| package com.gachi.be.domain.newsletter.pipeline; | ||
|
|
||
| import static org.assertj.core.api.Assertions.assertThat; | ||
| import static org.assertj.core.api.Assertions.assertThatThrownBy; | ||
|
|
||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import com.gachi.be.domain.newsletter.pipeline.AiNewsletterClient.AnalysisResponse; | ||
| import com.gachi.be.global.code.ErrorCode; | ||
| import com.gachi.be.global.config.external.AiServerProperties; | ||
| import com.gachi.be.global.exception.ExternalApiException; | ||
| import com.sun.net.httpserver.HttpServer; | ||
| import java.io.IOException; | ||
| import java.net.InetSocketAddress; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.util.List; | ||
| import java.util.concurrent.ExecutorService; | ||
| import java.util.concurrent.Executors; | ||
| import java.util.concurrent.atomic.AtomicReference; | ||
| import org.junit.jupiter.api.AfterEach; | ||
| import org.junit.jupiter.api.Test; | ||
|
|
||
| class AiNewsletterClientTest { | ||
|
|
||
| private HttpServer server; | ||
| private ExecutorService executor; | ||
|
|
||
| @AfterEach | ||
| void tearDown() { | ||
| if (server != null) { | ||
| server.stop(0); | ||
| } | ||
| if (executor != null) { | ||
| executor.shutdownNow(); | ||
| } | ||
| } | ||
|
|
||
| @Test | ||
| void analyzeCallsAnalyzeEndpointAndParsesTitleSummaryItems() throws IOException { | ||
| AtomicReference<String> requestPath = new AtomicReference<>(); | ||
| AtomicReference<String> requestBody = new AtomicReference<>(); | ||
| startServer(); | ||
| server.createContext( | ||
| "/ai/newsletters/analyze", | ||
| exchange -> { | ||
| requestPath.set(exchange.getRequestURI().getPath()); | ||
| requestBody.set( | ||
| new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8)); | ||
|
|
||
| byte[] response = | ||
| """ | ||
| { | ||
| "title": "AI 제목", | ||
| "summary": "AI 요약", | ||
| "items": [ | ||
| { | ||
| "type": "checklist", | ||
| "title": "동의서 제출", | ||
| "selectedDateCandidate": null, | ||
| "datetime": "2026-05-25", | ||
| "timezone": "Asia/Seoul", | ||
| "evidenceText": "5월 25일까지 동의서를 제출해 주세요.", | ||
| "dateStatus": "confirmed", | ||
| "confidence": 0.9, | ||
| "needsUserConfirmation": false, | ||
| "confirmationQuestion": null | ||
| } | ||
| ], | ||
| "meta": {"mode": "test"} | ||
| } | ||
| """ | ||
| .getBytes(StandardCharsets.UTF_8); | ||
| sendResponse(exchange, 200, response); | ||
| }); | ||
|
|
||
| AiNewsletterClient client = newClient(3); | ||
|
|
||
| AnalysisResponse response = client.analyze("원문", "번역문", "KO", List.of()); | ||
|
|
||
| assertThat(requestPath.get()).isEqualTo("/ai/newsletters/analyze"); | ||
| assertThat(requestBody.get()).contains("\"originalText\":\"원문\""); | ||
| assertThat(response.title()).isEqualTo("AI 제목"); | ||
| assertThat(response.summary()).isEqualTo("AI 요약"); | ||
| assertThat(response.items()).hasSize(1); | ||
| assertThat(response.items().get(0).title()).isEqualTo("동의서 제출"); | ||
| } | ||
|
|
||
| @Test | ||
| void analyzeThrowsExternalApiExceptionWhenAiServerReturnsError() throws IOException { | ||
| startServer(); | ||
| server.createContext( | ||
| "/ai/newsletters/analyze", | ||
| exchange -> sendResponse(exchange, 500, "{\"detail\":\"server error\"}".getBytes())); | ||
|
|
||
| AiNewsletterClient client = newClient(3); | ||
|
|
||
| assertThatThrownBy(() -> client.analyze("원문", null, "KO", List.of())) | ||
| .isInstanceOf(ExternalApiException.class) | ||
| .extracting("errorCode") | ||
| .isEqualTo(ErrorCode.EXTERNAL_API_ERROR); | ||
| } | ||
|
|
||
| @Test | ||
| void analyzeThrowsExternalApiExceptionWhenAiServerResponseTimesOut() throws IOException { | ||
| startServer(); | ||
| server.createContext( | ||
| "/ai/newsletters/analyze", | ||
| exchange -> { | ||
| try { | ||
| Thread.sleep(1500); | ||
| sendResponse(exchange, 200, "{}".getBytes(StandardCharsets.UTF_8)); | ||
| } catch (InterruptedException e) { | ||
| Thread.currentThread().interrupt(); | ||
| } | ||
| }); | ||
|
|
||
| AiNewsletterClient client = newClient(1); | ||
|
|
||
| assertThatThrownBy(() -> client.analyze("원문", null, "KO", List.of())) | ||
| .isInstanceOf(ExternalApiException.class) | ||
| .extracting("errorCode") | ||
| .isEqualTo(ErrorCode.EXTERNAL_API_ERROR); | ||
| } | ||
|
|
||
| @Test | ||
| void analyzeThrowsExternalApiExceptionWhenAiServerReturnsMalformedJson() throws IOException { | ||
| startServer(); | ||
| server.createContext( | ||
| "/ai/newsletters/analyze", | ||
| exchange -> sendResponse(exchange, 200, "{".getBytes(StandardCharsets.UTF_8))); | ||
|
|
||
| AiNewsletterClient client = newClient(3); | ||
|
|
||
| assertThatThrownBy(() -> client.analyze("원문", null, "KO", List.of())) | ||
| .isInstanceOf(ExternalApiException.class) | ||
| .extracting("errorCode") | ||
| .isEqualTo(ErrorCode.EXTERNAL_API_ERROR); | ||
| } | ||
|
|
||
| private void startServer() throws IOException { | ||
| server = HttpServer.create(new InetSocketAddress("localhost", 0), 0); | ||
| executor = Executors.newSingleThreadExecutor(); | ||
| server.setExecutor(executor); | ||
| server.start(); | ||
| } | ||
|
|
||
| private AiNewsletterClient newClient(int readTimeoutSeconds) { | ||
| AiServerProperties properties = new AiServerProperties(); | ||
| properties.setBaseUrl("http://localhost:" + server.getAddress().getPort()); | ||
| properties.setConnectTimeoutSeconds(3); | ||
| properties.setReadTimeoutSeconds(readTimeoutSeconds); | ||
| return new AiNewsletterClient(properties, new ObjectMapper().findAndRegisterModules()); | ||
| } | ||
|
|
||
| private void sendResponse(com.sun.net.httpserver.HttpExchange exchange, int status, byte[] body) | ||
| throws IOException { | ||
| exchange.getResponseHeaders().add("Content-Type", "application/json"); | ||
| exchange.sendResponseHeaders(status, body.length); | ||
| exchange.getResponseBody().write(body); | ||
| exchange.close(); | ||
| } | ||
| } | ||
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.
Uh oh!
There was an error while loading. Please reload this page.