Spaces:
Paused
Paused
Download vector_store.py from phanquocdat123/Ai_Agent: direct link, hf CLI and curl.
- Browser
- Download file 1.03 kB
-
https://huggingface.co/spaces/phanquocdat123/Ai_Agent/resolve/main/vector_store.py
- Command line
-
hf download hf://spaces/phanquocdat123/Ai_Agent/vector_store.py
-
curl -L -o vector_store.py https://huggingface.co/spaces/phanquocdat123/Ai_Agent/resolve/main/vector_store.py
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 |