Skip to content

fix: OpenAI 분석 응답 스키마 실패 재시도 - #45

Merged
deli-minju merged 2 commits into
developfrom
bugfix/#44-openai-schema-retry
Jun 12, 2026
Merged

fix: OpenAI 분석 응답 스키마 실패 재시도#45
deli-minju merged 2 commits into
developfrom
bugfix/#44-openai-schema-retry

Conversation

@deli-minju

@deli-minju deli-minju commented Jun 12, 2026

Copy link
Copy Markdown
Contributor

📌 작업 요약

  • 요약:
    • OpenAI 분석 응답이 JSON이지만 NewsletterAnalysisResponse 스키마 검증에 실패하는 경우 1회 자동 재시도하도록 개선
    • 재시도 요청에 검증 실패 원인과 items/checklistItems 배열 원소는 반드시 JSON object여야 한다는 보정 지시 추가
    • 기본 분석 프롬프트에도 배열 원소에 문자열 조각이 들어가지 않도록 방어 지시 추가
    • items.1 = "},{" 형태의 스키마 이탈 응답에 대한 재시도 성공/최종 실패 테스트 추가
  • 관련 이슈: closes [BUG] OpenAI 분석 응답 스키마 불일치로 가정통신문 분석 실패 #44

🌿 브랜치 정보

  • Source: bugfix/#44-openai-schema-retry
  • Target: develop (기본)

✅ 체크리스트

  • 브랜치 컨벤션 준수 (feat/refac/hotfix/chore/design/bugfix)
  • 커밋 컨벤션 준수 (feat/fix/refactor/docs/style/chore)
  • self-review 완료
  • 테스트 및 로컬 실행 확인 완료

🧪 테스트 결과

.\.venv\Scripts\python.exe -m unittest discover -s tests
.\.venv\Scripts\python.exe -m pytest
.\.venv\Scripts\python.exe -m ruff check .
.\.venv\Scripts\python.exe -m ruff format --check .

Summary by CodeRabbit

릴리스 노트

  • Bug Fixes

    • 분석 요청 중 응답 검증 실패 시 자동 재시도 로직 추가로 안정성 개선
    • JSON 출력 형식 제약 조건 강화로 데이터 일관성 향상
  • Tests

    • 검증 재시도 동작을 검증하는 테스트 추가

@deli-minju deli-minju self-assigned this Jun 12, 2026
@deli-minju deli-minju added the fix 버그 수정 작업 label Jun 12, 2026
@coderabbitai

coderabbitai Bot commented Jun 12, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@deli-minju, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 43 minutes and 22 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more credits in the billing tab to continue.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 557815b9-8be8-42d9-b91f-2f63a07eb9f6

📥 Commits

Reviewing files that changed from the base of the PR and between 9c3edbe and aa15ae9.

📒 Files selected for processing (2)
  • app/services/openai_adapter.py
  • tests/test_openai_adapter.py
📝 Walkthrough

Walkthrough

OpenAI 분석 응답의 간헐적 스키마 검증 실패 문제를 해결하기 위해 프롬프트 제약을 강화하고 어댑터에 재시도 로직을 추가하며, 이를 검증하는 테스트를 도입했습니다.

Changes

OpenAI 응답 스키마 검증 재시도

