티스토리 뷰

반응형

🚀 FastAPI 기반 로컬 LLM + RAG 챗봇 만들기 – FastAPI 프로젝트 구조 및 설정

이 글에서는 FastAPI 프로젝트 구조를 설계하고, 환경 변수 설정과 PostgreSQL 연결을 설정하는 과정을 다룹니다.
프로젝트 폴더 구조 → .env 설정 → PostgreSQL 연결 → FastAPI의 Dependency Injection 활용 순서로 진행됩니다.


📌 1. FastAPI 프로젝트 폴더 구조 구성

FastAPI 프로젝트의 구조를 체계적으로 구성하면 유지보수와 확장성이 쉬워집니다.
다음과 같은 폴더 구조를 사용합니다.

fastapi-llm-chatbot/
│── app/
│   ├── api/                # API 라우터 관리
│   │   ├── v1/
│   │   │   ├── endpoints/
│   │   │   │   ├── chat.py  # Ollama와 연결된 챗봇 API
│   │   │   │   ├── search.py  # 문서 검색 API
│   │   │   ├── __init__.py
│   ├── core/              # 핵심 설정 파일 (DB, 환경 변수 등)
│   │   ├── config.py       # 환경 변수 로드
│   │   ├── database.py     # PostgreSQL 연결 설정
│   │   ├── dependencies.py # FastAPI 의존성 관리
│   ├── models/             # 데이터베이스 모델 정의
│   ├── services/           # 비즈니스 로직 처리
│   ├── main.py             # FastAPI 애플리케이션 실행 파일
│── .env                    # 환경 변수 파일 (DB 연결 정보 등)
│── requirements.txt         # Python 패키지 목록
│── README.md                # 프로젝트 설명

이 구조를 사용하면 API, DB, 설정 파일을 논리적으로 분리하여 유지보수가 쉬워집니다.


📌 2. .env 파일을 활용한 환경 변수 설정

반응형

프로젝트에서 PostgreSQL 연결 정보, API 키 등 민감한 데이터를 안전하게 관리하려면 .env 파일을 사용해야 합니다.
📌 .env 파일을 생성하고 아래 내용을 추가합니다.

# PostgreSQL 설정
DATABASE_URL=postgresql://admin:password@localhost:5432/rag_db

# Ollama API 설정
OLLAMA_API_URL=http://localhost:11434/api/generate

# FastAPI 기본 설정
APP_NAME=FastAPI LLM Chatbot
APP_VERSION=1.0.0
DEBUG=True

1️⃣ python-dotenv 라이브러리 설치

환경 변수를 로드하려면 python-dotenv 패키지가 필요합니다.
설치하지 않았다면 아래 명령어를 실행하세요.

pip install python-dotenv

2️⃣ 환경 변수 로드 (config.py 설정)

app/core/config.py 파일을 생성하고 .env 값을 불러옵니다.

import os
from dotenv import load_dotenv

# .env 파일 로드
load_dotenv()

class Settings:
    DATABASE_URL: str = os.getenv("DATABASE_URL")
    OLLAMA_API_URL: str = os.getenv("OLLAMA_API_URL")
    APP_NAME: str = os.getenv("APP_NAME", "FastAPI LLM Chatbot")
    APP_VERSION: str = os.getenv("APP_VERSION", "1.0.0")
    DEBUG: bool = os.getenv("DEBUG", "False").lower() == "true"

settings = Settings()

이제 settings.DATABASE_URL 등으로 환경 변수를 사용할 수 있습니다! 🚀


📌 3. PostgreSQL 연결 설정 (database.py)

1️⃣ database.py 생성 (app/core/database.py)

PostgreSQL에 연결하는 코드를 작성합니다.

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base
from app.core.config import settings

# 데이터베이스 엔진 생성
engine = create_engine(settings.DATABASE_URL)

# 세션 팩토리 생성
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# Base 클래스 생성 (모든 모델이 이 클래스를 상속받음)
Base = declarative_base()

# DB 세션 종속성 함수
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

get_db()를 사용하여 API 핸들러에서 DB 세션을 주입할 수 있습니다.


📌 4. FastAPI의 Dependency Injection 활용

FastAPI에서는 Dependency Injection을 사용하여 데이터베이스 세션을 API 핸들러에 주입할 수 있습니다.

📌 예제: FastAPI에서 get_db()를 사용하는 API (chat.py)

from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app.core.database import get_db

router = APIRouter()

@router.get("/test-db")
async def test_db_connection(db: Session = Depends(get_db)):
    return {"message": "Database connection successful!"}

이제 API에서 db: Session = Depends(get_db)를 사용하여 DB 세션을 활용할 수 있습니다!


📌 5. main.py에서 FastAPI 실행

main.py를 생성하고 FastAPI 애플리케이션을 실행합니다.

from fastapi import FastAPI
from app.api.v1.endpoints import chat

app = FastAPI(title="FastAPI LLM Chatbot")

# 라우터 등록
app.include_router(chat.router, prefix="/api/v1", tags=["chat"])

@app.get("/")
async def root():
    return {"message": "FastAPI LLM Chatbot is running!"}

이제 FastAPI 서버를 실행하면 http://localhost:8000에서 API가 작동합니다!


📌 6. FastAPI 서버 실행 및 테스트

1️⃣ FastAPI 서버 실행

uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload

2️⃣ API 테스트 (curl 또는 브라우저 사용)

curl -X GET "http://localhost:8000/"

✅ 정상적으로 실행되었다면 다음과 같은 JSON 응답이 반환됩니다.

{"message": "FastAPI LLM Chatbot is running!"}

📌 7. 오류 해결 및 디버깅

🔥 1️⃣ ModuleNotFoundError: No module named 'app.core.config' 오류

원인: PYTHONPATH 설정이 필요함
해결 방법:

export PYTHONPATH=$PWD

🔥 2️⃣ sqlalchemy.exc.OperationalError: could not connect to server 오류

원인: PostgreSQL이 실행되지 않음
해결 방법: PostgreSQL 서버를 실행

sudo service postgresql start  # Ubuntu
brew services start postgresql  # macOS

📌 8. 결론 및 다음 단계

FastAPI 프로젝트 폴더 구조를 정리하고, .env 환경 변수와 PostgreSQL을 설정 완료!
FastAPI에서 Dependency Injection을 활용하여 DB 세션을 주입하는 방법을 학습!
FastAPI 서버 실행 및 API 테스트 완료! 🚀

🚀 다음 글에서는 FastAPI를 활용하여 Ollama의 LLaMA3 모델을 API 형태로 호출하는 방법을 설명합니다!

 

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
글 보관함
반응형