Ai_Agent / vector_store.py
phanquocdat123's picture
Update vector_store.py
8492855 verified
Raw History Blame Contribute Delete
1.03 kB
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