Layer / File(s) Summary
시스템 프롬프트 JSON 객체 제약 추가
app/services/newsletter_prompt.py
_build_system_prompt() 함수의 시스템 프롬프트에 itemschecklistItems 배열 원소가 반드시 JSON 객체여야 하며, 문자열 조각이나 가짜 JSON을 넣지 말아야 한다는 출력 형식 제약을 명시했습니다.
OpenAI 어댑터 재시도 로직 및 스키마 검증 헬퍼
app/services/openai_adapter.py
MAX_ANALYSIS_ATTEMPTS 상수를 추가하고, analyze() 메서드에 스키마 검증 실패 시 최대 2회 재시도하는 루프를 구현했습니다. 매 재시도마다 _build_schema_retry_message() 헬퍼를 호출해 검증 에러 상세를 포함한 스키마 준수 지침을 생성하고 다음 요청 메시지에 추가합니다. 모든 시도가 실패하면 마지막 검증 에러를 원인으로 OpenAIAdapterError를 발생시킵니다.
스키마 재시도 동작 검증 테스트
tests/test_openai_adapter.py
StubOpenAINewsletterAdapter 테스트 더블과 _valid_response(), _i18n() 헬퍼를 추가했습니다. OpenAIAdapterSchemaRetryTest에서 (1) 첫 응답이 스키마 불일치 후 재시도 시 성공하는 경우와 (2) 재시도 후에도 실패해 에러가 발생하는 경우를 검증하며, 재시도 메시지에 검증 에러와 items 배열 제약 가이드가 포함되는지 확인합니다.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • GACHI-Project/GACHI-AI#5: 분석 응답 스키마를 NewsletterAnalysis*로 정의한 변경으로, 동일 프롬프트 계층에서 스키마 계약을 확립한 선행 PR입니다.
  • GACHI-Project/GACHI-AI#21: newsletter_prompt.py의 시스템 프롬프트 스키마 요구사항을 수정한 변경으로, 동일 계층의 관련 스키마 제약 추가입니다.
  • GACHI-Project/GACHI-AI#32: _build_system_prompt() 함수의 JSON 출력 및 스키마 요구사항을 변경한 선행 변경으로, 동일 프롬프트 강화 맥락입니다.

Suggested labels

refactor

Suggested reviewers

  • Hminkyung
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed PR 제목이 주요 변경사항을 명확하게 요약하고 있습니다. OpenAI 분석 응답 스키마 검증 실패 시 재시도 기능 추가를 간결하게 표현합니다.
Description check ✅ Passed PR 설명이 템플릿의 모든 필수 섹션을 포함하고 있습니다. 작업 요약, 브랜치 정보, 체크리스트, 테스트 결과가 모두 완성되어 있습니다.
Linked Issues check ✅ Passed PR의 모든 변경사항이 #44 이슈의 요구사항을 충족합니다. 스키마 검증 실패 시 재시도 로직, 배열 원소 검증 강화, 방어 지시 추가, 관련 테스트 케이스가 모두 구현되어 있습니다.
Out of Scope Changes check ✅ Passed 모든 변경사항이 #44 이슈 해결에 직접 관련되어 있습니다. 범위 외의 변경사항은 발견되지 않습니다.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch bugfix/#44-openai-schema-retry

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@app/services/openai_adapter.py`:
- Around line 53-58: The current logger.warning call in openai_adapter.py logs
the full ValidationError string (logger.warning(..., exc)), which may include
sensitive input_value content; instead, catch the ValidationError and log a
sanitized summary: extract only the error paths/types/counts (e.g., from
ValidationError.errors() or similar) and log a concise message like
"[OpenAIAdapter] 응답 스키마 검증 실패. attempt=%s/%s, errors=%s" with a list of error
locations/types or a count, omitting any input_value or raw text; update the
logger.warning invocation (and any surrounding except block that handles
ValidationError) to build and log this sanitized summary rather than the full
exc.__str__().
- Around line 86-94: The retry prompt currently appends the full ValidationError
string which can include huge input_value data; update
_build_schema_retry_message to instead extract exc.errors(), map each error to a
concise dict with only loc, msg, and type, serialize that list (e.g., join or
JSON) and truncate the serialized string to a safe max length (choose a constant
like 500-1000 chars) before including it in the returned message; ensure you
reference ValidationError and exc.errors() and apply the truncation so the retry
prompt stays short and focused.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: e07e5ece-913d-4faa-9162-e86f237d4588

📥 Commits

Reviewing files that changed from the base of the PR and between b48a753 and 9c3edbe.

📒 Files selected for processing (3)
  • app/services/newsletter_prompt.py
  • app/services/openai_adapter.py
  • tests/test_openai_adapter.py

Comment thread app/services/openai_adapter.py
Comment thread app/services/openai_adapter.py
@deli-minju
deli-minju merged commit 45899ab into develop Jun 12, 2026
3 checks passed
@deli-minju
deli-minju deleted the bugfix/#44-openai-schema-retry branch June 12, 2026 15:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fix 버그 수정 작업

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] OpenAI 분석 응답 스키마 불일치로 가정통신문 분석 실패

1 participant