Skip to content

[PIPELINE] 각 부분 예외 처리 강화 및 가독성을 고려한 클래스, 메서드 이름 리팩터링#19

Merged
s0ooo0k merged 4 commits into
PETTY-HUB:mainfrom
Juyoung8563:main
Apr 22, 2025
Merged

[PIPELINE] 각 부분 예외 처리 강화 및 가독성을 고려한 클래스, 메서드 이름 리팩터링#19
s0ooo0k merged 4 commits into
PETTY-HUB:mainfrom
Juyoung8563:main

Conversation

@Juyoung8563
Copy link
Copy Markdown
Contributor

📜 PR 내용 요약

  • 전체적으로 상황의 맞는 예외 처리와 가독성을 고려하여 리팩터링 하였습니다

⚒️ 작업 및 변경 내용

  • PipelineController의 사용하지 않는 import문을 제거하였습니다.
  • 전체적으로 클래스, 메서드 이름을 목적이 명확하고 이해하기 쉽게 변경하였습니다.
  • Together API의 프롬프트를 담당하는 클래스를 Component로 변경하고 인터페이스를 삭제하였습니다.
  • API 호출과 필수 정보, 사용자 위치 등에 그에 맞는 예외 처리를 작성하였습니다.

📚 기타 참고 사항

  • 본 PR에 build.gradle 파일의 변경 사항은 없습니다.
  • 본 PR에 추가적인 기능의 구현은 없습니다.
  • 여러 차례 테스트를 진행하며 최종 결과의 JSON이 흐트러지는 이슈는 없었습니다.
  • 아래와 같이 Together API의 model을 application-secret.yml 파일에 위임하였습니다.

스크린샷 2025-04-23 002054

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 22, 2025

Summary by CodeRabbit

  • 신규 기능

    • 펫 정보 추출 및 프롬프트 생성을 위한 새로운 프롬프트 빌더가 도입되었습니다.
    • Together API의 모델을 설정에서 변경할 수 있도록 개선되었습니다.
  • 버그 수정

    • 프롬프트 생성 시 필수 입력값이 누락되었을 때 명확한 오류 메시지가 제공됩니다.
  • 기타

    • 내부 서비스 구조가 간소화되었습니다.

Walkthrough

이 변경사항은 기존의 PromptAssemblyService 및 그 구현체를 삭제하고, 새로운 TogetherPromptBuilder 클래스를 도입하여 프롬프트 생성 로직을 통합합니다. PipelineController는 이제 PromptAssemblyService 대신 TogetherPromptBuilder를 주입받아 사용하며, 관련 서비스의 import 및 필드 선언도 변경되었습니다. 또한, PromptGeneratorServiceImpl에는 입력값 검증 로직이 추가되었고, TogetherServiceImpl에서는 모델명을 외부 설정값으로 주입받도록 수정되었습니다.

Changes

파일/경로 요약 변경 요약
src/main/java/io/github/petty/pipeline/controller/PipelineController.java PromptAssemblyService 의존성 삭제, TogetherPromptBuilder로 대체, 관련 메서드 호출 변경
src/main/java/io/github/petty/pipeline/service/PromptAssemblyService.java,
src/main/java/io/github/petty/pipeline/service/PromptAssemblyServiceImpl.java
PromptAssemblyService 인터페이스 및 구현체 완전 삭제
src/main/java/io/github/petty/pipeline/service/PromptGeneratorServiceImpl.java generatePrompt 메서드에 입력값 검증(빈 값일 때 예외 발생) 추가
src/main/java/io/github/petty/pipeline/service/TogetherServiceImpl.java 모델명을 외부 설정값(@Value("${together.api.model}"))으로 주입, 예외 메시지 개선
src/main/java/io/github/petty/pipeline/support/TogetherPromptBuilder.java TogetherPromptBuilder 신규 클래스 추가, 프롬프트 빌드 및 예외 처리 로직 통합

Sequence Diagram(s)

