Skip to content

feat: 챗봇 AI 연결 - #13

Merged
Hminkyung merged 9 commits into
developfrom
feat/#12-chatbot-openAI
Jun 4, 2026
Merged

feat: 챗봇 AI 연결#13
Hminkyung merged 9 commits into
developfrom
feat/#12-chatbot-openAI

Conversation

@Hminkyung

@Hminkyung Hminkyung commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator

📌 작업 요약

  • 요약:
    • AI 서버 챗봇 엔드포인트 구현
    • 시스템 프롬프트를 구성하고 API 호출 로직을 작성
    • temperature 0.2로 설정하여 창의적 응답을 최소화하고 사실 기반 정확한 정보를 전달하도록 구현
    • 불확실한 내용은 담임선생님/학교에 확인을 권유하도록 프롬프트를 설계
    • chat type 필드를 포함하여 추후에 문서 챗봇 생성시에 분리할 수 있도록 설계
  • 관련 이슈: closes [FEAT] 챗봇 AI OpenAI로 연결 #12

🌿 브랜치 정보

  • Source: feat/#12-chatbot-openAI
  • Target: develop (기본)

✅ 체크리스트

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

🧪 테스트 결과

  • (테스트 코드 실행 결과 스크린샷이나 로그, 또는 테스트 방법)
스크린샷 2026-06-04 130130 스크린샷 2026-06-04 130126

Summary by CodeRabbit

릴리스 노트

  • 새로운 기능

    • AI 채팅 엔드포인트 추가 - 사용자는 메시지를 전송하고 AI 응답을 받을 수 있습니다.
    • 다중 언어 및 채팅 유형 지원 포함 (기본값: 한국어, 일반 채팅)
    • 대화 이력 기능으로 연속적인 대화 지원
  • 개선 사항

    • 환경 변수 설정 파일 지원 개선

@Hminkyung Hminkyung self-assigned this Jun 4, 2026
@coderabbitai

coderabbitai Bot commented Jun 4, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

변경 개요

OpenAI와 연동된 채팅 API 기능이 추가됩니다. 요청/응답 데이터 모델, 프롬프트 생성, OpenAI HTTP 호출, FastAPI 라우터, 앱 통합 및 환경 설정이 포함됩니다.

변경 사항

OpenAI 채팅 API 전체 구현

계층 / 파일 요약
채팅 요청/응답 스키마
app/schemas.py
ChatMessageItem(role/content), ChatRequest(message, history, language="KO", chat_type="GENERAL"), ChatResponse(reply) Pydantic 모델을 추가하여 요청/응답 계약을 정의합니다.
프롬프트 생성 로직
app/services/chat_prompt.py
언어 코드별 표시명 매핑(_LANGUAGE_NAME)을 유지하고, build_chat_messages()가 시스템 프롬프트, 히스토리, 현재 메시지를 순서대로 조합하며, _build_system_prompt()가 언어에 맞는 교육용 시스템 프롬프트를 생성합니다.
OpenAI 채팅 서비스
app/services/chat_service.py
chat() 공개 함수가 OpenAI 설정 검증, 메시지 구성, 전후 로깅을 수행하고, _call_openai_chat()/chat/completions에 POST 요청을 보내며 HTTP/통신/파싱 오류를 OpenAIAdapterError로 매핑합니다.
채팅 라우터 및 예외 매핑
app/routers/chat.py
/ai/chat 프리픽스로 APIRouter를 생성하고, POST /messages 엔드포인트가 chat() 호출 결과를 반환하며 OpenAIConfigurationError를 503으로, OpenAIAdapterError를 502로 변환합니다.
앱 초기화 및 환경 설정
.gitignore, app/main.py
.env 패턴을 .gitignore에 추가하고, main.py에서 load_dotenv()를 호출하며 chat.router를 FastAPI 앱에 등록합니다.

예상 코드 리뷰 난이도

🎯 3 (중간) | ⏱️ ~25분

관련 PR

  • GACHI-Project/GACHI-AI#6: OpenAI 어댑터 설정 및 예외 처리 계층과 동일한 코드 경로에서 상호작용합니다.

제안 레이블

