sema-mem0 0.1.0

Store, search, and manage long-term memories for AI agents through the Mem0 platform API

Source

package.sema

242 lines 95a55e795340
File details

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

SHA-256 95a55e795340355b99ce7c7a169a8175c6ea88a8a6b8e7b6eeb385c7c51ff5b0

1;; sema-mem0 — Mem0 memory-layer API client with typed errors
2;;
3;; A client is a plain map built by (mem0/client ...) and passed as the first
4;; argument to every call. Messages go in, memories come out: responses are
5;; JSON-decoded into keyword-keyed maps (or lists of them). Non-2xx statuses
6;; raise an error carrying method, path, status, and the API's own message.
7;; (mem0/request ...) is the raw escape hatch for endpoints the wrappers don't
8;; cover. Every memory belongs to an identity — a :user-id, :agent-id, or
9;; :run-id — supplied through the trailing options map.
10
11(module sema-mem0
12  (export mem0/client
13          mem0/request
14          mem0/add!
15          mem0/search
16          mem0/get-all
17          mem0/delete!)
18
19  ;; -------------------------------------------------------------------------
20  ;; Private: percent-encoding (RFC 3986 unreserved set, UTF-8 for the rest)
21  ;; -------------------------------------------------------------------------
22
23  (define hex-digits "0123456789ABCDEF")
24
25  ;; Byte (0-255) → two uppercase hex digits.
26  (define (hex2 n)
27    (string-append
28      (substring hex-digits (floor (/ n 16)) (+ (floor (/ n 16)) 1))
29      (substring hex-digits (mod n 16) (+ (mod n 16) 1))))
30
31  ;; Unicode codepoint → list of UTF-8 byte values.
32  (define (utf8-bytes cp)
33    (cond
34      ((< cp 128) (list cp))
35      ((< cp 2048)
36       (list (+ 192 (floor (/ cp 64)))
37             (+ 128 (mod cp 64))))
38      ((< cp 65536)
39       (list (+ 224 (floor (/ cp 4096)))
40             (+ 128 (mod (floor (/ cp 64)) 64))
41             (+ 128 (mod cp 64))))
42      (#t
43       (list (+ 240 (floor (/ cp 262144)))
44             (+ 128 (mod (floor (/ cp 4096)) 64))
45             (+ 128 (mod (floor (/ cp 64)) 64))
46             (+ 128 (mod cp 64))))))
47
48  ;; RFC 3986 unreserved: ALPHA / DIGIT / "-" / "." / "_" / "~"
49  (define (unreserved? cp)
50    (or (and (>= cp 48) (<= cp 57))
51        (and (>= cp 65) (<= cp 90))
52        (and (>= cp 97) (<= cp 122))
53        (= cp 45) (= cp 46) (= cp 95) (= cp 126)))
54
55  (define (percent-encode s)
56    (string/join
57      (map (fn (cp)
58             (if (unreserved? cp)
59               (string/from-codepoints (list cp))
60               (string/join
61                 (map (fn (b) (string-append "%" (hex2 b))) (utf8-bytes cp))
62                 "")))
63           (string/codepoints s))
64      ""))
65
66  (define (key->string k)
67    (cond
68      ((keyword? k) (keyword/to-string k))
69      ((string? k) k)
70      (#t (str k))))
71
72  (define (val->string v)
73    (cond
74      ((string? v) v)
75      ((equal? v #t) "true")
76      ((equal? v #f) "false")
77      (#t (str v))))
78
79  ;; Build a percent-encoded query string (no leading ?) from a map, skipping
80  ;; keys whose value is nil. nil or an empty map yields "".
81  (define (query-string params)
82    (if (or (nil? params) (empty? (keys params)))
83      ""
84      (string/join
85        (map (fn (k)
86               (string-append (percent-encode (key->string k))
87                              "="
88                              (percent-encode (val->string (get params k)))))
89             (filter (fn (k) (not (nil? (get params k)))) (keys params)))
90        "&")))
91
92  ;; -------------------------------------------------------------------------
93  ;; Client
94  ;; -------------------------------------------------------------------------
95
96  (define (mem0/client . opts)
97    "Build a Mem0 API client map. Options: :api-key (default: MEM0_API_KEY env var), :base-url (default \"https://api.mem0.ai\"), :timeout in ms (default 30000). Errors if no API key is found."
98    (let* ((o (if (null? opts) {} (first opts)))
99           (api-key (or (get o :api-key) (env "MEM0_API_KEY"))))
100      (when (nil? api-key)
101        (error "mem0/client: no API key found — pass {:api-key \"...\"} or set the MEM0_API_KEY environment variable"))
102      {:api-key api-key
103       :base-url (string/chop-end (get o :base-url "https://api.mem0.ai") "/")
104       :timeout (get o :timeout 30000)}))
105
106  ;; -------------------------------------------------------------------------
107  ;; Private: request plumbing
108  ;; -------------------------------------------------------------------------
109
110  (define (client-headers client)
111    {"Authorization" (string-append "Token " (get client :api-key))
112     "Accept" "application/json"})
113
114  ;; Path may be an API path ("/v1/memories/") or a full URL.
115  (define (build-url client path query)
116    (let* ((base (if (string/starts-with? path "http")
117                   path
118                   (string-append (get client :base-url)
119                                  (string/ensure-start path "/"))))
120           (qs (query-string query)))
121      (if (string/empty? qs)
122        base
123        (string-append base (if (string/contains? base "?") "&" "?") qs))))
124
125  ;; Best error message we can extract from a failed response body.
126  (define (api-error-message body)
127    (let ((decoded (try (json/decode body) (catch e nil))))
128      (if (map? decoded)
129        (or (get decoded :detail)
130            (get decoded :message)
131            (get decoded :error)
132            (string/take (string/trim body) 200))
133        (string/take (string/trim body) 200))))
134
135  (define (decode-body body)
136    (if (or (nil? body) (string/empty? (string/trim body)))
137      {}
138      (json/decode body)))
139
140  ;; -------------------------------------------------------------------------
141  ;; Escape hatch
142  ;; -------------------------------------------------------------------------
143
144  (define (mem0/request client method path body)
145    "Make a raw Mem0 API request. method is \"GET\"/\"POST\"/\"DELETE\"/...; path an API path (\"/v1/memories/\") or full URL; body a map (auto-JSON) or nil. Returns the decoded JSON body ({} when empty); raises on non-2xx with method, path, status, and the API's message."
146    (let* ((url (build-url client path nil))
147           (opts {:headers (client-headers client) :timeout (get client :timeout)})
148           (resp (if (nil? body)
149                   (http/request method url opts)
150                   (http/request method url opts body)))
151           (status (get resp :status)))
152      (if (and (>= status 200) (< status 300))
153        (decode-body (get resp :body))
154        (error (format "mem0: ~a ~a → ~a: ~a"
155                       method path status (api-error-message (get resp :body)))))))
156
157  ;; -------------------------------------------------------------------------
158  ;; Private: identity + option shaping
159  ;; -------------------------------------------------------------------------
160
161  ;; Pull the identity keys from an options map into API-named string keys.
162  ;; :user-id → :user_id, :agent-id → :agent_id, :run-id → :run_id, :app-id → :app_id.
163  (define (identity-fields o)
164    (foldl
165      (fn (acc pair)
166        (let ((v (get o (first pair))))
167          (if (nil? v) acc (assoc acc (last pair) v))))
168      {}
169      (list (list :user-id :user_id)
170            (list :agent-id :agent_id)
171            (list :run-id :run_id)
172            (list :app-id :app_id))))
173
174  (define (has-identity? m)
175    (not (empty? (keys m))))
176
177  ;; A string, or a list of {:role :content} maps, into the messages array.
178  (define (normalize-messages messages)
179    (cond
180      ((string? messages)
181       (if (string/empty? (string/trim messages))
182         (error "mem0/add!: messages string is empty — pass some text to remember")
183         (list {:role "user" :content messages})))
184      ((list? messages)
185       (if (empty? messages)
186         (error "mem0/add!: messages list is empty — pass at least one {:role :content} map")
187         messages))
188      (#t (error "mem0/add!: messages must be a string or a list of {:role :content} maps"))))
189
190  ;; -------------------------------------------------------------------------
191  ;; Memories
192  ;; -------------------------------------------------------------------------
193
194  (define (mem0/add! client messages . opts)
195    "Store memories extracted from messages. messages is a plain string (stored as one user message) or a list of {:role :content} maps. Options require at least one identity — :user-id, :agent-id, or :run-id — and may include :metadata (map) and :infer (bool, default true; false stores text verbatim). Returns the decoded add result."
196    (let* ((o (if (null? opts) {} (first opts)))
197           (ids (identity-fields o)))
198      (when (not (has-identity? ids))
199        (error "mem0/add!: no identity — pass :user-id, :agent-id, or :run-id in the options map"))
200      (let* ((base (assoc ids :messages (normalize-messages messages)))
201             (with-meta (if (nil? (get o :metadata))
202                          base
203                          (assoc base :metadata (get o :metadata))))
204             (body (if (nil? (get o :infer))
205                     with-meta
206                     (assoc with-meta :infer (get o :infer)))))
207        (mem0/request client "POST" "/v1/memories/" body))))
208
209  (define (mem0/search client query . opts)
210    "Search stored memories by relevance to query. Options require an identity — :user-id, :agent-id, or :run-id — or an explicit :filters map, plus optional :top-k (result count) and :threshold (min relevance score). Returns the decoded search result."
211    (when (or (not (string? query)) (string/empty? (string/trim query)))
212      (error "mem0/search: query must be a non-empty string"))
213    (let* ((o (if (null? opts) {} (first opts)))
214           (filters (or (get o :filters) (identity-fields o))))
215      (when (or (nil? filters) (empty? (keys filters)))
216        (error "mem0/search: no filters — pass :user-id, :agent-id, :run-id, or an explicit :filters map"))
217      (let* ((base {:query query :filters filters})
218             (with-topk (if (nil? (get o :top-k))
219                          base
220                          (assoc base :top_k (get o :top-k))))
221             (body (if (nil? (get o :threshold))
222                     with-topk
223                     (assoc with-topk :threshold (get o :threshold)))))
224        (mem0/request client "POST" "/v2/memories/search/" body))))
225
226  (define (mem0/get-all client . opts)
227    "List all stored memories for an identity. Options require an identity — :user-id, :agent-id, or :run-id — and may include :page and :page-size for pagination. Returns the decoded list result."
228    (let* ((o (if (null? opts) {} (first opts)))
229           (ids (identity-fields o)))
230      (when (not (has-identity? ids))
231        (error "mem0/get-all: no identity — pass :user-id, :agent-id, or :run-id in the options map"))
232      (let* ((params (assoc ids :page (get o :page) :page_size (get o :page-size)))
233             (path (build-url client "/v1/memories/" params)))
234        (mem0/request client "GET" path nil))))
235
236  (define (mem0/delete! client memory-id)
237    "Delete a single memory by its id. Returns the decoded confirmation."
238    (when (or (not (string? memory-id)) (string/empty? (string/trim memory-id)))
239      (error "mem0/delete!: memory-id must be a non-empty string"))
240    (mem0/request client "DELETE"
241                  (string-append "/v1/memories/" (percent-encode memory-id) "/")
242                  nil)))