File size: 2,943 Bytes
fbf3c28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
"""
id: memory_qdrant
title: Qdrant Memory (HTTP)
author: system
description: Minimal Qdrant upsert/query via HTTP for Nova memory.
version: 0.1.0
"""

import json
from typing import List, Dict, Any, Optional
import urllib.request


def _http(method: str, url: str, data: Optional[bytes] = None, headers: Optional[dict] = None) -> dict:
    headers = headers or {}
    req = urllib.request.Request(url, data=data, headers=headers, method=method)
    try:
        with urllib.request.urlopen(req, timeout=10) as resp:
            body = resp.read()
            txt = body.decode("utf-8") if body else ""
            try:
                return {"status": resp.status, "json": json.loads(txt)}
            except Exception:
                return {"status": resp.status, "text": txt}
    except Exception as e:
        return {"error": str(e)}


class Tools:
    def __init__(self):
        pass

    def ensure_collection(
        self,
        collection: str,
        size: int,
        distance: str = "Cosine",
        url: str = "http://127.0.0.1:17000",
    ) -> dict:
        """
        Ensure a Qdrant collection exists.
        :param collection: Collection name
        :param size: Vector size (dimension)
        :param distance: Distance metric (Cosine, Euclid, Dot)
        :param url: Qdrant HTTP URL
        """
        payload = {
            "vectors": {"size": size, "distance": distance},
            "optimizers_config": {"default_segment_number": 1},
        }
        return _http(
            "PUT",
            f"{url}/collections/{collection}",
            data=json.dumps(payload).encode("utf-8"),
            headers={"Content-Type": "application/json"},
        )

    def upsert(
        self,
        collection: str,
        points: List[Dict[str, Any]],
        url: str = "http://127.0.0.1:17000",
    ) -> dict:
        """
        Upsert points into Qdrant.
        :param collection: Collection name
        :param points: List of {id, vector, payload}
        :param url: Qdrant HTTP URL
        """
        payload = {"points": points}
        return _http(
            "PUT",
            f"{url}/collections/{collection}/points?wait=true",
            data=json.dumps(payload).encode("utf-8"),
            headers={"Content-Type": "application/json"},
        )

    def query(
        self,
        collection: str,
        vector: List[float],
        top: int = 5,
        url: str = "http://127.0.0.1:17000",
    ) -> dict:
        """
        Query nearest neighbors.
        :param collection: Collection name
        :param vector: Query vector
        :param top: Top-k
        :param url: Qdrant HTTP URL
        """
        payload = {"vector": vector, "limit": top}
        return _http(
            "POST",
            f"{url}/collections/{collection}/points/search",
            data=json.dumps(payload).encode("utf-8"),
            headers={"Content-Type": "application/json"},
        )