oliviadb 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ Metadata-Version: 2.4
2
+ Name: oliviadb
3
+ Version: 0.1.0
4
+ Summary: Client for OliviaDB's network API: agent memory and layer-1 reads
5
+ License-Expression: Apache-2.0
6
+ Requires-Python: >=3.10
@@ -0,0 +1,15 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ [build-system]
3
+ requires = ["setuptools>=68"]
4
+ build-backend = "setuptools.build_meta"
5
+
6
+ [project]
7
+ name = "oliviadb"
8
+ version = "0.1.0"
9
+ description = "Client for OliviaDB's network API: agent memory and layer-1 reads"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.10"
12
+ dependencies = []
13
+
14
+ [tool.setuptools.packages.find]
15
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,426 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Client for OliviaDB's network API (spec/oliviadb-api.openapi.json): agent memory and layer-1
3
+ reads over HTTPS. Standard library only.
4
+
5
+ from oliviadb import OliviaDbClient
6
+ oliviadb = OliviaDbClient("https://oliviadb.example:8443", token="...") # OAuth access token
7
+ oliviadb = OliviaDbClient("http://127.0.0.1:8080", api_key="dev-key") # development key
8
+ oliviadb.remember(thread="t1", text="Ann works at Acme.", step_id="s1",
9
+ facts=[{"entity": "Ann", "attr": "employer", "value": "Acme"}])
10
+ pack = oliviadb.recall("Where does Ann work?", budget=500)
11
+ print(pack["text"])
12
+
13
+ Request arguments and results are those of the MCP tools of the same name; errors are
14
+ raised as OliviaDbError (an RFC 9457 problem document), retried when the server says they are
15
+ retryable. Transaction times, fact ids and cursors above 2**53 - 1 arrive as decimal
16
+ strings (for clients whose numbers are doubles); ``int(x)`` gives the exact value, and
17
+ arguments take either form.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import http.client
23
+ import json
24
+ import ssl
25
+ import time
26
+ import urllib.error
27
+ import urllib.parse
28
+ import urllib.request
29
+ from collections.abc import Iterator
30
+ from typing import Any, Literal, cast, overload
31
+
32
+ __all__ = ["Event", "OliviaDbClient", "OliviaDbError"]
33
+ __version__ = "0.1.0"
34
+
35
+
36
+ class OliviaDbError(Exception):
37
+ """A problem document returned by the server."""
38
+
39
+ def __init__(self, status: int, problem: dict[str, Any]):
40
+ self.status = status
41
+ self.problem = problem
42
+ self.type = problem.get("type", "")
43
+ self.detail = problem.get("detail", "")
44
+ self.retryable = bool(problem.get("retryable", False))
45
+ super().__init__(f"{status} {self.type}: {self.detail}")
46
+
47
+
48
+ class Event:
49
+ """One change seen by a watch (server-sent event)."""
50
+
51
+ def __init__(self, id: str, data: dict[str, Any]):
52
+ self.id = id
53
+ self.data = data
54
+
55
+ def __repr__(self) -> str:
56
+ return f"Event(id={self.id!r}, data={self.data!r})"
57
+
58
+
59
+ def _clean(d: dict[str, Any]) -> dict[str, Any]:
60
+ return {k: v for k, v in d.items() if v is not None}
61
+
62
+
63
+ def _object(raw: bytes) -> dict[str, Any]:
64
+ """A response body: a JSON object (every answer of the API is one), {} when empty."""
65
+ if not raw:
66
+ return {}
67
+ v = json.loads(raw)
68
+ if not isinstance(v, dict):
69
+ raise ValueError(f"the server answered with JSON that is not an object: {raw[:80]!r}")
70
+ return v
71
+
72
+
73
+ class OliviaDbClient:
74
+ def __init__(
75
+ self,
76
+ base_url: str | list[str],
77
+ *,
78
+ token: str | None = None,
79
+ api_key: str | None = None,
80
+ ca_file: str | None = None,
81
+ timeout: float = 30.0,
82
+ retries: int = 3,
83
+ traceparent: str | None = None,
84
+ ):
85
+ """``base_url``: the server, or the nodes of a high-availability pair (all of them):
86
+ a refused connection or a retryable 503 moves the client to the node the answer
87
+ names as primary (``oliviadb-primary``), else to the next one."""
88
+ if (token is None) == (api_key is None):
89
+ raise ValueError("give either token or api_key")
90
+ urls = [base_url] if isinstance(base_url, str) else list(base_url)
91
+ if not urls:
92
+ raise ValueError("no base URL")
93
+ self.bases = [u.rstrip("/") for u in urls]
94
+ self.cur = 0
95
+ self.auth = f"Bearer {token}" if token is not None else f"Token {api_key}"
96
+ self.timeout = timeout
97
+ self.retries = retries
98
+ self.traceparent = traceparent
99
+ self.ctx = ssl.create_default_context(cafile=ca_file) if ca_file else None
100
+
101
+ # ---- transport ---------------------------------------------------------------
102
+
103
+ @overload
104
+ def _request(
105
+ self,
106
+ method: str,
107
+ path: str,
108
+ body: dict[str, Any] | None = None,
109
+ headers: dict[str, str] | None = None,
110
+ stream: Literal[False] = False,
111
+ ) -> tuple[int, dict[str, Any]]: ...
112
+
113
+ @overload
114
+ def _request(
115
+ self,
116
+ method: str,
117
+ path: str,
118
+ body: dict[str, Any] | None = None,
119
+ headers: dict[str, str] | None = None,
120
+ *,
121
+ stream: Literal[True],
122
+ ) -> http.client.HTTPResponse: ...
123
+
124
+ def _request(
125
+ self,
126
+ method: str,
127
+ path: str,
128
+ body: dict[str, Any] | None = None,
129
+ headers: dict[str, str] | None = None,
130
+ stream: bool = False,
131
+ ) -> tuple[int, dict[str, Any]] | http.client.HTTPResponse:
132
+ data = json.dumps(body).encode() if body is not None else None
133
+ h = {"Authorization": self.auth, "Accept": "application/json"}
134
+ if data is not None:
135
+ h["Content-Type"] = "application/json"
136
+ if self.traceparent:
137
+ h["traceparent"] = self.traceparent
138
+ h.update(headers or {})
139
+ attempt = 0
140
+ # With several nodes every one gets its turn before the retries run out.
141
+ budget = self.retries * len(self.bases)
142
+ while True:
143
+ req = urllib.request.Request(self.bases[self.cur] + path, data=data, method=method, headers=h)
144
+ try:
145
+ resp = cast(
146
+ http.client.HTTPResponse,
147
+ urllib.request.urlopen(req, timeout=None if stream else self.timeout, context=self.ctx),
148
+ )
149
+ if stream:
150
+ return resp
151
+ with resp:
152
+ return resp.status, _object(resp.read())
153
+ except urllib.error.HTTPError as e:
154
+ raw = e.read()
155
+ e.close()
156
+ try:
157
+ problem = _object(raw)
158
+ except ValueError:
159
+ problem = {"type": "about:blank", "detail": raw.decode(errors="replace"), "retryable": False}
160
+ err = OliviaDbError(e.code, problem)
161
+ if err.retryable and attempt < budget:
162
+ attempt += 1
163
+ self._next(e.headers.get("oliviadb-primary"))
164
+ # A move to another node is tried at once; the same node after its Retry-After.
165
+ if len(self.bases) == 1 or attempt % len(self.bases) == 0:
166
+ time.sleep(float(e.headers.get("Retry-After", "1") or 1) * max(1, attempt // len(self.bases)))
167
+ continue
168
+ raise err from None
169
+ except (urllib.error.URLError, ConnectionError, TimeoutError) as e:
170
+ # A node that is down: the next one (only when there is another).
171
+ if isinstance(e, urllib.error.HTTPError) or len(self.bases) == 1 or attempt >= budget:
172
+ raise
173
+ attempt += 1
174
+ self._next(None)
175
+ if attempt % len(self.bases) == 0:
176
+ time.sleep(0.2 * attempt)
177
+
178
+ def _next(self, primary: str | None) -> None:
179
+ if primary and primary.rstrip("/") in self.bases:
180
+ self.cur = self.bases.index(primary.rstrip("/"))
181
+ else:
182
+ self.cur = (self.cur + 1) % len(self.bases)
183
+
184
+ def _post(self, path: str, body: dict[str, Any], headers: dict[str, str] | None = None) -> dict[str, Any]:
185
+ return self._request("POST", path, _clean(body), headers)[1]
186
+
187
+ # ---- memory ------------------------------------------------------------------
188
+
189
+ def remember(
190
+ self,
191
+ thread: str,
192
+ text: str,
193
+ step_id: str | None = None,
194
+ entities: list[str] | None = None,
195
+ facts: list[dict[str, Any]] | None = None,
196
+ durability: str | None = None,
197
+ visibility: str | None = None,
198
+ ) -> dict[str, Any]:
199
+ """Write an episode and its facts; idempotent per step_id."""
200
+ return self._post(
201
+ "/v1/memory/remember",
202
+ {
203
+ "step_id": step_id,
204
+ "thread": thread,
205
+ "text": text,
206
+ "entities": entities,
207
+ "facts": facts,
208
+ "durability": durability,
209
+ "visibility": visibility,
210
+ },
211
+ )
212
+
213
+ def recall(
214
+ self,
215
+ query: str,
216
+ budget: int = 1000,
217
+ thread: str | None = None,
218
+ valid_at: int | str | None = None,
219
+ known_at: int | str | None = None,
220
+ min_ts: int | str | None = None,
221
+ already: list[str] | None = None,
222
+ ) -> dict[str, Any]:
223
+ """Context for a query within a token budget: {"text", "pack", "items", "tokens", ...}."""
224
+ return self._post(
225
+ "/v1/memory/recall",
226
+ {
227
+ "query": query,
228
+ "budget": budget,
229
+ "thread": thread,
230
+ "valid_at": valid_at,
231
+ "known_at": known_at,
232
+ "min_ts": min_ts,
233
+ "already": already,
234
+ },
235
+ )
236
+
237
+ def expand(self, pack: str, ref: str) -> dict[str, Any]:
238
+ return self._post("/v1/memory/expand", {"pack": pack, "ref": ref})
239
+
240
+ def feedback(
241
+ self, pack: str, used_refs: list[str] | None = None, answer: str | None = None, outcome: str | None = None
242
+ ) -> dict[str, Any]:
243
+ return self._post(
244
+ "/v1/memory/feedback", {"pack": pack, "used_refs": used_refs, "answer": answer, "outcome": outcome}
245
+ )
246
+
247
+ def assert_fact(
248
+ self, entity: str, attr: str, value: str, evidence: str | None = None, expected_version: int | str | None = None
249
+ ) -> dict[str, Any]:
250
+ return self._post(
251
+ "/v1/memory/facts",
252
+ {
253
+ "entity": entity,
254
+ "attr": attr,
255
+ "value": value,
256
+ "evidence": evidence,
257
+ "expected_version": expected_version,
258
+ },
259
+ )
260
+
261
+ def retract(self, fact_id: int | str, reason: str | None = None) -> dict[str, Any]:
262
+ return self._post("/v1/memory/facts/retract", {"fact_id": fact_id, "reason": reason})
263
+
264
+ def consolidate(self, cool_after_days: int | None = None) -> dict[str, Any]:
265
+ return self._post("/v1/memory/consolidate", {"cool_after_days": cool_after_days})
266
+
267
+ def export_subject(self, entity: str) -> dict[str, Any]:
268
+ return self._post("/v1/admin/subjects/export", {"entity": entity})
269
+
270
+ def erase_subject(self, entity: str, request_state: str | None = None) -> dict[str, Any]:
271
+ """First call: {"input_required": {...confirmation URL...}, "request_state": ...};
272
+ after the confirmation, call again with request_state."""
273
+ return self._post("/v1/admin/subjects/erase", {"entity": entity, "request_state": request_state})
274
+
275
+ # ---- paths and layer 1 -----------------------------------------------------------
276
+
277
+ def path(self, p: str) -> dict[str, Any]:
278
+ """A path of the path language (ENTITY=Ann, CUSTDB/CUST=C001?as_of=...)."""
279
+ return self._request("GET", "/v1/path?" + urllib.parse.urlencode({"p": p}))[1]
280
+
281
+ def catalog(self) -> dict[str, Any]:
282
+ return self._request("GET", "/v1/data/catalog")[1]
283
+
284
+ def data_recall(self, query: str, budget: int = 1000, collection: str | None = None) -> dict[str, Any]:
285
+ return self._post("/v1/data/recall", {"query": query, "budget": budget, "collection": collection})
286
+
287
+ # ---- agent state (namespaced documents) ------------------------------------------
288
+
289
+ def state_put(
290
+ self,
291
+ namespace: list[str],
292
+ key: str,
293
+ value: Any,
294
+ ttl_ms: int | None = None,
295
+ expected_version: int | None = None,
296
+ index: Any = None,
297
+ vector: list[float] | None = None,
298
+ visibility: str | None = None,
299
+ ) -> dict[str, Any]:
300
+ """Write a document; returns {"version"}. expected_version=0: only if absent."""
301
+ return self._post(
302
+ "/v1/state/put",
303
+ {
304
+ "namespace": list(namespace),
305
+ "key": key,
306
+ "value": value,
307
+ "ttl_ms": ttl_ms,
308
+ "expected_version": expected_version,
309
+ "index": index,
310
+ "vector": vector,
311
+ "visibility": visibility,
312
+ },
313
+ )
314
+
315
+ def state_update(
316
+ self,
317
+ namespace: list[str],
318
+ key: str,
319
+ ops: list[dict[str, Any]],
320
+ create: bool = True,
321
+ visibility: str | None = None,
322
+ ) -> dict[str, Any]:
323
+ """Change one document atomically (an optimistic transaction on the server).
324
+
325
+ ops: {"op": "inc", "path": "/n", "by": 1}, {"op": "set", "path": .., "value": ..},
326
+ {"op": "remove", "path": ..}, {"op": "merge", "value": {..}}. Returns {"value", "version",
327
+ "attempts", "pessimistic"}."""
328
+ return self._post(
329
+ "/v1/state/update",
330
+ {"namespace": list(namespace), "key": key, "ops": ops, "create": create, "visibility": visibility},
331
+ )
332
+
333
+ def state_append(self, namespace: list[str], value: Any, ttl_ms: int | None = None) -> dict[str, Any]:
334
+ """Add a document under a fresh increasing key; returns {"key", "version"}."""
335
+ return self._post("/v1/state/append", {"namespace": list(namespace), "value": value, "ttl_ms": ttl_ms})
336
+
337
+ def state_get(self, namespace: list[str], key: str) -> dict[str, Any] | None:
338
+ try:
339
+ return self._post("/v1/state/get", {"namespace": list(namespace), "key": key})
340
+ except OliviaDbError as e:
341
+ if e.status == 404:
342
+ return None
343
+ raise
344
+
345
+ def state_delete(self, namespace: list[str], key: str | None = None, prefix: bool = False) -> int:
346
+ r = self._post("/v1/state/delete", {"namespace": list(namespace), "key": key, "prefix": prefix or None})
347
+ return int(r["deleted"])
348
+
349
+ def state_list(
350
+ self, namespace: list[str], after: str | None = None, limit: int = 100, reverse: bool = False
351
+ ) -> list[dict[str, Any]]:
352
+ return cast(
353
+ "list[dict[str, Any]]",
354
+ self._post(
355
+ "/v1/state/list",
356
+ {"namespace": list(namespace), "after": after, "limit": limit, "reverse": reverse or None},
357
+ )["items"],
358
+ )
359
+
360
+ def state_namespaces(
361
+ self,
362
+ prefix: list[str] | None = None,
363
+ suffix: list[str] | None = None,
364
+ max_depth: int | None = None,
365
+ limit: int = 100,
366
+ offset: int = 0,
367
+ ) -> list[list[str]]:
368
+ r = self._post(
369
+ "/v1/state/namespaces",
370
+ {"prefix": prefix, "suffix": suffix, "max_depth": max_depth, "limit": limit, "offset": offset},
371
+ )
372
+ return cast("list[list[str]]", r["namespaces"])
373
+
374
+ def state_search(
375
+ self,
376
+ namespace_prefix: list[str],
377
+ query: str | None = None,
378
+ vector: list[float] | None = None,
379
+ filter: dict[str, Any] | None = None,
380
+ limit: int = 10,
381
+ offset: int = 0,
382
+ semantic: bool | None = None,
383
+ ) -> list[dict[str, Any]]:
384
+ """semantic=True ranks a text query by the server embedder's cosine only."""
385
+ r = self._post(
386
+ "/v1/state/search",
387
+ {
388
+ "namespace_prefix": list(namespace_prefix),
389
+ "query": query,
390
+ "vector": vector,
391
+ "filter": filter,
392
+ "limit": limit,
393
+ "offset": offset,
394
+ "semantic": semantic,
395
+ },
396
+ )
397
+ return cast("list[dict[str, Any]]", r["items"])
398
+
399
+ # ---- watches -----------------------------------------------------------------
400
+
401
+ def watch(self, entities: list[str] | None = None, paths: list[str] | None = None) -> str:
402
+ """Create a watch on memory entities or layer-1 paths; returns its id."""
403
+ return str(self._post("/v1/watches", {"entities": entities, "paths": paths})["id"])
404
+
405
+ def watch_read(self, watch_id: str) -> dict[str, Any]:
406
+ return self._request("GET", f"/v1/watches/{urllib.parse.quote(watch_id)}")[1]
407
+
408
+ def events(self, watch_id: str, last_event_id: str | None = None) -> Iterator[Event]:
409
+ """Server-sent events of a watch, as they come (blocking iterator)."""
410
+ h = {"Accept": "text/event-stream"}
411
+ if last_event_id is not None:
412
+ h["Last-Event-ID"] = last_event_id
413
+ resp = self._request("GET", f"/v1/watches/{urllib.parse.quote(watch_id)}/events", headers=h, stream=True)
414
+ with resp:
415
+ eid: str | None = None
416
+ data: list[str] = []
417
+ for raw in resp:
418
+ line = raw.decode().rstrip("\r\n")
419
+ if not line:
420
+ if data:
421
+ yield Event(eid or "", json.loads("\n".join(data)))
422
+ eid, data = None, []
423
+ elif line.startswith("id:"):
424
+ eid = line[3:].strip()
425
+ elif line.startswith("data:"):
426
+ data.append(line[5:].strip())