sequenceDiagram
    participant Controller as PipelineController
    participant Builder as TogetherPromptBuilder
    participant Together as TogetherService
    participant Generator as PromptGeneratorService

    Controller->>Builder: buildPrompt(visionReport, location)
    Builder->>Together: answer("Extract pet info from visionReport ...")
    Together-->>Builder: extractedPetInfoJson
    Builder->>Generator: generatePrompt(extractedPetInfoJson, location)
    Generator-->>Builder: finalPrompt
    Builder-->>Controller: finalPrompt
Loading

Possibly related PRs

Poem

🐇
서비스 바꿔, 빌더로 hop!
프롬프트 조립, 한 번에 pop!
오래된 서비스는 이제 안녕,
새 빌더와 함께라면 걱정 끝!
토끼는 코를 실룩이며,
코드의 숲을 경쾌하게 달려가네!

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@Juyoung8563
Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 22, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/main/java/io/github/petty/pipeline/support/TogetherPromptBuilder.java (2)

20-24: 프롬프트 구성 문자열 개선 제안

프롬프트 구성 문자열이 다소 길고 여러 부분이 연결되어 있습니다. 이 부분을 상수로 추출하거나 템플릿 형태로 관리하면 가독성과 유지보수성이 향상될 것입니다.

+    private static final String PET_INFO_EXTRACTION_PROMPT_TEMPLATE = 
+            "%s -> 이 문장에서 반려동물의 이름(name), 종(species), 무게(weight), " +
+            "맹수 여부(is_danger(only true or false))를 JSON 형식으로 작성 + " +
+            "만약 반려동물의 종과 무게를 보았을 때, 입마개가 필요할 것 같다면 맹수 여부를 'true'로 작성 + " +
+            "무게는 kg 단위를 반드시 포함" + "no markdown, only JSON" + "최종 결과에 {}는 제거";
 
     public String buildPrompt(String visionReport, String location) throws Exception {
         try {
             if (visionReport.isEmpty()) {
                 throw new IllegalStateException("Vision API 에서 필수 정보를 받아오지 못했습니다.");
             }
-            String extractedPetInfoJson = togetherService.answer(
-                    visionReport + " -> 이 문장에서 반려동물의 이름(name), 종(species), 무게(weight), 맹수 여부(is_danger(only true or false))를 JSON 형식으로 작성 + " +
-                            "만약 반려동물의 종과 무게를 보았을 때, 입마개가 필요할 것 같다면 맹수 여부를 'true'로 작성 + " +
-                            "무게는 kg 단위를 반드시 포함" + "no markdown, only JSON" + "최종 결과에 {}는 제거"
-            );
+            String extractedPetInfoJson = togetherService.answer(
+                    String.format(PET_INFO_EXTRACTION_PROMPT_TEMPLATE, visionReport)
+            );

27-29: 예외 처리 개선 제안

현재 모든 RuntimeException을 포착하고 일반적인 메시지로 다시 던지고 있습니다. 원래 예외의 정보를 로깅하거나 예외 체인에 포함시키면 디버깅이 더 용이해질 것입니다.

     } catch (RuntimeException e) {
-            throw new RuntimeException("프롬프트 빌드 중 예기치 못한 오류가 발생했습니다.");
+            throw new RuntimeException("프롬프트 빌드 중 예기치 못한 오류가 발생했습니다.", e);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5f40d3c and 244d38f.

📒 Files selected for processing (6)
  • src/main/java/io/github/petty/pipeline/controller/PipelineController.java (3 hunks)
  • src/main/java/io/github/petty/pipeline/service/PromptAssemblyService.java (0 hunks)
  • src/main/java/io/github/petty/pipeline/service/PromptAssemblyServiceImpl.java (0 hunks)
  • src/main/java/io/github/petty/pipeline/service/PromptGeneratorServiceImpl.java (1 hunks)
  • src/main/java/io/github/petty/pipeline/service/TogetherServiceImpl.java (2 hunks)
  • src/main/java/io/github/petty/pipeline/support/TogetherPromptBuilder.java (1 hunks)
💤 Files with no reviewable changes (2)
  • src/main/java/io/github/petty/pipeline/service/PromptAssemblyService.java
  • src/main/java/io/github/petty/pipeline/service/PromptAssemblyServiceImpl.java
🔇 Additional comments (9)
src/main/java/io/github/petty/pipeline/service/TogetherServiceImpl.java (3)

21-22: API 모델을 설정 파일에서 주입하도록 개선했습니다.

설정 파일에서 API 모델을 주입받는 방식으로 변경한 것은 좋은 개선입니다. 하드코딩된 값을 제거하고 외부 설정으로 관리함으로써 환경별 구성과 모델 변경이 용이해졌습니다.


30-30: API 요청 본문에 주입된 모델 변수를 사용하도록 수정했습니다.

설정에서 주입받은 apiModel 변수를 사용하도록 변경한 것이 잘 적용되었습니다. 이로써 모델 변경 시 코드 수정 없이 설정 파일만 변경하면 됩니다.


43-43: 예외 메시지를 더 명확하게 개선했습니다.

"잘못된 결과" 대신 "Together API를 호출하지 못하였습니다"로 변경하여 오류의 원인을 더 명확하게 표현한 것이 좋습니다. 오류 발생 시 문제 해결이 용이해질 것입니다.

src/main/java/io/github/petty/pipeline/service/PromptGeneratorServiceImpl.java (1)

10-14: 입력값 검증 로직 추가로 예외 처리가 강화되었습니다.

필수 정보와 사용자 위치 정보에 대한 빈 값 체크를 추가한 것은 매우 좋은 개선입니다. 이를 통해 잘못된 입력으로 인한 문제를 사전에 방지하고, 사용자에게 명확한 오류 메시지를 제공할 수 있게 되었습니다. 예외 메시지도 구체적이고 이해하기 쉽습니다.

src/main/java/io/github/petty/pipeline/controller/PipelineController.java (3)

3-3: 불필요한 import 제거 및 새로운 컴포넌트 import 추가

PromptAssemblyService 대신 새로운 TogetherPromptBuilder 컴포넌트를 import하도록 변경했습니다. 코드 정리가 잘 되었습니다.


17-17: 의존성 주입 개선

PromptAssemblyService에서 TogetherPromptBuilder로 의존성이 변경되었습니다. 이는 PR 목표에 맞게 컴포넌트의 역할과 책임을 명확히 하는 좋은 리팩토링입니다.


33-33: 메서드 호출 변경

assemblePrompt에서 buildPrompt로 메서드 호출이 변경되었습니다. 메서드 이름이 더 직관적으로 바뀌어 코드의 가독성이 향상되었습니다.

src/main/java/io/github/petty/pipeline/support/TogetherPromptBuilder.java (2)

8-14: 새로운 컴포넌트 구조가 잘 설계되었습니다.

TogetherPromptBuilder 컴포넌트가 적절하게 구현되었습니다. 생성자 주입을 통해 의존성을 관리하고, 단일 책임 원칙을 준수하며, 프롬프트 생성 로직을 효과적으로 통합했습니다.


17-19: 입력값 검증 로직이 잘 추가되었습니다.

Vision API 결과가 비어있는 경우에 대한 예외 처리가 적절히 구현되었습니다. 이러한 검증은 불필요한 API 호출을 방지하고 사용자에게 명확한 오류 메시지를 제공합니다.

@s0ooo0k
Copy link
Copy Markdown
Member

s0ooo0k commented Apr 22, 2025

✅ 리뷰

  • 예외 처리 및 가독성 향상 감사합니다!
  • 해당 내용까지 반영하여 RAG 파트와 통합 진행하겠습니다

🔧 제안사항

  • application-secret.yml 변경 파트 팀 채널에 공유부탁드립니다 :)

@s0ooo0k s0ooo0k merged commit 1485cf8 into PETTY-HUB:main Apr 22, 2025
2 checks passed
23MinL pushed a commit to 23MinL/PETTY-BACK-VISION that referenced this pull request Apr 23, 2025
[PIPELINE] 각 부분 예외 처리 강화 및 가독성을 고려한 클래스, 메서드 이름 리팩터링
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants