Skip to content

feat: chatbot document rag logic advancement - #100

Merged
Yu-JeSeung merged 2 commits into
mainfrom
feat/chatbot_rag_logic
Apr 30, 2026
Merged

feat: chatbot document rag logic advancement#100
Yu-JeSeung merged 2 commits into
mainfrom
feat/chatbot_rag_logic

Conversation

@Yu-JeSeung

@Yu-JeSeung Yu-JeSeung commented Apr 30, 2026

Copy link
Copy Markdown
Contributor

관련 이슈

Close #99

🎯 배경

  • 기존 학교 정보 RAG 인덱싱은 dmu_documents_cleaned.json의 실제 데이터 구조를 충분히 반영하지 못하고, 단순 문장/토큰 기준 청킹에 의존하고 있었습니다.
  • 학교 홈페이지 데이터에는 편집모드 문구, 담당부서 꼬리말, 연락처, 정책/연혁/개인정보 문서, 표 형태 텍스트가 섞여 있어 검색 정확도와 답변 근거 품질을 개선할 필요가 있었습니다.

🔍 주요 내용

  • dmu_documents_cleaned.json 기반 RAG 전처리/청킹 구조 고도화

    • 편집모드 문구, fnctId/fnctNo, 다운로드 UI 텍스트 등 노이즈 제거
    • intro, department, policy, history, privacy, contact, table_like, page 문서 타입 분류 추가
    • 문서 타입별 청킹 기준 적용
  • 검색 인덱스 스키마 확장

    • text_for_embedding, text_for_bm25, text_for_answer 분리
    • breadcrumb, leaf_title, section_title, has_phone, has_date, has_credit, has_policy_keyword, is_privacy_old 메타데이터 추가
    • BM25와 임베딩 생성 시 검색 목적별 텍스트 컬럼 사용
  • query_index.py 검색/재랭킹 개선

    • 새 컬럼이 있으면 메타데이터 기반 가중치 적용
    • 구버전 아티팩트는 기존 text 컬럼으로 fallback
    • 연락처, 정책/학칙/졸업, 소개/학과, 개인정보 질의별 가중치 보정
    • 납작한 표 형태의 졸업학점 추출 패턴 보강
  • 회귀 테스트 케이스 추가

    • 컴퓨터공학부 소개
    • 휴복학 안내
    • 졸업학점
    • 디자인홍보센터 전화번호
    • 개인정보처리방침
  • 검증

    • build_index.py 전체 실행 및 RAG 아티팩트 재생성
    • search_df, embeddings, bm25 row 수 정합성 확인
    • 챗봇 API 회귀 테스트 17/17 통과

변경 요약(1~3줄)

학교 웹사이트 RAG 파이프라인을 개선해 전처리·청킹·인덱스 스키마를 확장하고, 쿼리 의도 기반 검색 가중치와 재순위 로직을 도입해 검색·응답 정확도를 높였습니다.

주요 변경점

  • 노이즈 제거 및 문서 타입 분류 추가(privacy, history, contact, department, policy, table_like, intro, page) 및 타입별 청킹 규칙 적용
  • 텍스트 필드 분리: text_for_embedding / text_for_bm25 / text_for_answer로 목적별 인덱싱 분리
  • 메타데이터 확대: breadcrumb, leaf_title, section_title, has_phone, has_date, has_credit, has_policy_keyword, is_privacy_old 등 추가
  • 검색엔진 변경: BM25는 text_for_bm25 사용, 임베딩은 text_for_embedding 사용(구 아티팩트 대비 폴백 처리)
  • 쿼리 의도 기반 가중치·재순위: 연락처/정책/학사/소개/개인정보 등 카테고리별 가중치 조정 및 평점 보정
  • 표 형식(졸업학점 등) 추출 정규식 강화 및 연락처 추출 기준 개선
  • 회귀 테스트 추가 및 전체 챗봇 API 회귀(17/17) 통과, build_index.py로 RAG 아티팩트 재생성

주의/리스크

  • 인덱스 스키마 변경으로 기존 아티팩트와 호환성 주의(폴백 존재하나 구버전 지원 여부 검증 필요)
  • 메타데이터가 누락된 문서에서 검색 품질 저하 가능성(검증 필요)

다음 액션

  • 프로덕션에서 새 인덱스 재생성 및 롤아웃 확인(build_index.py 실행)
  • 실제 쿼리 모니터링으로 가중치·재순위 튜닝 및 추가 회귀 케이스 보강

@Yu-JeSeung Yu-JeSeung self-assigned this Apr 30, 2026
@coderabbitai

coderabbitai Bot commented Apr 30, 2026

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 3b0238e7-1e0f-44fd-91b0-5ec79d9910c6

📥 Commits

Reviewing files that changed from the base of the PR and between 48b4e2e and a1c05d5.

📒 Files selected for processing (1)
  • LLM/sub_model/query_index.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • LLM/sub_model/query_index.py

📝 Walkthrough

Walkthrough

문서 정제·분류·청킹 파이프라인과 색인 스키마가 확장되었습니다. BM25·임베딩 대상 텍스트 필드 분리, 조회용 메타데이터/플래그 추가, 회귀 테스트 케이스 및 깃 설정(.gitignore·PR 템플릿) 변경이 포함됩니다. (총 변경: 스크립트·유틸·쿼리·테스트·설정 파일 다수 변경)

Changes

