Skip to content

feat: 문서 챗봇 기능와 맥락설명을 위한 프롬프팅 - #49

Merged
Hminkyung merged 12 commits into
developfrom
feat/#48-document-chat
Jul 27, 2026
Merged

feat: 문서 챗봇 기능와 맥락설명을 위한 프롬프팅#49
Hminkyung merged 12 commits into
developfrom
feat/#48-document-chat

Conversation

@Hminkyung

@Hminkyung Hminkyung commented Jul 27, 2026

Copy link
Copy Markdown
Collaborator

📌 작업 요약

  • 요약: 문서챗봇 기능과 맥락설명에 들어갈 정보를 위한 프롬프팅과 기능 추가입니다.
  • 관련 이슈: closes [FEAT] 문서 챗봇 #48

🌿 브랜치 정보

  • Source: feat/#48-document-chat
  • Target: develop (기본) / main (릴리즈, 핫픽스)

✅ 체크리스트

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

🧪 테스트 결과

  • (테스트 코드 실행 결과 스크린샷이나 로그, 또는 테스트 방법)
스크린샷 2026-07-27 171826 스크린샷 2026-07-27 171831 스크린샷 2026-07-27 171955 스크린샷 2026-07-27 171959

Summary by CodeRabbit

  • 새로운 기능

    • 가정통신문 문서를 기반으로 질문에 답하는 문서 챗봇 기능이 추가되었습니다.
    • 문화 가이드 FAQ 추천 기능이 추가되어, 뉴스레터 내용에 적합한 FAQ를 최대 2개까지 추천합니다.
    • 문화 가이드 추천 결과에 FAQ ID와 추천 사유가 함께 제공됩니다.
  • 버그 수정

    • 문서 없이 문서 챗봇을 요청할 경우 명확한 잘못된 요청 오류로 안내됩니다.
    • 문화 가이드 추천 결과의 중복되거나 유효하지 않은 항목을 자동으로 정리합니다.

@coderabbitai

coderabbitai Bot commented Jul 27, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@Hminkyung, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 26 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

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.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: fb7a402e-78c5-4b7b-ae94-54024120dfd1

📥 Commits

Reviewing files that changed from the base of the PR and between 3cd6173 and f237211.

📒 Files selected for processing (7)
  • app/routers/newsletters.py
  • app/schemas.py
  • app/services/chat_prompt.py
  • app/services/chat_service.py
  • app/services/cultural_guide_prompt.py
  • app/services/openai_adapter.py
  • tests/test_chat_prompt.py
📝 Walkthrough

Walkthrough

문서 챗봇용 요청 스키마, 문서 기반 프롬프트, 누락 문서 오류 처리를 추가했습니다. 문화 가이드 FAQ 선택을 위한 스키마·프롬프트·서비스·OpenAI 어댑터·POST 엔드포인트도 추가했습니다.

Changes

문서 챗봇

Layer / File(s) Summary
문서 채팅 계약과 입력 검증
app/schemas.py, app/services/chat_service.py, app/routers/chat.py
ChatRequest에 문서 컨텍스트를 추가하고, 문서 본문이 없는 문서 모드 요청을 400 Bad Request로 처리합니다.
문서 기반 프롬프트 생성
app/services/chat_prompt.py
요청 전체를 기준으로 문서 모드 프롬프트를 생성하며, 문서 본문을 최대 6000자로 제한합니다.

문화 가이드 FAQ 선택

Layer / File(s) Summary
문화 가이드 계약과 선택 프롬프트
app/schemas.py, app/services/cultural_guide_prompt.py
FAQ 후보·선택 결과 스키마와 최대 2개 선택을 제한하는 JSON 및 프롬프트 규칙을 추가합니다.
문화 가이드 OpenAI 호출
app/services/openai_adapter.py
FAQ 후보를 OpenAI /responses 요청으로 전달하고 JSON 응답을 CulturalGuideResponse로 검증합니다.
문화 가이드 정제와 API 노출
app/services/cultural_guide_service.py, app/routers/newsletters.py
후보 외 ID와 중복을 제거하고 선택 수를 제한한 결과를 POST /ai/newsletters/cultural-guides에서 반환합니다.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

문서 채팅 오류 처리

sequenceDiagram
  participant Client
  participant send_message
  participant chat
  Client->>send_message: 문서 채팅 요청
  send_message->>chat: chat(request)
  chat-->>send_message: 문서 본문 누락 오류
  send_message-->>Client: 400 Bad Request
Loading

문화 가이드 FAQ 선택

sequenceDiagram
  participant Client
  participant cultural_guides
  participant select_cultural_guides
  participant OpenAINewsletterAdapter
  Client->>cultural_guides: POST /ai/newsletters/cultural-guides
  cultural_guides->>select_cultural_guides: CulturalGuideRequest
  select_cultural_guides->>OpenAINewsletterAdapter: FAQ 선택 요청
  OpenAINewsletterAdapter-->>select_cultural_guides: CulturalGuideResponse
  select_cultural_guides-->>Client: 정제된 selectedFaqs
Loading

Possibly related issues

Possibly related PRs

  • GACHI-Project/GACHI-AI#6OpenAINewsletterAdapter의 OpenAI 호출 구조를 확장하는 코드 경로가 직접 연결됩니다.
  • GACHI-Project/GACHI-AI#13 — 채팅 라우터와 서비스 경로에 문서 모드 검증 및 예외 매핑을 추가한 변경과 연결됩니다.
🚥 Pre-merge checks | ✅ 3 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning 문화 가이드 FAQ 선택 엔드포인트와 관련 서비스·스키마가 문서 챗봇 이슈 #48 범위를 벗어납니다. 문화 가이드 기능은 별도 이슈나 PR로 분리하고, #48에는 문서 챗봇 관련 변경만 남기세요.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed 문서 챗봇용 프롬프트, 스키마, 서비스, 예외 처리가 이슈 #48의 완료 조건을 충족합니다.
Title check ✅ Passed 제목이 문서 챗봇 프롬프팅과 맥락 설명 추가라는 주요 변경을 잘 요약합니다.
Description check ✅ Passed 작업 요약, 관련 이슈, 브랜치 정보, 체크리스트, 테스트 결과가 템플릿 형식에 맞게 대부분 채워져 있습니다.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/#48-document-chat

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.

@Hminkyung Hminkyung self-assigned this Jul 27, 2026
@Hminkyung Hminkyung added the feat 새로운 기능 추가 작업 label Jul 27, 2026

@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: 7

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
app/services/chat_service.py (1)

17-29: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

문서 입력을 OpenAI 설정보다 먼저 검증하세요.

현재 OpenAI가 비활성화됐거나 키가 없으면 공백 document.originalText 요청도 400이 아닌 503으로 끝납니다. DOCUMENT 요청의 본문 검증을 함수 첫 부분으로 옮겨 잘못된 클라이언트 입력이 항상 400으로 매핑되게 하세요.

🤖 Prompt for 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.

In `@app/services/chat_service.py` around lines 17 - 29, In the chat service
validation flow, move the ChatType.DOCUMENT check for missing or blank
request.document.original_text before retrieving or validating OpenAI settings.
Preserve the existing ChatDocumentMissingError so invalid document requests map
to 400 regardless of OpenAI availability, while leaving settings validation
unchanged for valid requests.
🤖 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/routers/newsletters.py`:
- Around line 68-81: Update the /cultural-guides endpoint and
CulturalGuideResponse so the public DTO exposes only the selected FAQ IDs and
never serializes SelectedCulturalGuide.relevanceReason. Keep relevanceReason
available only in the internal selection result for logging or quality checks,
and map the result to the new FAQ-ID-only response schema before returning it
from cultural_guides.

In `@app/schemas.py`:
- Line 147: Update the schema field original_text in the relevant document model
to allow a missing or null originalText value, so DOCUMENT requests reach the
service-level ChatDocumentMissingError and retain the existing 400 response
mapping; keep non-document validation behavior unchanged.

In `@app/services/chat_prompt.py`:
- Around line 80-90: Update _build_document_system_prompt so it contains only
trusted static instructions and explicitly treats document content as untrusted
data, not executable instructions. Move document_block out of the system prompt
and pass it through a separate user/reference message while preserving the
required language and document-chat behavior.
- Around line 135-141: Update the prompt construction around the document block
to enforce length limits on document.title and document.summary, not just
original_text. Apply the schema-input limits for each metadata field and cap the
complete assembled document block at 6,000 characters before adding it to the
system prompt, preserving the existing formatting and trimming behavior for
valid content.
- Around line 87-90: Update the prompt templates in the document-description
sections near the Korean and alternate-language blocks to state that the content
may be a truncated excerpt, not the entire original document. Explicitly
instruct the model to distinguish information absent from the provided excerpt
from information absent in the original document, and include whether truncation
occurred using the existing document-length/truncation context.

In `@app/services/cultural_guide_prompt.py`:
- Around line 82-109: Update the request schema for CulturalGuideRequest to
enforce maximum limits on original_text length and FAQ candidate count, and
limit each candidate’s category and question length. Reject inputs exceeding
these contract limits with validation errors mapped to HTTP 422, while
preserving the existing _build_user_prompt and _format_faq_candidates behavior
for valid requests.

In `@app/services/openai_adapter.py`:
- Around line 164-175: Update the payload constructed in
select_cultural_guides() to explicitly set the Responses API store option to
False, preserving the existing model, input, and response-format fields.

---

Outside diff comments:
In `@app/services/chat_service.py`:
- Around line 17-29: In the chat service validation flow, move the
ChatType.DOCUMENT check for missing or blank request.document.original_text
before retrieving or validating OpenAI settings. Preserve the existing
ChatDocumentMissingError so invalid document requests map to 400 regardless of
OpenAI availability, while leaving settings validation unchanged for valid
requests.
🪄 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 Plus

Run ID: b578f2d6-3da6-44ff-818f-43a38581fd2f

📥 Commits

Reviewing files that changed from the base of the PR and between f0b33a9 and 3cd6173.

📒 Files selected for processing (8)
  • app/routers/chat.py
  • app/routers/newsletters.py
  • app/schemas.py
  • app/services/chat_prompt.py
  • app/services/chat_service.py
  • app/services/cultural_guide_prompt.py
  • app/services/cultural_guide_service.py
  • app/services/openai_adapter.py

Comment thread app/routers/newsletters.py
Comment thread app/schemas.py Outdated
Comment thread app/services/chat_prompt.py Outdated
Comment thread app/services/chat_prompt.py Outdated
Comment thread app/services/chat_prompt.py
Comment thread app/services/cultural_guide_prompt.py
Comment thread app/services/openai_adapter.py
@Hminkyung
Hminkyung merged commit e507a10 into develop Jul 27, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feat 새로운 기능 추가 작업

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEAT] 문서 챗봇

1 participant