Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 109 additions & 0 deletions .serena/memories/code_style_and_conventions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
# 코드 스타일 및 규칙

## 네이밍 규칙
- **변수/함수/메서드**: `snake_case`
- **클래스**: `PascalCase`
- **상수**: `UPPER_SNAKE_CASE`
- **비공개 메서드/속성**: `_leading_underscore`

## 타입 힌트
- **필수**: 모든 함수 파라미터와 반환값에 타입 힌트 사용
- **형식**: 콜론 앞에 공백 (예: `user_id : str`, `chatbot_id: int`)
- 일관성은 없지만 대부분 콜론 뒤에만 공백
- **타입**: Python 표준 타입 힌트 사용 (`str`, `int`, `dict`, `list` 등)
- **Optional**: `Optional[T]` 또는 `T | None` 사용

## 비동기 프로그래밍
- **async/await**: FastAPI 엔드포인트와 서비스 로직에서 일관되게 사용
- **비동기 함수**: 모든 I/O 작업 (DB, API 호출, gRPC 등)은 비동기로 처리
```python
async def chat(chatbot_id: int, ...) -> BaseResponse:
chatbot_response = await chatbot_service.chat(...)
return BaseResponse(...)
```

## FastAPI 패턴

### 라우터
- **APIRouter 사용**: 각 도메인별로 라우터 분리
- **prefix와 tags**: 라우터 그룹화
```python
router = APIRouter(prefix="/chatbots", tags=["chatbot"])
```

### 의존성 주입
- **Depends**: FastAPI의 의존성 주입 시스템 활용
```python
async def chat(
chatbot_id: int,
user_id: str = Depends(get_user_id),
user_grpc_client: UserGrpcClient = Depends(user_stub_dep),
):
...
```

### 응답 형식
- **BaseResponse**: 일관된 응답 래퍼 사용
```python
return BaseResponse(message="success message", data=response_data)
```

## 예외 처리
- **BusinessException**: 비즈니스 로직 예외는 커스텀 예외 사용
```python
class BusinessException(Exception):
def __init__(self, message: str = "에러 발생", status_code: int = 500):
self.status_code = status_code
self.message = message
```
- **Global Exception Handler**: `main.py`에서 전역 예외 처리

## 코멘트 및 문서화
- **한글 코멘트**: 코드 내 주석은 한글로 작성
```python
# 캐릭터 챗
@router.post("/chat/{chatbot_id}")
async def chat(...):
...
```
- **Docstring**: 복잡한 함수에는 docstring 추가 권장 (하지만 필수는 아님)

## Import 순서
1. 표준 라이브러리
2. 서드파티 라이브러리
3. 로컬 모듈
- `core.*`
- `api.*`
- `app.*`

예시:
```python
from fastapi import APIRouter, Depends, Query

from core.grpcs.client import UserGrpcClient
from api.depends.get_user_id import get_user_id
from api.schemas.request.chatbot_request import ChatRequest
from app.chatbot.service import chatbot_service
```

## 파일 구조
- **라우터**: `api/routers/` - FastAPI 엔드포인트만 정의
- **서비스**: `app/{domain}/service.py` - 비즈니스 로직
- **스키마**: `api/schemas/` - Pydantic 모델
- **의존성**: `api/depends/`, `core/*/deps/` - 의존성 주입 함수

## 데이터베이스
- **Beanie ORM**: MongoDB 모델 정의
- **MongoDB 연결**: 앱 lifespan에서 초기화/종료
```python
@asynccontextmanager
async def lifespan(app: FastAPI):
await init_mongodb(app)
yield
await close_mongodb(app)
```

## 코드 포맷팅
- 명시적인 린터/포맷터 설정 파일 없음
- 일반적인 Python 컨벤션 따름 (PEP 8 기반)
- 들여쓰기: 4 스페이스
100 changes: 100 additions & 0 deletions .serena/memories/project_overview.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# FastAPIProject - 프로젝트 개요

## 프로젝트 목적
AI 캐릭터 챗봇 시스템을 제공하는 FastAPI 기반 백엔드 API 서비스입니다.

