File size: 1,034 Bytes
b1955dd
8492855
b1955dd
 
8492855
 
 
b1955dd
 
 
 
 
 
 
 
 
8492855
 
b1955dd
 
 
 
8492855
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import chromadb
import os
from chromadb.utils import embedding_functions

# Tạo thư mục lưu data nếu chưa có
os.makedirs("./chroma_db", exist_ok=True)

chroma_client = chromadb.PersistentClient(path="./chroma_db")
embedding_func = embedding_functions.SentenceTransformerEmbeddingFunction(model_name="all-MiniLM-L6-v2")
collection = chroma_client.get_or_create_collection(name="knowledge_base", embedding_function=embedding_func)

def add_vector(doc_id, category, content):
    collection.add(documents=[content], metadatas=[{"category": category}], ids=[doc_id])

def search(query):
    try:
        # Tăng n_results lên để có nhiều ngữ cảnh hơn cho AI
        results = collection.query(query_texts=[query], n_results=3)
        if results['documents'] and results['documents'][0]:
            return "\n- ".join(results['documents'][0])
        return "Không tìm thấy thông tin nào liên quan."
    except Exception as e:
        return "" # Trả về rỗng để AI tự xử lý nếu lỗi database