sema-upstash-vector 0.1.0

Store and search vector embeddings in an Upstash Vector database over its REST API

Source

package.sema

184 lines 92c1875a2691
File details

Source stored with sema-upstash-vector 0.1.0. Line links refer to these exact bytes.

SHA-256 92c1875a269138f865ed3f35becbdf906560108e669112b61ef7f989e683ef50

1;; sema-upstash-vector — Upstash Vector database client over its REST API
2;;
3;; A client is a plain map built by (upstash-vector/client ...) and passed as
4;; the first argument to every call. Upstash wraps every successful response in
5;; {:result ...}; the wrappers here return the :result payload. Non-2xx
6;; responses raise an error carrying method, path, status, and Upstash's own
7;; error message. (upstash-vector/request ...) is the raw escape hatch for
8;; endpoints the wrappers don't cover.
9;;
10;; Namespaces are addressed by appending the namespace to the path
11;; (e.g. /query/my-namespace); the default namespace is the empty string.
12
13(module sema-upstash-vector
14  (export upstash-vector/client
15          upstash-vector/request
16          upstash-vector/upsert!
17          upstash-vector/query
18          upstash-vector/fetch
19          upstash-vector/delete!
20          upstash-vector/info
21          upstash-vector/reset!)
22
23  ;; -------------------------------------------------------------------------
24  ;; Private: percent-encoding for path segments (RFC 3986 unreserved set)
25  ;; -------------------------------------------------------------------------
26
27  (define hex-digits "0123456789ABCDEF")
28
29  (define (hex2 n)
30    (string-append
31      (substring hex-digits (floor (/ n 16)) (+ (floor (/ n 16)) 1))
32      (substring hex-digits (mod n 16) (+ (mod n 16) 1))))
33
34  (define (utf8-bytes cp)
35    (cond
36      ((< cp 128) (list cp))
37      ((< cp 2048)
38       (list (+ 192 (floor (/ cp 64)))
39             (+ 128 (mod cp 64))))
40      ((< cp 65536)
41       (list (+ 224 (floor (/ cp 4096)))
42             (+ 128 (mod (floor (/ cp 64)) 64))
43             (+ 128 (mod cp 64))))
44      (#t
45       (list (+ 240 (floor (/ cp 262144)))
46             (+ 128 (mod (floor (/ cp 4096)) 64))
47             (+ 128 (mod (floor (/ cp 64)) 64))
48             (+ 128 (mod cp 64))))))
49
50  ;; RFC 3986 unreserved: ALPHA / DIGIT / "-" / "." / "_" / "~"
51  (define (unreserved? cp)
52    (or (and (>= cp 48) (<= cp 57))
53        (and (>= cp 65) (<= cp 90))
54        (and (>= cp 97) (<= cp 122))
55        (= cp 45) (= cp 46) (= cp 95) (= cp 126)))
56
57  (define (percent-encode s)
58    (string/join
59      (map (fn (cp)
60             (if (unreserved? cp)
61               (string/from-codepoints (list cp))
62               (string/join
63                 (map (fn (b) (string-append "%" (hex2 b))) (utf8-bytes cp))
64                 "")))
65           (string/codepoints s))
66      ""))
67
68  ;; -------------------------------------------------------------------------
69  ;; Client
70  ;; -------------------------------------------------------------------------
71
72  (define (upstash-vector/client . opts)
73    "Build an Upstash Vector client map. Options: :url (default: UPSTASH_VECTOR_REST_URL env var — your index REST URL), :token (default: UPSTASH_VECTOR_REST_TOKEN env var), :timeout in ms (default 30000). Errors if the URL or token is missing."
74    (let* ((o (if (null? opts) {} (first opts)))
75           (url (or (get o :url) (env "UPSTASH_VECTOR_REST_URL")))
76           (token (or (get o :token) (env "UPSTASH_VECTOR_REST_TOKEN"))))
77      (when (or (nil? url) (and (string? url) (string/empty? (string/trim url))))
78        (error "upstash-vector/client: no url — pass {:url \"https://xxx.upstash.io\"} or set the UPSTASH_VECTOR_REST_URL environment variable"))
79      (when (nil? token)
80        (error "upstash-vector/client: no token — pass {:token \"...\"} or set the UPSTASH_VECTOR_REST_TOKEN environment variable"))
81      {:url (string/chop-end url "/")
82       :token token
83       :timeout (get o :timeout 30000)}))
84
85  ;; -------------------------------------------------------------------------
86  ;; Private: request plumbing
87  ;; -------------------------------------------------------------------------
88
89  (define (client-headers client)
90    {"Authorization" (string-append "Bearer " (:token client))
91     "Content-Type" "application/json"})
92
93  (define (build-url client path)
94    (string-append (:url client) (string/ensure-start path "/")))
95
96  ;; Append a namespace to an endpoint path; empty namespace = default namespace.
97  (define (ns-path base namespace)
98    (if (or (nil? namespace)
99            (and (string? namespace) (string/empty? (string/trim namespace))))
100      base
101      (string-append base "/" (percent-encode namespace))))
102
103  ;; Upstash errors look like {:error "..." :status 422}.
104  (define (api-error-message body)
105    (let ((decoded (try (json/decode body) (catch e nil))))
106      (if (map? decoded)
107        (let ((err (get decoded :error)))
108          (if (string? err)
109            err
110            (string/take (string/trim (or body "")) 200)))
111        (string/take (string/trim (or body "")) 200))))
112
113  (define (decode-body body)
114    (if (or (nil? body) (string/empty? (string/trim body)))
115      {}
116      (json/decode body)))
117
118  ;; -------------------------------------------------------------------------
119  ;; Escape hatch
120  ;; -------------------------------------------------------------------------
121
122  (define (upstash-vector/request client method path body)
123    "Make a raw Upstash Vector request. method is \"GET\"/\"POST\"/\"DELETE\", path an API path (\"/query\", \"/upsert/my-namespace\"). body is a map/list (sent as JSON) or nil. Returns the full decoded response map ({:result ...}); raises on non-2xx."
124    (let* ((url (build-url client path))
125           (opts {:headers (client-headers client) :timeout (:timeout client)})
126           (resp (if (nil? body)
127                   (http/request method url opts)
128                   (http/request method url opts body)))
129           (status (:status resp)))
130      (if (and (>= status 200) (< status 300))
131        (decode-body (:body resp))
132        (error (format "upstash-vector: ~a ~a → ~a: ~a"
133                       method path status (api-error-message (:body resp)))))))
134
135  (define (result client method path body)
136    (get (upstash-vector/request client method path body) :result))
137
138  ;; -------------------------------------------------------------------------
139  ;; Vectors
140  ;; -------------------------------------------------------------------------
141
142  (define (upstash-vector/upsert! client vectors . opts)
143    "Insert or overwrite vectors. vectors is a map, or a list of maps, each with :id, :vector, and optional :metadata / :data. opts: :namespace (default \"\"). Returns Upstash's result (\"Success\")."
144    (let* ((o (if (null? opts) {} (first opts)))
145           (path (ns-path "/upsert" (get o :namespace ""))))
146      (result client "POST" path vectors)))
147
148  (define (upstash-vector/query client vector . opts)
149    "Query for the nearest vectors to vector (a list of numbers). opts: :top-k (default 10), :include-metadata (default #t), :include-vectors (default #f), :include-data (default #f), :filter (a metadata filter string), :namespace (default \"\"). Returns a list of matches ({:id ... :score ... :metadata ...})."
150    (let* ((o (if (null? opts) {} (first opts)))
151           (body0 {:vector vector
152                   :topK (get o :top-k 10)
153                   :includeMetadata (get o :include-metadata #t)
154                   :includeVectors (get o :include-vectors #f)
155                   :includeData (get o :include-data #f)})
156           (body (if (contains? o :filter) (assoc body0 :filter (get o :filter)) body0))
157           (path (ns-path "/query" (get o :namespace ""))))
158      (result client "POST" path body)))
159
160  (define (upstash-vector/fetch client ids . opts)
161    "Fetch vectors by id. ids is a list of ids (strings or numbers). opts: :include-metadata (default #t), :include-vectors (default #f), :include-data (default #f), :namespace (default \"\"). Returns a list of vectors (nil entries for ids not found)."
162    (let* ((o (if (null? opts) {} (first opts)))
163           (body {:ids ids
164                  :includeMetadata (get o :include-metadata #t)
165                  :includeVectors (get o :include-vectors #f)
166                  :includeData (get o :include-data #f)})
167           (path (ns-path "/fetch" (get o :namespace ""))))
168      (result client "POST" path body)))
169
170  (define (upstash-vector/delete! client ids . opts)
171    "Delete vectors by id. ids is a list of ids (strings or numbers). opts: :namespace (default \"\"). Returns a map with the number deleted ({:deleted N})."
172    (let* ((o (if (null? opts) {} (first opts)))
173           (path (ns-path "/delete" (get o :namespace ""))))
174      (result client "DELETE" path {:ids ids})))
175
176  (define (upstash-vector/info client)
177    "Return index stats: vector count, pending count, dimension, similarity function, and per-namespace details."
178    (result client "GET" "/info" nil))
179
180  (define (upstash-vector/reset! client . opts)
181    "Delete every vector in a namespace. opts: :namespace (default \"\" = the default namespace). Returns \"Success\". Irreversible."
182    (let* ((o (if (null? opts) {} (first opts)))
183           (path (ns-path "/reset" (get o :namespace ""))))
184      (result client "POST" path nil))))