### 주요 기능
- **AI 캐릭터 챗봇**: LangChain, OpenAI, Pinecone을 활용한 RAG 기반 대화형 챗봇
- **챗봇 말투셋 관리**: 캐릭터별 말투와 스타일 커스터마이징
- **대화 히스토리**: 사용자와 챗봇 간의 대화 기록 관리
- **gRPC 통신**: User, Chatbot 등 다른 마이크로서비스와 통신
- **이벤트 처리**: Kafka를 통한 비동기 이벤트 발행/구독
- **웹 크롤링**: Selenium + Chromium을 활용한 웹 데이터 수집

## 기술 스택

### 백엔드 프레임워크
- **Python 3.11**
- **FastAPI 0.116**: 현대적인 Python 웹 프레임워크
- **Uvicorn**: ASGI 서버

### 데이터베이스 및 저장소
- **MongoDB** (Motor + Beanie ORM): 주 데이터베이스
- **Redis**: 캐싱
- **Pinecone**: 벡터 데이터베이스 (임베딩 저장)

### AI/ML
- **LangChain**: AI 애플리케이션 프레임워크
- **OpenAI API**: LLM
- **Google Generative AI**: 추가 AI 모델
- **DeepSeek**: 대체 LLM

### 메시징 및 통신
- **Kafka** (aiokafka): 이벤트 스트리밍
- **gRPC** (grpcio): 마이크로서비스 간 통신

### 웹 크롤링
- **Selenium**: 브라우저 자동화
- **undetected-chromedriver**: Chromium 드라이버
- **BeautifulSoup4**: HTML 파싱

### 배포
- **Docker**: 컨테이너화 (ARM64 지원)
- **포트**: 4449

## 프로젝트 구조

```
FastAPIProject/
├── main.py # FastAPI 앱 진입점
├── requirements.txt # Python 의존성
├── Dockerfile # ARM64 Docker 이미지 설정
├── api/ # API 계층
│ ├── routers/ # 엔드포인트 라우터
│ │ ├── chatbot.py # 챗봇 관련 API
│ │ ├── chatbot_wordset.py # 말투셋 관리 API
│ │ ├── chat_history.py # 대화 기록 API
│ │ └── dit.py # DIT 관련 API
│ ├── schemas/ # Pydantic 스키마 (요청/응답)
│ └── depends/ # 의존성 주입
├── app/ # 비즈니스 로직 계층
│ ├── chatbot/ # 챗봇 서비스
│ ├── chatbot_wordset/ # 말투셋 서비스
│ ├── chat_history/ # 대화 기록 서비스
│ └── dit/ # DIT 서비스
├── core/ # 핵심 인프라
│ ├── db/ # 데이터베이스 설정
│ ├── exceptions/ # 커스텀 예외
│ ├── grpcs/ # gRPC 클라이언트
│ ├── events/ # 이벤트 발행/처리
│ ├── embedder/ # 임베딩 생성
│ ├── vectorstores/ # 벡터 저장소 연동
│ ├── sessions/ # 세션 관리
│ ├── loader/ # 데이터 로더
│ └── util/ # 유틸리티
├── ai/ # AI 관련
│ ├── character_chat_bot.py # 캐릭터 챗봇 구현
│ ├── llm.py # LLM 래퍼
│ ├── memory/ # 대화 메모리
│ └── callbacks/ # LangChain 콜백
├── protos/ # gRPC protobuf 정의
└── avro/ # Avro 스키마
```

Comment on lines +47 to +83
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

코드 블록에 언어 식별자 추가 필요

Line 47의 fenced 코드 블록에 언어 식별자가 누락되어 있습니다.

다음과 같이 수정하세요:

-```
+```text
 FastAPIProject/
 ├── main.py              # FastAPI 앱 진입점
🧰 Tools
🪛 markdownlint-cli2 (0.18.1)