Cohort / File(s) Summary
PR 템플릿 및 설정
.github/pull_request_template.md, .gitignore, CHECKLIST.md
PR 템플릿의 리뷰 소요시간 블록 제거 및 리스트 표기 변경. .gitignorehs_err_pid*.log 추가, debug/ 경로 무시 규칙을 내용 무시로 변경하고 debug/regression/과 파일을 예외 처리. CHECKLIST.md 개행 보정.
색인 구축 파이프라인
LLM/sub_model/build_index.py
청킹을 chunk_document(row) 호출로 전환. search_df 스키마 확장(예: parent_id, text_for_embedding, text_for_bm25, text_for_answer, 문서/청크 메타데이터 및 플래그). 연락처 행 처리도 확장된 스키마에 맞게 갱신. BM25·임베딩 생성은 신규 텍스트 칼럼 사용.
색인 유틸리티 / 청킹 로직
LLM/sub_model/index_utils.py
원문 정제 함수(clean_content) 추가, 문서 타입 분류(classify_doc_type), 문서 단위 청킹(chunk_document) 및 연락처 후보 필터(_is_contact_unit_candidate) 추가. 토큰 제한/오버랩 기반 청킹, 타입별 세그먼트 분해, 메타데이터 플래그(전화/이메일/날짜/신용카드/정책 키워드 등) 생성. load_json_gz 개행 문제 수정.
쿼리/검색 로직
LLM/sub_model/query_index.py
의도 기반 정규식/상수 확장(예: 졸업학점 관련), 검색/재순위 보너스·패널티 계산을 메타데이터·의도에 맞게 리팩토링. 답변/연락처 선택용 헬퍼 추가, BM25 토크나이저가 text_for_bm25 사용하도록 변경. 일부 문서 타입을 페이지로 분류하는 재순위 규칙 완화.
회귀 테스트 케이스(데이터)
debug/regression/chatbot_regression_cases.json
챗봇 회귀 케이스 JSON 파일 추가(다수의 한국어 프롬프트와 기대 키워드 조건 포함).

Sequence Diagram(s)

sequenceDiagram
    participant Raw as Raw Document
    participant Cleaner as Content Cleaner
    participant Classifier as Doc Classifier
    participant Chunker as Document Chunker
    participant Indexer as Index Builder
    participant BM25 as BM25 Indexer
    participant Embedder as Embedding Generator

    Raw->>Cleaner: 원문 전송
    Cleaner->>Cleaner: 대시/ID 정규화<br/>편집자 푸터·다운로드 노이즈 제거
    Cleaner->>Classifier: 정제된 텍스트 전달
    Classifier->>Classifier: 제목/URL/내용 분석으로 문서 타입 분류
    Classifier->>Chunker: 타입별 분할 로직 지시
    Chunker->>Chunker: 세그먼트 생성 및 토큰 제한으로 청킹(오버랩 포함)
    Chunker->>Indexer: 청크(부모ID, text_for_*, 메타데이터) 제출
    Indexer->>BM25: `text_for_bm25` + 메타데이터로 색인
    BM25->>BM25: 토큰화 및 역색인 구축
    Indexer->>Embedder: `text_for_embedding`로 임베딩 생성 요청
    Embedder->>Embedder: 임베딩 생성
    Indexer->>Indexer: 최종 search_df와 doc_type_counts 완성
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive PR 설명이 템플릿의 필수 섹션을 포함하고 있으나, '⌛️ 리뷰 소요 시간' 섹션이 누락되어 있습니다. 템플릿의 '⌛️ 리뷰 소요 시간' 섹션을 추가하여 예상 검토 시간을 명시해 주세요.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed PR 제목이 주요 변경사항인 RAG 로직 고도화를 명확하게 요약하고 있습니다.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/chatbot_rag_logic

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
Review rate limit: 0/1 reviews remaining, refill in 60 minutes.

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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@LLM/sub_model/query_index.py`:
- Around line 328-335: The has_phone/has_email computation incorrectly treats
non-empty sentinel strings like "없음" as valid; update the logic in
query_index.py that builds has_phone and has_email from search_df (columns
"phone" and "email") to normalize and validate values: trim and lower the
string, reject known placeholders (e.g., "없음", "없다", "none", "n/a", "-", "na")
and only mark as present if the normalized value is not in that blacklist and
also matches a simple validation (phone: digits/optional separators of expected
length; email: basic local@domain pattern). Replace the current
.astype(str).ne("") checks with this combined blacklist + regex validation so
has_phone and has_email reflect true contact info.
🪄 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: CHILL

Plan: Pro

Run ID: 75e7c30d-0312-4497-92f9-6b3117236570

📥 Commits

Reviewing files that changed from the base of the PR and between af79fb6 and 48b4e2e.

📒 Files selected for processing (6)
  • .github/pull_request_template.md
  • .gitignore
  • LLM/sub_model/build_index.py
  • LLM/sub_model/index_utils.py
  • LLM/sub_model/query_index.py
  • debug/regression/chatbot_regression_cases.json

Comment thread LLM/sub_model/query_index.py
@Yu-JeSeung
Yu-JeSeung merged commit c325084 into main Apr 30, 2026
1 check passed
@Yu-JeSeung
Yu-JeSeung deleted the feat/chatbot_rag_logic branch April 30, 2026 10:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEAT] 챗봇 RAG 구조 개편

1 participant