File size: 937 Bytes
99b596a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import chromadb

CHROMA_PATH = "./chroma_db"
COLLECTION_NAME = "smartstudy_docs"


def get_chroma_client():
    return chromadb.PersistentClient(path=CHROMA_PATH)


def get_collection():
    client = get_chroma_client()
    return client.get_or_create_collection(
        name=COLLECTION_NAME,
        metadata={"hnsw:space": "cosine"}
    )


def add_documents(chunks: list, metadatas: list, ids: list):
    collection = get_collection()
    collection.add(documents=chunks, metadatas=metadatas, ids=ids)


def query_documents(query: str, n_results: int = 4) -> dict:
    collection = get_collection()
    count = collection.count()
    if count == 0:
        return {"documents": [[]], "metadatas": [[]], "distances": [[]]}
    actual_n = min(n_results, count)
    return collection.query(query_texts=[query], n_results=actual_n)


def delete_collection():
    client = get_chroma_client()
    client.delete_collection(COLLECTION_NAME)