feat

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed 제목 '챗봇 AI 연결'은 PR의 주요 변경사항을 명확하게 요약하고 있습니다. FastAPI 애플리케이션에 OpenAI 기반의 챗봇 기능을 추가하는 핵심 목표를 잘 반영하고 있습니다.
Linked Issues check ✅ Passed PR은 이슈 #12의 요구사항을 충족합니다: OpenAI 프롬프트 작성(chat_prompt.py에서 system prompt 구성), AI 서버 통합(chat_service.py에서 OpenAI API 호출), 그리고 테스트 완료 확인(스크린샷 제공)이 구현되었습니다.
Out of Scope Changes check ✅ Passed 모든 변경사항이 이슈 #12의 범위 내에 있습니다. .gitignore 수정(환경변수 지원), main.py(router 등록), schemas.py(요청/응답 모델), chat.py(라우터), chat_service.py(OpenAI 통합), chat_prompt.py(프롬프트)는 모두 챗봇 AI 연결 기능과 직접 관련됩니다.
Description check ✅ Passed PR 설명이 템플릿 구조를 따르고 있으며, 작업 요약, 브랜치 정보, 체크리스트, 테스트 결과를 포함하고 있습니다.

✏️ 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 feat/#12-chatbot-openAI

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.

@Hminkyung Hminkyung added the feat 새로운 기능 추가 작업 label Jun 4, 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: 5

🤖 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/main.py`:
- Around line 1-7: Move the call to load_dotenv() so all imports are grouped
first; currently load_dotenv() is between imports causing Ruff E402. In main.py,
gather the import statements (from dotenv import load_dotenv, from fastapi
import FastAPI, from app.routers import chat, health, newsletters) at the top,
then call load_dotenv() immediately after those imports (before any other
runtime code) to preserve behavior and satisfy the linter.

In `@app/schemas.py`:
- Around line 108-112: The ChatRequest model accepts free-form strings for
language and chat_type which lets clients send invalid values (breaking API
contract and causing silent fallback in app/services/chat_prompt.py); define
explicit Enum classes (e.g., Language and ChatType) with the allowed values and
change ChatRequest.language: Language and ChatRequest.chat_type: ChatType so
pydantic validates inputs and returns 422 on invalid values; update any code
that reads these fields (e.g., functions in app/services/chat_prompt.py that
currently fallback) to use the enum members rather than raw strings.
- Around line 103-110: Change ChatMessageItem.role from an unconstrained str to
a strict enum/Literal limiting values to only "user" or "assistant" so clients
cannot inject "system" or other roles; update the ChatMessageItem definition
(and import types) to use typing.Literal["user","assistant"] or a small Enum and
ensure ChatRequest.history remains a list[ChatMessageItem] (and remove/avoid
using a mutable default like [] if applicable) so downstream code in
chat_prompt.py that forwards item.role to OpenAI only ever receives validated
"user" or "assistant" values.

In `@app/services/chat_prompt.py`:
- Around line 57-59: The CI fails due to a >100-char string on the second prompt
line in app/services/chat_prompt.py; locate the long Korean sentence in the
prompt definition (the multi-line prompt constant or list of prompt strings) and
break it into shorter string literals under 100 chars each using implicit
concatenation or by splitting into two strings joined with a space so the
runtime text is unchanged (e.g., split the long sentence into two shorter quoted
segments in the same prompt variable such as the system prompt constant used by
the chat prompt builder).

In `@app/services/chat_service.py`:
- Around line 14-18: chat currently only checks get_openai_settings().api_key
and ignores the OpenAISettings.enabled flag; update chat to first inspect
get_openai_settings().enabled (the OpenAISettings.enabled property) and if it's
False raise or return an OpenAIConfigurationError (same error type) before any
API calls or api_key checks, so no OpenAI traffic occurs when disabled; locate
the check in the chat function and modify the control flow to validate
settings.enabled prior to using settings.api_key.
🪄 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: 45c57693-eb6c-4716-ab98-bfca682be94f

📥 Commits

Reviewing files that changed from the base of the PR and between 28fae7f and e90b391.

📒 Files selected for processing (6)
  • .gitignore
  • app/main.py
  • app/routers/chat.py
  • app/schemas.py
  • app/services/chat_prompt.py
  • app/services/chat_service.py

Comment thread app/main.py
Comment thread app/schemas.py Outdated
Comment thread app/schemas.py Outdated
Comment thread app/services/chat_prompt.py
Comment thread app/services/chat_service.py
@Hminkyung
Hminkyung requested a review from deli-minju June 4, 2026 04:50

@deli-minju deli-minju left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

시스템 프롬프트와 OpenAI 호출 흐름이 잘 정리되어 있고, 낮은 temperature 설정과 불확실한 내용에 대한 확인 안내도 서비스 성격에 맞게 적절해 보입니다.
chat type 필드로 추후 문서 챗봇 확장까지 고려된 점도 확인했습니다. 고생하셨습니다!

@Hminkyung
Hminkyung merged commit 9d51eca into develop Jun 4, 2026
3 checks passed
@deli-minju
deli-minju deleted the feat/#12-chatbot-openAI branch June 11, 2026 07:56
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] 챗봇 AI OpenAI로 연결

2 participants