File size: 2,266 Bytes
1c29d49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import requests
from dotenv import load_dotenv

load_dotenv()

QDRANT_URL = os.getenv("QDRANT_URL")
QDRANT_API_KEY = os.getenv("QDRANT_API_KEY")
COLLECTION_NAME = "physical_ai_textbook"

if not QDRANT_URL or not QDRANT_API_KEY:
    raise ValueError("QDRANT_URL and QDRANT_API_KEY must be set in the .env file")

# Ensure URL doesn't end with slash + handle if user put "https://" or not
if not QDRANT_URL.startswith("http"):
    QDRANT_URL = f"https://{QDRANT_URL}"
QDRANT_URL = QDRANT_URL.rstrip("/")

HEADERS = {
    "api-key": QDRANT_API_KEY,
    "Content-Type": "application/json"
}

def init_db():
    """

    Initializes the Qdrant collection via REST API.

    """
    # Check if collection exists
    check_url = f"{QDRANT_URL}/collections/{COLLECTION_NAME}"
    response = requests.get(check_url, headers=HEADERS)

    if response.status_code == 200:
        print(f"Collection {COLLECTION_NAME} already exists.")
    else:
        print(f"Creating collection: {COLLECTION_NAME}")
        # Create collection
        create_url = f"{QDRANT_URL}/collections/{COLLECTION_NAME}"
        payload = {
            "vectors": {
                "size": 768,
                "distance": "Cosine"
            }
        }
        resp = requests.put(create_url, headers=HEADERS, json=payload)
        if resp.status_code == 200:
            print("Collection created successfully.")
        else:
            print(f"Error creating collection: {resp.text}")

def search_points(vector, limit=5):
    url = f"{QDRANT_URL}/collections/{COLLECTION_NAME}/points/search"
    payload = {
        "vector": vector,
        "limit": limit,
        "with_payload": True
    }
    response = requests.post(url, headers=HEADERS, json=payload)
    if response.status_code == 200:
        return response.json().get("result", [])
    else:
        print(f"Search Error: {response.text}")
        return []

def upsert_points(points):
    url = f"{QDRANT_URL}/collections/{COLLECTION_NAME}/points?wait=true"
    payload = {
        "points": points
    }
    response = requests.put(url, headers=HEADERS, json=payload)
    if response.status_code != 200:
        print(f"Upsert Error: {response.text}")