File size: 2,425 Bytes
6c2ddf8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
"""
Supabase 데이터베이스 연동 모듈
- 문서 저장 및 검색
- 벡터 유사도 검색 (pgvector)
"""

from supabase import create_client
from config import SUPABASE_URL, SUPABASE_KEY
from typing import List, Dict, Optional

# Supabase 클라이언트 초기화
supabase = create_client(SUPABASE_URL, SUPABASE_KEY) if SUPABASE_URL and SUPABASE_KEY else None


def save_document(title: str, content: str, embedding: List[float], category: str = "일반") -> bool:
    """문서를 데이터베이스에 저장"""
    if not supabase:
        return False

    try:
        supabase.table("documents").insert({
            "title": title,
            "content": content,
            "embedding": embedding,
            "category": category
        }).execute()
        return True
    except Exception as e:
        print(f"문서 저장 오류: {e}")
        return False


def search_documents(query_embedding: List[float], top_k: int = 3) -> List[Dict]:
    """벡터 유사도 기반 문서 검색"""
    if not supabase:
        return []

    try:
        # Supabase RPC 함수 호출 (pgvector 유사도 검색)
        result = supabase.rpc(
            "match_documents",
            {
                "query_embedding": query_embedding,
                "match_count": top_k
            }
        ).execute()
        return result.data if result.data else []
    except Exception as e:
        print(f"문서 검색 오류: {e}")
        return []


def get_all_documents(category: Optional[str] = None) -> List[Dict]:
    """모든 문서 조회"""
    if not supabase:
        return []

    try:
        query = supabase.table("documents").select("id, title, content, category")
        if category:
            query = query.eq("category", category)
        result = query.execute()
        return result.data if result.data else []
    except Exception as e:
        print(f"문서 조회 오류: {e}")
        return []


def save_chat_history(user_message: str, bot_response: str, session_id: str) -> bool:
    """채팅 기록 저장"""
    if not supabase:
        return False

    try:
        supabase.table("chat_history").insert({
            "session_id": session_id,
            "user_message": user_message,
            "bot_response": bot_response
        }).execute()
        return True
    except Exception as e:
        print(f"채팅 기록 저장 오류: {e}")
        return False