47-47: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🤖 Prompt for AI Agents
.serena/memories/project_overview.md around lines 47 to 83: the fenced code
block showing the project tree is missing a language identifier; update the
opening fence from ``` to ```text so the block is tagged as plain text (i.e.,
replace the opening backticks with ```text and leave the rest of the block
unchanged).

## 아키텍처 패턴

### 계층 구조
1. **API 계층** (`api/`): FastAPI 라우터, 스키마, 의존성 주입
2. **서비스 계층** (`app/`): 비즈니스 로직
3. **인프라 계층** (`core/`): DB, gRPC, 이벤트 등 인프라 관심사

### 설계 패턴
- **의존성 주입**: FastAPI의 Depends를 통한 DI
- **Repository 패턴**: 데이터 액세스 추상화
- **Event-Driven Architecture**: Kafka를 통한 비동기 이벤트 처리
- **Microservices**: gRPC를 통한 서비스 간 통신

## 환경 설정
- 환경 변수는 `.env` 파일로 관리
- CORS 설정: localhost:5173, 10.200.139.219:5173 허용
- MongoDB 연결은 앱 lifespan에서 관리 (init/close)
158 changes: 158 additions & 0 deletions .serena/memories/suggested_commands.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
# Suggested Commands

## 개발 환경 설정

### 가상환경 생성 및 활성화
```bash
python3 -m venv .venv
source .venv/bin/activate # macOS/Linux
```

### 의존성 설치
```bash
pip install -r requirements.txt
```

## 실행 명령어

### 로컬 개발 서버 실행
```bash
# 방법 1: uvicorn 직접 실행
uvicorn main:app --host 0.0.0.0 --port 4449

# 방법 2: 리로드 모드 (개발용)
uvicorn main:app --host 0.0.0.0 --port 4449 --reload

# 방법 3: Python으로 직접 실행
python main.py
```

### 서버 접속
- 로컬: http://localhost:4449
- API 문서: http://localhost:4449/docs (Swagger UI)
- ReDoc: http://localhost:4449/redoc

## Docker 명령어

### Docker 이미지 빌드
```bash
# ARM64용 빌드
docker build -t fastapi-project .

# 플랫폼 명시적 지정
docker build --platform linux/arm64 -t fastapi-project .
```

### Docker 컨테이너 실행
```bash
# 기본 실행
docker run -p 4449:4449 fastapi-project

# 환경 변수 포함
docker run -p 4449:4449 --env-file .env fastapi-project

# 백그라운드 실행
docker run -d -p 4449:4449 --name fastapi-app fastapi-project
```

## 테스트

### pytest 실행
```bash
# 모든 테스트 실행
pytest

# 특정 파일 테스트
pytest tests/test_chatbot.py

# 비동기 테스트 (pytest-asyncio 사용)
pytest -v

# 벤치마크 테스트
pytest --benchmark-only
```

## Git 명령어

### 브랜치 관리
```bash
# 현재 브랜치 확인
git branch

# 상태 확인
git status

# 메인 브랜치로 전환
git checkout master

# 새 브랜치 생성 및 전환
git checkout -b feature/new-feature
```

### 커밋 및 푸시
```bash
# 변경사항 스테이징
git add .

# 커밋
git commit -m "feat: 기능 추가"

# 푸시
git push origin <branch-name>
```

## 유틸리티 명령어 (macOS)

### 파일 검색
```bash
# 파일 찾기
find . -name "*.py"

# 특정 내용 검색
grep -r "pattern" .

# 파일 목록
ls -la
```

### 프로세스 관리
```bash
# 포트 사용 확인
lsof -i :4449

# 프로세스 종료
kill -9 <PID>
```

### Python 관련
```bash
# Python 버전 확인
python --version

# 패키지 설치
pip install <package-name>

# 설치된 패키지 목록
pip list

# requirements.txt 생성
pip freeze > requirements.txt
```

## gRPC 관련

### Protobuf 컴파일
```bash
# proto 파일에서 Python 코드 생성
python -m grpc_tools.protoc -I./protos --python_out=. --grpc_python_out=. ./protos/*.proto
```

## 데이터베이스

### MongoDB
- 연결은 앱 시작 시 자동으로 처리됨 (환경 변수 필요)
- Beanie를 통해 ODM 방식으로 접근

## 환경 변수
- `.env` 파일에 환경 변수 설정 필요
- 주요 환경 변수: MongoDB URI, Redis URI, OpenAI API Key, Pinecone API Key 등
Loading