geniffy 0.1.0__py3-none-any.whl

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.

Potentially problematic release.


This version of geniffy might be problematic. Click here for more details.

geniffy/__init__.py ADDED
@@ -0,0 +1,17 @@
1
+ """Geniffy for Python: add notes, files and links to a memory, then search it and ask it.
2
+
3
+ from geniffy import Geniffy
4
+
5
+ g = Geniffy() # reads GENIFFY_API_KEY
6
+ g.memories.add("Tarun sets every price before anything is sold.")
7
+ print(g.ask("Who sets prices?").answer)
8
+ """
9
+ from ._client import DEFAULT_BASE_URL, AsyncGeniffy, Geniffy, __version__
10
+ from ._errors import (APIConnectionError, AuthenticationError, BadRequestError, GeniffyError, InternalServerError,
11
+ NotFoundError, RateLimitError, UnreadableError)
12
+ from ._types import Answer, Memory, MemoryDetail, MemoryPage, Source, SourcePage, SourceRef
13
+
14
+ __all__ = ["Geniffy", "AsyncGeniffy", "DEFAULT_BASE_URL", "__version__",
15
+ "Answer", "Memory", "MemoryDetail", "MemoryPage", "Source", "SourcePage", "SourceRef",
16
+ "GeniffyError", "APIConnectionError", "AuthenticationError", "BadRequestError", "UnreadableError",
17
+ "NotFoundError", "RateLimitError", "InternalServerError"]
geniffy/_client.py ADDED
@@ -0,0 +1,490 @@
1
+ """The Geniffy client: Geniffy (blocking) and AsyncGeniffy (asyncio), over https://api.geniffy.com/v1.
2
+
3
+ from geniffy import Geniffy
4
+ g = Geniffy() # reads GENIFFY_API_KEY
5
+ g.memories.add("Tarun sets every price before anything is sold.")
6
+ print(g.ask("Who sets prices?").answer)
7
+
8
+ Retries: reads and deletes are retried on network errors, 408, 429 and 5xx; adding is retried only when
9
+ the request never reached Geniffy (a failed connection) or on 429, so a retry never saves a note twice.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import mimetypes
15
+ import os
16
+ import random
17
+ import time
18
+ from typing import IO, Any, AsyncIterator, Dict, Iterator, List, Optional, Tuple, Union
19
+ from urllib.parse import quote
20
+
21
+ import httpx
22
+
23
+ from ._errors import APIConnectionError, GeniffyError, from_response
24
+ from ._types import Answer, Kind, Memory, MemoryDetail, MemoryPage, Source, SourcePage
25
+
26
+ __version__ = "0.1.0"
27
+ DEFAULT_BASE_URL = "https://api.geniffy.com"
28
+ _RETRY_STATUS = {408, 429, 500, 502, 503, 504}
29
+ FileInput = Union[str, "os.PathLike[str]", bytes, IO[bytes]]
30
+
31
+
32
+ def _settings(api_key: Optional[str], base_url: Optional[str]) -> Tuple[str, str, Dict[str, str]]:
33
+ key = (api_key or os.environ.get("GENIFFY_API_KEY") or "").strip()
34
+ if not key:
35
+ raise GeniffyError("No API key. Pass api_key=... or set GENIFFY_API_KEY. "
36
+ "Make one in the Geniffy app under Connect, API keys.")
37
+ url = (base_url or os.environ.get("GENIFFY_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
38
+ headers = {"Authorization": f"Bearer {key}", "User-Agent": f"geniffy-python/{__version__}",
39
+ "Accept": "application/json"}
40
+ return key, url, headers
41
+
42
+
43
+ def _delay(attempt: int, response: Optional[httpx.Response]) -> float:
44
+ if response is not None:
45
+ try:
46
+ wait = float(response.headers.get("retry-after", ""))
47
+ if 0 <= wait <= 60:
48
+ return wait
49
+ except ValueError:
50
+ pass
51
+ return min(8.0, 0.5 * (2 ** attempt)) * (0.75 + random.random() / 2)
52
+
53
+
54
+ def _retryable(method: str, response: Optional[httpx.Response], error: Optional[Exception]) -> bool:
55
+ if error is not None:
56
+ # a connection that never opened never delivered the request: always safe to send again
57
+ return method not in ("POST", "PATCH") or isinstance(error, (httpx.ConnectError, httpx.ConnectTimeout))
58
+ assert response is not None
59
+ if response.status_code == 429:
60
+ return True
61
+ return method not in ("POST", "PATCH") and response.status_code in _RETRY_STATUS
62
+
63
+
64
+ def _body(response: httpx.Response) -> Dict[str, Any]:
65
+ if not response.content:
66
+ return {}
67
+ try:
68
+ data = response.json()
69
+ except ValueError:
70
+ return {"error": {"code": "bad_response", "message": response.text[:300]}}
71
+ return data if isinstance(data, dict) else {"data": data}
72
+
73
+
74
+ def _file(file: FileInput, filename: Optional[str]) -> Tuple[str, bytes]:
75
+ """(name, bytes) for a path, raw bytes or an open binary file; read whole so a retry can resend it."""
76
+ if isinstance(file, (str, os.PathLike)):
77
+ path = os.fspath(file)
78
+ with open(path, "rb") as fh:
79
+ return filename or os.path.basename(path), fh.read()
80
+ if isinstance(file, (bytes, bytearray)):
81
+ return filename or "file", bytes(file)
82
+ data = file.read()
83
+ if isinstance(data, str):
84
+ raise TypeError("Open the file in binary mode: open(path, 'rb').")
85
+ return filename or os.path.basename(str(getattr(file, "name", "") or "")) or "file", data
86
+
87
+
88
+ def _note_or_link(text: Optional[str], url: Optional[str], title: Optional[str]) -> Dict[str, Any]:
89
+ if (text is None) == (url is None):
90
+ raise ValueError("Pass the text of a note, or url=... for a web page (one of them).")
91
+ body: Dict[str, Any] = {"text": text} if text is not None else {"url": url}
92
+ if title:
93
+ body["title"] = title
94
+ return body
95
+
96
+
97
+ def _multipart(file: FileInput, filename: Optional[str], title: Optional[str]):
98
+ name, content = _file(file, filename)
99
+ files = {"file": (name, content, mimetypes.guess_type(name)[0] or "application/octet-stream")}
100
+ return files, ({"title": title} if title else None)
101
+
102
+
103
+ def _hold(http: Any, left: float) -> float:
104
+ """How long to ask Geniffy to hold a wait open: up to 30 seconds, never past the caller's deadline, and
105
+ never so long that this client's own read timeout fires first. With a short timeout this comes to 0,
106
+ and waiting falls back to asking every `interval` seconds."""
107
+ read = getattr(getattr(http, "timeout", None), "read", None)
108
+ cap = 30.0 if read is None else float(read) - 5.0
109
+ return round(max(0.0, min(left, cap, 30.0)), 1)
110
+
111
+
112
+ def _page_params(kind: Optional[Kind], limit: int, cursor: int) -> Dict[str, Any]:
113
+ params: Dict[str, Any] = {"limit": limit, "cursor": cursor}
114
+ if kind:
115
+ params["kind"] = kind
116
+ return params
117
+
118
+
119
+ def _search_body(q: str, limit: int, kind: Optional[Kind]) -> Dict[str, Any]:
120
+ body: Dict[str, Any] = {"q": q, "limit": limit}
121
+ if kind:
122
+ body["kind"] = kind
123
+ return body
124
+
125
+
126
+ # ── blocking ──────────────────────────────────────────────────────────────────
127
+ class Geniffy:
128
+ """A person's memory, from Python. Every call reaches only the memory of the key's owner.
129
+
130
+ Building an app on this, give each of YOUR users a space and nothing else can read it:
131
+
132
+ client = Geniffy(api_key=...) # once, for the process
133
+ mem = client.space(user.id) # per request
134
+ mem.memories.add("Prefers WhatsApp, not email.")
135
+ print(mem.ask("How should we reach them?").answer)
136
+
137
+ Name no space and the client reaches your own memory, the one the Geniffy app shows you.
138
+ """
139
+
140
+ def __init__(self, api_key: Optional[str] = None, *, base_url: Optional[str] = None, timeout: float = 60.0,
141
+ max_retries: int = 2, http_client: Optional[httpx.Client] = None, space: str = ""):
142
+ _, url, headers = _settings(api_key, base_url)
143
+ self.max_retries = max(0, int(max_retries))
144
+ self._http = http_client or httpx.Client(timeout=timeout)
145
+ self.space_id = (space or "").strip()
146
+ # One header carries the space, so every call a bound client makes is scoped without a
147
+ # single method taking it, and a space can never be lost by forgetting an argument.
148
+ if self.space_id:
149
+ headers = {**headers, "X-Geniffy-Space": self.space_id}
150
+ self._url, self._headers = url, headers
151
+ self._api_key, self._base_url, self._timeout = api_key, base_url, timeout
152
+ self.memories = Memories(self)
153
+ self.sources = Sources(self)
154
+
155
+ def space(self, space: str) -> "Geniffy":
156
+ """The same client, pointed at one of YOUR users. It shares this client's connection pool,
157
+ so one per request is cheap. `space` is your own name for that user, an id or an email or
158
+ whatever you already call them, up to 128 letters, digits, dots, dashes or underscores."""
159
+ return Geniffy(self._api_key, base_url=self._base_url, timeout=self._timeout,
160
+ max_retries=self.max_retries, http_client=self._http, space=space)
161
+
162
+ def _request(self, method: str, path: str, **kw: Any) -> Dict[str, Any]:
163
+ for attempt in range(self.max_retries + 1):
164
+ response, error = None, None
165
+ try:
166
+ response = self._http.request(method, self._url + path, headers=self._headers, **kw)
167
+ except httpx.TransportError as e:
168
+ error = e
169
+ if attempt < self.max_retries and _retryable(method, response, error):
170
+ time.sleep(_delay(attempt, response))
171
+ continue
172
+ if error is not None:
173
+ raise APIConnectionError(f"Couldn't reach Geniffy: {type(error).__name__}.") from error
174
+ assert response is not None
175
+ body = _body(response)
176
+ if response.status_code >= 400:
177
+ raise from_response(response.status_code, body, response.headers.get("x-request-id"))
178
+ return body
179
+ raise AssertionError("unreachable") # pragma: no cover
180
+
181
+ def ask(self, question: str) -> Answer:
182
+ """An answer from your memory only. When nothing you added supports one, .answer is None."""
183
+ return Answer.from_json(self._request("POST", "/v1/ask", json={"question": question}))
184
+
185
+ def search(self, q: str, *, limit: int = 10, kind: Optional[Kind] = None) -> List[Memory]:
186
+ """The memories that best match q, best first."""
187
+ out = self._request("POST", "/v1/search", json=_search_body(q, limit, kind))
188
+ return [Memory.from_json(m) for m in out.get("memories") or []]
189
+
190
+ def context(self, question: str, *, limit: int = 12, kind: Optional[Kind] = None,
191
+ with_sources: bool = True) -> str:
192
+ """The memories that bear on a question, already written out for YOUR prompt:
193
+
194
+ prompt = f"{mem.context(question)}
195
+
196
+ User: {question}"
197
+
198
+ This is the ten lines of formatting every integration writes after calling search, so it is
199
+ written here once. It is never empty: when nothing is held it says so in words, because an
200
+ empty block reads to a model as permission to invent."""
201
+ return str(self.context_full(question, limit=limit, kind=kind, with_sources=with_sources)["context"])
202
+
203
+ def context_full(self, question: str, *, limit: int = 12, kind: Optional[Kind] = None,
204
+ with_sources: bool = True) -> Dict[str, Any]:
205
+ """The same, with the memories behind it and whether anything was found."""
206
+ return self._request("POST", "/v1/context", json={"question": question, "limit": limit, "kind": kind,
207
+ "with_sources": with_sources})
208
+
209
+ def profile(self, subject: Optional[str] = None) -> Dict[str, Any]:
210
+ """What stays true about someone, and what is going on with them now."""
211
+ return self._request("GET", "/v1/profile", params={"subject": subject} if subject else None)
212
+
213
+ def brief(self, subject: Optional[str] = None, *, limit: int = 60) -> Dict[str, Any]:
214
+ """What to read before dealing with someone."""
215
+ q: Dict[str, Any] = {"limit": limit}
216
+ if subject:
217
+ q["subject"] = subject
218
+ return self._request("GET", "/v1/brief", params=q)
219
+
220
+ def graph(self) -> Dict[str, Any]:
221
+ """What the memory holds and what connects to what. Every line has a memory behind it."""
222
+ return self._request("GET", "/v1/graph")
223
+
224
+ def me(self) -> Dict[str, Any]:
225
+ """Whose key this is, and which space this client is reading."""
226
+ return self._request("GET", "/v1/me")
227
+
228
+ def spaces(self) -> List[Dict[str, Any]]:
229
+ """Which of your users have memory, busiest first."""
230
+ return list(self._request("GET", "/v1/spaces").get("spaces") or [])
231
+
232
+ def forget_space(self, space: str) -> Dict[str, Any]:
233
+ """Everything one of your users ever said, gone: facts, sources, all of it. The call to make
234
+ when they ask to be forgotten. It cannot be undone."""
235
+ return self._request("DELETE", f"/v1/spaces/{quote(str(space), safe='')}")
236
+
237
+ def close(self) -> None:
238
+ self._http.close()
239
+
240
+ def __enter__(self) -> "Geniffy":
241
+ return self
242
+
243
+ def __exit__(self, *exc: Any) -> None:
244
+ self.close()
245
+
246
+
247
+ class Memories:
248
+ def __init__(self, client: Geniffy):
249
+ self._c = client
250
+
251
+ def add(self, text: Optional[str] = None, *, url: Optional[str] = None,
252
+ messages: Optional[List[Dict[str, Any]]] = None, title: Optional[str] = None) -> Source:
253
+ """Add a note (text), a web page (url=...) that Geniffy reads once, or a conversation
254
+ (messages=[{"role": ..., "content": ...}]) as your framework already holds it: content as a
255
+ string, or as Anthropic's blocks or OpenAI's parts, or parts as Gemini holds them. Only text is
256
+ kept, system and developer messages are skipped, and who said what is kept, so the user's words
257
+ become facts about the user. Learning takes a moment: see sources.wait()."""
258
+ body = _note_or_link(text, url, title) if messages is None else {"messages": list(messages)}
259
+ if messages is not None and title:
260
+ body["title"] = title
261
+ return Source.from_json(self._c._request("POST", "/v1/memories", json=body)["source"])
262
+
263
+ def add_many(self, items: List[Dict[str, Any]]) -> Dict[str, Any]:
264
+ """Up to a hundred at once. One bad item does not take the rest down: every item comes back
265
+ in the order you sent it, with either its source or why it was refused."""
266
+ return self._c._request("POST", "/v1/memories/batch", json={"items": list(items)})
267
+
268
+ def correct(self, memory_id: int, text: str) -> Dict[str, Any]:
269
+ """Say what we got wrong, and what is right. The wrong memory is marked and never used
270
+ again; what is right is learned as a new memory with its own source, so a correction leaves
271
+ a trail rather than quietly overwriting."""
272
+ return self._c._request("PATCH", f"/v1/memories/{int(memory_id)}", json={"text": text})
273
+
274
+ def add_file(self, file: FileInput, *, filename: Optional[str] = None, title: Optional[str] = None) -> Source:
275
+ """Add a PDF or Word (.docx) file: a path, bytes, or a file opened with 'rb'."""
276
+ files, data = _multipart(file, filename, title)
277
+ return Source.from_json(self._c._request("POST", "/v1/memories/file", files=files, data=data)["source"])
278
+
279
+ def list(self, *, kind: Optional[Kind] = None, limit: int = 50, cursor: int = 0) -> MemoryPage:
280
+ """One page of memories, newest first."""
281
+ return MemoryPage.from_json(self._c._request("GET", "/v1/memories", params=_page_params(kind, limit, cursor)))
282
+
283
+ def iter(self, *, kind: Optional[Kind] = None, page_size: int = 100) -> Iterator[Memory]:
284
+ """Every memory, newest first, a page at a time."""
285
+ cursor: Optional[int] = 0
286
+ while cursor is not None:
287
+ page = self.list(kind=kind, limit=page_size, cursor=cursor)
288
+ yield from page.memories
289
+ cursor = page.next
290
+
291
+ def get(self, memory_id: int) -> MemoryDetail:
292
+ """A memory, the sentence it came from (.memory.quote), and the values it held before."""
293
+ return MemoryDetail.from_json(self._c._request("GET", f"/v1/memories/{int(memory_id)}"))
294
+
295
+ def delete(self, memory_id: int) -> None:
296
+ """Forget a memory for good."""
297
+ self._c._request("DELETE", f"/v1/memories/{int(memory_id)}")
298
+
299
+
300
+ class Sources:
301
+ def __init__(self, client: Geniffy):
302
+ self._c = client
303
+
304
+ def list(self, *, limit: int = 100, cursor: int = 0) -> SourcePage:
305
+ return SourcePage.from_json(self._c._request("GET", "/v1/sources", params={"limit": limit, "cursor": cursor}))
306
+
307
+ def get(self, source_id: str) -> Source:
308
+ return Source.from_json(self._c._request("GET", f"/v1/sources/{source_id}")["source"])
309
+
310
+ def delete(self, source_id: str) -> None:
311
+ """Delete a source and every memory learned only from it."""
312
+ self._c._request("DELETE", f"/v1/sources/{source_id}")
313
+
314
+ def wait(self, source_id: str, *, timeout: float = 120.0, interval: float = 2.0) -> Source:
315
+ """Wait until Geniffy has learned from a source (or could not), then return it. Geniffy holds the
316
+ call open until the source is done, so this returns the moment it is, usually in one call."""
317
+ deadline = time.monotonic() + timeout
318
+ while True:
319
+ asked = time.monotonic()
320
+ src = Source.from_json(self._c._request("GET", f"/v1/sources/{source_id}",
321
+ params={"wait": _hold(self._c._http, deadline - asked)})["source"])
322
+ now = time.monotonic()
323
+ if src.done or now >= deadline:
324
+ return src
325
+ if now - asked < 1.0: # answered at once rather than held: don't spin
326
+ time.sleep(min(interval, deadline - now))
327
+
328
+
329
+ # ── asyncio ───────────────────────────────────────────────────────────────────
330
+ class AsyncGeniffy:
331
+ """The same client for asyncio: every method is awaited."""
332
+
333
+ def __init__(self, api_key: Optional[str] = None, *, base_url: Optional[str] = None, timeout: float = 60.0,
334
+ max_retries: int = 2, http_client: Optional[httpx.AsyncClient] = None, space: str = ""):
335
+ _, url, headers = _settings(api_key, base_url)
336
+ self.max_retries = max(0, int(max_retries))
337
+ self._http = http_client or httpx.AsyncClient(timeout=timeout)
338
+ self.space_id = (space or "").strip()
339
+ if self.space_id:
340
+ headers = {**headers, "X-Geniffy-Space": self.space_id}
341
+ self._url, self._headers = url, headers
342
+ self._api_key, self._base_url, self._timeout = api_key, base_url, timeout
343
+ self.memories = AsyncMemories(self)
344
+ self.sources = AsyncSources(self)
345
+
346
+ def space(self, space: str) -> "AsyncGeniffy":
347
+ """The same client, pointed at one of YOUR users. Shares this client's connection pool."""
348
+ return AsyncGeniffy(self._api_key, base_url=self._base_url, timeout=self._timeout,
349
+ max_retries=self.max_retries, http_client=self._http, space=space)
350
+
351
+ async def _request(self, method: str, path: str, **kw: Any) -> Dict[str, Any]:
352
+ for attempt in range(self.max_retries + 1):
353
+ response, error = None, None
354
+ try:
355
+ response = await self._http.request(method, self._url + path, headers=self._headers, **kw)
356
+ except httpx.TransportError as e:
357
+ error = e
358
+ if attempt < self.max_retries and _retryable(method, response, error):
359
+ await asyncio.sleep(_delay(attempt, response))
360
+ continue
361
+ if error is not None:
362
+ raise APIConnectionError(f"Couldn't reach Geniffy: {type(error).__name__}.") from error
363
+ assert response is not None
364
+ body = _body(response)
365
+ if response.status_code >= 400:
366
+ raise from_response(response.status_code, body, response.headers.get("x-request-id"))
367
+ return body
368
+ raise AssertionError("unreachable") # pragma: no cover
369
+
370
+ async def ask(self, question: str) -> Answer:
371
+ return Answer.from_json(await self._request("POST", "/v1/ask", json={"question": question}))
372
+
373
+ async def search(self, q: str, *, limit: int = 10, kind: Optional[Kind] = None) -> List[Memory]:
374
+ out = await self._request("POST", "/v1/search", json=_search_body(q, limit, kind))
375
+ return [Memory.from_json(m) for m in out.get("memories") or []]
376
+
377
+ # The async client lacked these until 5 Oct 2026, context() among them: the one call most apps want,
378
+ # in the client most Python AI apps use (FastAPI, async agents). Each mirrors the sync method above.
379
+ async def context(self, question: str, *, limit: int = 12, kind: Optional[Kind] = None,
380
+ with_sources: bool = True) -> str:
381
+ """The memories that bear on a question, written out for your prompt; never empty."""
382
+ out = await self.context_full(question, limit=limit, kind=kind, with_sources=with_sources)
383
+ return str(out["context"])
384
+
385
+ async def context_full(self, question: str, *, limit: int = 12, kind: Optional[Kind] = None,
386
+ with_sources: bool = True) -> Dict[str, Any]:
387
+ """The same, with the memories behind it and whether anything was found."""
388
+ return await self._request("POST", "/v1/context", json={"question": question, "limit": limit, "kind": kind,
389
+ "with_sources": with_sources})
390
+
391
+ async def profile(self, subject: Optional[str] = None) -> Dict[str, Any]:
392
+ """What stays true about someone, and what is going on with them now."""
393
+ return await self._request("GET", "/v1/profile", params={"subject": subject} if subject else None)
394
+
395
+ async def brief(self, subject: Optional[str] = None, *, limit: int = 60) -> Dict[str, Any]:
396
+ """What to read before dealing with someone."""
397
+ q: Dict[str, Any] = {"limit": limit}
398
+ if subject:
399
+ q["subject"] = subject
400
+ return await self._request("GET", "/v1/brief", params=q)
401
+
402
+ async def graph(self) -> Dict[str, Any]:
403
+ """What the memory holds and what connects to what."""
404
+ return await self._request("GET", "/v1/graph")
405
+
406
+ async def me(self) -> Dict[str, Any]:
407
+ return await self._request("GET", "/v1/me")
408
+
409
+ async def spaces(self) -> List[Dict[str, Any]]:
410
+ """Which of your users have memory, busiest first."""
411
+ return list((await self._request("GET", "/v1/spaces")).get("spaces") or [])
412
+
413
+ async def forget_space(self, space: str) -> Dict[str, Any]:
414
+ """Everything one of your users ever said, gone. It cannot be undone."""
415
+ return await self._request("DELETE", f"/v1/spaces/{quote(str(space), safe='')}")
416
+
417
+ async def close(self) -> None:
418
+ await self._http.aclose()
419
+
420
+ async def __aenter__(self) -> "AsyncGeniffy":
421
+ return self
422
+
423
+ async def __aexit__(self, *exc: Any) -> None:
424
+ await self.close()
425
+
426
+
427
+ class AsyncMemories:
428
+ def __init__(self, client: AsyncGeniffy):
429
+ self._c = client
430
+
431
+ async def add(self, text: Optional[str] = None, *, url: Optional[str] = None,
432
+ messages: Optional[List[Dict[str, Any]]] = None, title: Optional[str] = None) -> Source:
433
+ body = _note_or_link(text, url, title) if messages is None else {"messages": list(messages)}
434
+ if messages is not None and title:
435
+ body["title"] = title
436
+ out = await self._c._request("POST", "/v1/memories", json=body)
437
+ return Source.from_json(out["source"])
438
+
439
+ async def add_many(self, items: List[Dict[str, Any]]) -> Dict[str, Any]:
440
+ return await self._c._request("POST", "/v1/memories/batch", json={"items": list(items)})
441
+
442
+ async def correct(self, memory_id: int, text: str) -> Dict[str, Any]:
443
+ return await self._c._request("PATCH", f"/v1/memories/{int(memory_id)}", json={"text": text})
444
+
445
+ async def add_file(self, file: FileInput, *, filename: Optional[str] = None, title: Optional[str] = None) -> Source:
446
+ files, data = _multipart(file, filename, title)
447
+ return Source.from_json((await self._c._request("POST", "/v1/memories/file", files=files, data=data))["source"])
448
+
449
+ async def list(self, *, kind: Optional[Kind] = None, limit: int = 50, cursor: int = 0) -> MemoryPage:
450
+ return MemoryPage.from_json(await self._c._request("GET", "/v1/memories", params=_page_params(kind, limit, cursor)))
451
+
452
+ async def iter(self, *, kind: Optional[Kind] = None, page_size: int = 100) -> AsyncIterator[Memory]:
453
+ cursor: Optional[int] = 0
454
+ while cursor is not None:
455
+ page = await self.list(kind=kind, limit=page_size, cursor=cursor)
456
+ for m in page.memories:
457
+ yield m
458
+ cursor = page.next
459
+
460
+ async def get(self, memory_id: int) -> MemoryDetail:
461
+ return MemoryDetail.from_json(await self._c._request("GET", f"/v1/memories/{int(memory_id)}"))
462
+
463
+ async def delete(self, memory_id: int) -> None:
464
+ await self._c._request("DELETE", f"/v1/memories/{int(memory_id)}")
465
+
466
+
467
+ class AsyncSources:
468
+ def __init__(self, client: AsyncGeniffy):
469
+ self._c = client
470
+
471
+ async def list(self, *, limit: int = 100, cursor: int = 0) -> SourcePage:
472
+ return SourcePage.from_json(await self._c._request("GET", "/v1/sources", params={"limit": limit, "cursor": cursor}))
473
+
474
+ async def get(self, source_id: str) -> Source:
475
+ return Source.from_json((await self._c._request("GET", f"/v1/sources/{source_id}"))["source"])
476
+
477
+ async def delete(self, source_id: str) -> None:
478
+ await self._c._request("DELETE", f"/v1/sources/{source_id}")
479
+
480
+ async def wait(self, source_id: str, *, timeout: float = 120.0, interval: float = 2.0) -> Source:
481
+ deadline = time.monotonic() + timeout
482
+ while True:
483
+ asked = time.monotonic()
484
+ src = Source.from_json((await self._c._request("GET", f"/v1/sources/{source_id}",
485
+ params={"wait": _hold(self._c._http, deadline - asked)}))["source"])
486
+ now = time.monotonic()
487
+ if src.done or now >= deadline:
488
+ return src
489
+ if now - asked < 1.0:
490
+ await asyncio.sleep(min(interval, deadline - now))
geniffy/_errors.py ADDED
@@ -0,0 +1,73 @@
1
+ """Errors the Geniffy client raises. Every one carries the sentence the API sent, written for people."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Any, Dict, Optional
5
+
6
+
7
+ class GeniffyError(Exception):
8
+ """Anything that went wrong talking to Geniffy.
9
+
10
+ `request_id` is the id Geniffy gave the call (its X-Request-ID): log it, and paste it into Requests in
11
+ the Geniffy app to see exactly what was sent and what came back. None when the call never arrived."""
12
+
13
+ def __init__(self, message: str, *, status: Optional[int] = None, code: Optional[str] = None,
14
+ body: Optional[Dict[str, Any]] = None, request_id: Optional[str] = None):
15
+ super().__init__(message)
16
+ self.message, self.status, self.code, self.body = message, status, code, body or {}
17
+ self.request_id = request_id
18
+
19
+ def __str__(self) -> str:
20
+ return f"{self.message} (request {self.request_id})" if self.request_id else self.message
21
+
22
+
23
+ class APIConnectionError(GeniffyError):
24
+ """Geniffy could not be reached (network, DNS, timeout), after the retries."""
25
+
26
+
27
+ class AuthenticationError(GeniffyError):
28
+ """The key is missing, wrong or revoked (401), or not allowed here (403)."""
29
+
30
+
31
+ class NotFoundError(GeniffyError):
32
+ """No such memory or source in this memory (404)."""
33
+
34
+
35
+ class BadRequestError(GeniffyError):
36
+ """The request was refused as sent (400, 413, 422)."""
37
+
38
+
39
+ class UnreadableError(BadRequestError):
40
+ """A file or link was saved but could not be read; `source` is the row it left, with the reason."""
41
+
42
+ @property
43
+ def source(self) -> Optional[Dict[str, Any]]:
44
+ return (self.body.get("error") or {}).get("source")
45
+
46
+
47
+ class RateLimitError(GeniffyError):
48
+ """Too many requests at once (429); retried automatically before this is raised."""
49
+
50
+
51
+ class InternalServerError(GeniffyError):
52
+ """Geniffy or the memory behind it did not answer (5xx); retried automatically before this is raised."""
53
+
54
+
55
+ def from_response(status: int, body: Dict[str, Any], request_id: Optional[str] = None) -> GeniffyError:
56
+ err = body.get("error") if isinstance(body.get("error"), dict) else {}
57
+ code = err.get("code")
58
+ message = err.get("message") or body.get("detail") or f"Geniffy answered {status}."
59
+ if status in (401, 403):
60
+ cls = AuthenticationError
61
+ elif status == 404:
62
+ cls = NotFoundError
63
+ elif status == 422 and code == "unreadable":
64
+ cls = UnreadableError
65
+ elif status in (400, 409, 413, 422):
66
+ cls = BadRequestError
67
+ elif status == 429:
68
+ cls = RateLimitError
69
+ elif status >= 500:
70
+ cls = InternalServerError
71
+ else:
72
+ cls = GeniffyError
73
+ return cls(str(message), status=status, code=code, body=body, request_id=request_id)
geniffy/_types.py ADDED
@@ -0,0 +1,128 @@
1
+ """What the API returns, as plain objects. Unknown fields are kept in `.raw`, so a newer API never breaks
2
+ an older client."""
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, Dict, List, Literal, Optional
7
+
8
+ Kind = Literal["all", "people", "plan", "pref", "detail"]
9
+
10
+
11
+ @dataclass
12
+ class SourceRef:
13
+ """Where a memory came from: a note, a file or a link you added, or "other"."""
14
+ id: Optional[str]
15
+ kind: str
16
+ title: str
17
+
18
+ @classmethod
19
+ def from_json(cls, d: Optional[Dict[str, Any]]) -> Optional["SourceRef"]:
20
+ if not d:
21
+ return None
22
+ return cls(id=d.get("id"), kind=str(d.get("kind") or "other"), title=str(d.get("title") or ""))
23
+
24
+
25
+ @dataclass
26
+ class Memory:
27
+ """One thing your memory knows."""
28
+ id: int
29
+ text: str
30
+ kind: str # people, plan, pref or detail
31
+ about: Optional[str] = None
32
+ status: str = "current" # current, or clash when two memories disagree
33
+ learned_at: Optional[str] = None
34
+ said_at: Optional[str] = None
35
+ source: Optional[SourceRef] = None
36
+ quote: Optional[str] = None # the sentence it came from (on get())
37
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
38
+
39
+ @classmethod
40
+ def from_json(cls, d: Dict[str, Any]) -> "Memory":
41
+ return cls(id=int(d["id"]), text=str(d.get("text") or ""), kind=str(d.get("kind") or "detail"),
42
+ about=d.get("about"), status=str(d.get("status") or "current"), learned_at=d.get("learned_at"),
43
+ said_at=d.get("said_at"), source=SourceRef.from_json(d.get("source")), quote=d.get("quote"),
44
+ raw=d)
45
+
46
+
47
+ @dataclass
48
+ class MemoryPage:
49
+ memories: List[Memory]
50
+ counts: Dict[str, int]
51
+ total: int
52
+ next: Optional[int] = None
53
+
54
+ @classmethod
55
+ def from_json(cls, d: Dict[str, Any]) -> "MemoryPage":
56
+ return cls(memories=[Memory.from_json(m) for m in d.get("memories") or []], counts=dict(d.get("counts") or {}),
57
+ total=int(d.get("total") or 0), next=d.get("next"))
58
+
59
+
60
+ @dataclass
61
+ class MemoryDetail:
62
+ memory: Memory
63
+ history: List[Memory]
64
+
65
+ @classmethod
66
+ def from_json(cls, d: Dict[str, Any]) -> "MemoryDetail":
67
+ return cls(memory=Memory.from_json(d["memory"]), history=[Memory.from_json(h) for h in d.get("history") or []])
68
+
69
+
70
+ @dataclass
71
+ class Source:
72
+ """Something you added: a note, a file or a link, and how learning from it went."""
73
+ id: str
74
+ kind: str # note, file or link
75
+ title: str
76
+ status: str # reading, learned or failed
77
+ error: Optional[str] = None # why it failed, in plain words
78
+ facts: Optional[int] = None
79
+ url: Optional[str] = None
80
+ file_name: Optional[str] = None
81
+ file_type: Optional[str] = None
82
+ size_bytes: Optional[int] = None
83
+ added_by: Optional[str] = None
84
+ added_at: Optional[str] = None
85
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False)
86
+
87
+ @property
88
+ def done(self) -> bool:
89
+ return self.status in ("learned", "failed")
90
+
91
+ @classmethod
92
+ def from_json(cls, d: Dict[str, Any]) -> "Source":
93
+ return cls(id=str(d["id"]), kind=str(d.get("kind") or ""), title=str(d.get("title") or ""),
94
+ status=str(d.get("status") or ""), error=d.get("error"), facts=d.get("facts"), url=d.get("url"),
95
+ file_name=d.get("file_name"), file_type=d.get("file_type"), size_bytes=d.get("size_bytes"),
96
+ added_by=d.get("added_by"), added_at=d.get("added_at"), raw=d)
97
+
98
+
99
+ @dataclass
100
+ class SourcePage:
101
+ sources: List[Source]
102
+ total: int
103
+ next: Optional[int] = None
104
+
105
+ @classmethod
106
+ def from_json(cls, d: Dict[str, Any]) -> "SourcePage":
107
+ return cls(sources=[Source.from_json(s) for s in d.get("sources") or []], total=int(d.get("total") or 0),
108
+ next=d.get("next"))
109
+
110
+
111
+ @dataclass
112
+ class Answer:
113
+ """The answer, from your memory only. `answer` is None when nothing you added supports one; `message`
114
+ then says so."""
115
+ question: str
116
+ answer: Optional[str]
117
+ memories: List[Memory]
118
+ message: Optional[str] = None
119
+ clash: bool = False
120
+
121
+ def __str__(self) -> str:
122
+ return self.answer if self.answer is not None else (self.message or "")
123
+
124
+ @classmethod
125
+ def from_json(cls, d: Dict[str, Any]) -> "Answer":
126
+ return cls(question=str(d.get("question") or ""), answer=d.get("answer"),
127
+ memories=[Memory.from_json(m) for m in d.get("memories") or []], message=d.get("message"),
128
+ clash=bool(d.get("clash")))
geniffy/py.typed ADDED
File without changes
@@ -0,0 +1,130 @@
1
+ Metadata-Version: 2.5
2
+ Name: geniffy
3
+ Version: 0.1.0
4
+ Summary: Geniffy for Python: add notes, files and links to a memory, then search it and ask it.
5
+ Project-URL: Homepage, https://geniffy.com
6
+ Project-URL: Documentation, https://docs.geniffy.com
7
+ Author-email: Geniffy <ops@geniffy.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: agents,ai,geniffy,llm,memory,rag
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Software Development :: Libraries
15
+ Classifier: Typing :: Typed
16
+ Requires-Python: >=3.9
17
+ Requires-Dist: httpx<1,>=0.25
18
+ Provides-Extra: test
19
+ Requires-Dist: pytest>=7; extra == 'test'
20
+ Description-Content-Type: text/markdown
21
+
22
+ # Geniffy for Python
23
+
24
+ Give your app a memory. Write what each of your users tells you, and put what is known about them
25
+ in front of your model, with where every line came from. When nothing is known, it says so instead
26
+ of guessing.
27
+
28
+ ```bash
29
+ pip install geniffy
30
+ ```
31
+
32
+ Make a key in the Geniffy app under **API keys** and set it as `GENIFFY_API_KEY`.
33
+
34
+ ```python
35
+ from geniffy import Geniffy
36
+
37
+ client = Geniffy() # reads GENIFFY_API_KEY
38
+ mem = client.space("customer_1042") # one of your users; nothing else can read it
39
+
40
+ source = mem.memories.add("Priya Nair signs the Lumen renewal, and it comes up in March.")
41
+ mem.sources.wait(source.id) # learning usually takes a few seconds
42
+
43
+ prompt = f"{mem.context('Who signs the Lumen renewal?')}\n\nUser: Who signs the Lumen renewal?"
44
+ ```
45
+
46
+ `context()` returns the memories that bear on the question, one per line, each with where it came from:
47
+
48
+ ```
49
+ - Priya Nair signs the Lumen renewal. [note, 2026-10-05]
50
+ - The Lumen renewal comes up in March 2027. [note, 2026-10-05]
51
+ ```
52
+
53
+ Ask about something that was never stored and it returns one sentence, `There is nothing stored about
54
+ this yet. Say so rather than guessing.`, never an empty string: a model reads silence as permission to
55
+ invent.
56
+
57
+ ## Three ways to recall
58
+
59
+ ```python
60
+ mem.context("Who signs the renewal?") # a block for your own prompt; the one most apps want
61
+ mem.ask("Who signs the renewal?") # our answer in words, or answer=None and a message saying why
62
+ mem.search("renewal", limit=5) # the raw memories, ranked, to do with as you like
63
+ ```
64
+
65
+ `context()` and `ask()` judge whether anything bears on the question. `search()` ranks and does not
66
+ judge: it returns its best matches for any question at all.
67
+
68
+ ## Spaces: one memory per user
69
+
70
+ A space is your own name for one of your users. Bind a client to it and every call stays inside it.
71
+ A space exists from the first time you write to it; there is nothing to create.
72
+
73
+ ```python
74
+ mem = client.space(f"user_{user.id}") # per request
75
+ client.memories.add("...") # no space: your own memory, the one the Geniffy app shows
76
+ client.spaces() # which spaces hold anything, most recently written first
77
+ client.forget_space("user_8841") # everything held for that user, gone, when they ask
78
+ ```
79
+
80
+ ## Add
81
+
82
+ ```python
83
+ mem.memories.add("A note to remember", title="Call with Priya")
84
+ mem.memories.add(url="https://example.com") # a web page, read once
85
+ mem.memories.add(messages=chat_history) # a conversation, as your framework holds it
86
+ mem.memories.add_file("Pricing.pdf") # PDF or Word (.docx): a path, bytes or a file opened "rb"
87
+ mem.memories.add_many([{"text": "..."}, {"url": "https://..."}])
88
+ ```
89
+
90
+ A file or page that can't be read raises `UnreadableError`; `error.source` is the row it left, with the reason.
91
+
92
+ ## Read and correct
93
+
94
+ ```python
95
+ page = mem.memories.list(kind="people") # all, people, plan, pref or detail; newest first
96
+ for m in mem.memories.iter(): # every memory, a page at a time
97
+ ...
98
+ detail = mem.memories.get(42) # .memory.quote is the sentence it came from; .history its older values
99
+ mem.memories.correct(42, "Priya signs it, with Arjun co-signing.")
100
+ mem.memories.delete(42) # forget it for good
101
+ mem.profile("Priya Nair") # what is lastingly true about someone, and what is going on now
102
+ mem.brief("Priya Nair") # what to read before talking to them
103
+ mem.sources.list(); mem.sources.delete(source.id) # a source, and what only it taught
104
+ ```
105
+
106
+ ## Async
107
+
108
+ ```python
109
+ from geniffy import AsyncGeniffy
110
+
111
+ async with AsyncGeniffy() as client:
112
+ mem = client.space("customer_1042")
113
+ await mem.memories.add("Priya wants a demo on Tuesday.")
114
+ print(await mem.context("When is Priya's demo?"))
115
+ ```
116
+
117
+ ## Errors, retries and request ids
118
+
119
+ Every error carries the API's own sentence: `AuthenticationError` (a wrong or revoked key),
120
+ `NotFoundError`, `BadRequestError`, `UnreadableError`, `RateLimitError`, `InternalServerError`,
121
+ `APIConnectionError`. Reads are retried twice on network errors, 408, 429 and 5xx. Adding is retried
122
+ only when the request never reached Geniffy, or on 429, so a retry never saves a note twice. Set
123
+ `max_retries=` and `timeout=` on the client to change that.
124
+
125
+ Every response carries an `X-Request-ID`, and every error carries it as `error.request_id`. Paste it into
126
+ **Requests** in the Geniffy app to see that exact call: what was asked, what came back, and how long it took.
127
+
128
+ A key reaches its owner's memory and every space beneath it. Keep it on your server.
129
+
130
+ Docs: https://docs.geniffy.com
@@ -0,0 +1,9 @@
1
+ geniffy/__init__.py,sha256=dWE5uFq303A6vohc62hOAFRShOBQd9PuSel45dir0Ic,1006
2
+ geniffy/_client.py,sha256=R6TCOGJaZPLWZ1iEOtLlpoFm31XypniLGyfPyGeyEWs,24852
3
+ geniffy/_errors.py,sha256=FRgVKlkPDf_jafXHtpdxcHds4UAHj_FxgM8UNEFuiJs,2749
4
+ geniffy/_types.py,sha256=jR1_BB9M5XqZq4slFai-vIjXQa1qBKtMyPwuM5XicVg,4627
5
+ geniffy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ geniffy-0.1.0.dist-info/METADATA,sha256=EzFPHz4eU839iYC0cHc-yIKyhORAB62N05C19idNEf0,5447
7
+ geniffy-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
8
+ geniffy-0.1.0.dist-info/licenses/LICENSE,sha256=LFdAkiSgW1sa7sB8beoIPHH373FWiW-TfZ8fujN82Sg,1092
9
+ geniffy-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Geniffy Innovations Private Limited
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.