cortexdbai 0.3.0__tar.gz → 0.3.2__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.
@@ -69,3 +69,11 @@ dist/
69
69
  # Scratch/debug text files at root
70
70
  /*.txt
71
71
  /*.log
72
+
73
+ # Local debug / marketing / private content (not for repo)
74
+ harness/.reports/
75
+ harness_data_*/
76
+ blog/
77
+ sales/
78
+ videos/
79
+ local-instance/
@@ -0,0 +1,175 @@
1
+ Metadata-Version: 2.4
2
+ Name: cortexdbai
3
+ Version: 0.3.2
4
+ Summary: The Long-Term Memory Layer for AI Systems
5
+ Project-URL: Homepage, https://cortexdb.ai
6
+ Project-URL: Documentation, https://docs.cortexdb.ai
7
+ Project-URL: Repository, https://github.com/cortexdb/cortexdb
8
+ Project-URL: Issues, https://github.com/cortexdb/cortexdb/issues
9
+ Project-URL: Changelog, https://github.com/cortexdb/cortexdb/blob/main/CHANGELOG.md
10
+ Author-email: Prashant Malik <prashant@cortexdb.ai>
11
+ License-Expression: Apache-2.0
12
+ Keywords: ai,cortexdb,event-sourcing,knowledge-graph,llm,memory
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Database
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.10
24
+ Requires-Dist: httpx>=0.24
25
+ Requires-Dist: pydantic>=2.0
26
+ Requires-Dist: requests>=2.31
27
+ Requires-Dist: tenacity>=8.0
28
+ Provides-Extra: async
29
+ Requires-Dist: httpx[http2]; extra == 'async'
30
+ Provides-Extra: dev
31
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
32
+ Requires-Dist: pytest>=8.0; extra == 'dev'
33
+ Requires-Dist: ruff>=0.4; extra == 'dev'
34
+ Description-Content-Type: text/markdown
35
+
36
+ # CortexDB Python SDK
37
+
38
+ **The Long-Term Memory Layer for AI Systems.**
39
+
40
+ CortexDB gives your AI agents persistent, structured memory. Capture experiences, then recall a stratified pack (events, facts, beliefs, episodes, concepts) or get a grounded answer — all scoped to a hierarchical `scope` path.
41
+
42
+ [![PyPI version](https://img.shields.io/pypi/v/cortexdbai.svg)](https://pypi.org/project/cortexdbai/)
43
+ [![Python](https://img.shields.io/pypi/pyversions/cortexdbai.svg)](https://pypi.org/project/cortexdbai/)
44
+ [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](https://github.com/cortexdb/cortexdb/blob/main/LICENSE)
45
+
46
+ This SDK targets the **v1 API** (`/v1/experience`, `/v1/recall`, `/v1/answer`, …), PASETO auth, and hierarchical scopes. The pre-0.3 `remember()`/`tenant_id` client was retired — `Cortex` is now an alias of `V1Client`.
47
+
48
+ ## Installation
49
+
50
+ ```bash
51
+ pip install cortexdbai
52
+ ```
53
+
54
+ ## Quick start
55
+
56
+ ```python
57
+ from cortexdb import Cortex
58
+
59
+ # Local `docker run` with auth disabled (CORTEX_API_KEY unset on the server):
60
+ with Cortex("http://localhost:3141") as c:
61
+ c.experience("ws:demo", text="Priya at Acme signed for 200 seats. Q3 close.")
62
+ pack = c.recall("ws:demo", query="How many seats did Acme sign for?")
63
+ print(pack["context_block"])
64
+ ```
65
+
66
+ ### Hosted / multi-tenant (PASETO bearer + actor)
67
+
68
+ ```python
69
+ with Cortex(
70
+ "https://api-v1.cortexdb.ai",
71
+ actor="user:alice",
72
+ bearer="v4.public…", # PASETO v4 public or JWT (RS256/ES256)
73
+ ) as c:
74
+ out = c.answer(
75
+ "org:initech/user:alice",
76
+ "What did Alice say about coffee?",
77
+ )
78
+ print(out["answer"])
79
+ ```
80
+
81
+ ### One-call signup (no prior credentials)
82
+
83
+ ```python
84
+ from cortexdb import Cortex
85
+
86
+ c = Cortex.signup() # POST /v1/auth/signup → free-tier PASETO
87
+ c.experience(c.actor, text="hello, memory!")
88
+ print(c.recall(c.actor, query="what did I say?")["context_block"])
89
+ ```
90
+
91
+ ## Core operations
92
+
93
+ ```python
94
+ # Write — async by default (202); pass wait= for synchronous indexing.
95
+ c.experience("ws:demo", text="Deployed payments-service v3.1 to prod.")
96
+ c.experience("ws:demo", text="Rolled back auth-gateway.", wait="indexed")
97
+
98
+ # Recall — returns a StratifiedPack { context_block, layers, provenance }.
99
+ pack = c.recall("ws:demo", query="recent deploys", view="holistic")
100
+
101
+ # Answer — recall + LLM render with citations.
102
+ ans = c.answer("ws:demo", "What changed in payments recently?")
103
+
104
+ # Forget — GDPR erasure. confirm_all wipes the whole scope.
105
+ c.forget("ws:demo", confirm_all=True, cascade="redact_events",
106
+ audit_note="GDPR Article 17 request")
107
+
108
+ # Layer reads (paginated { items, has_more }).
109
+ c.events("ws:demo")
110
+ c.facts("ws:demo")
111
+ c.beliefs("ws:demo")
112
+ c.episodes("ws:demo")
113
+ c.understanding("ws:demo")
114
+ ```
115
+
116
+ ## Async usage
117
+
118
+ `AsyncCortex` mirrors every method:
119
+
120
+ ```python
121
+ import asyncio
122
+ from cortexdb import AsyncCortex
123
+
124
+ async def main():
125
+ async with AsyncCortex("http://localhost:3141") as c:
126
+ await c.experience("ws:demo", text="async memory works great")
127
+ pack = await c.recall("ws:demo", query="what works?")
128
+ print(pack["context_block"])
129
+
130
+ asyncio.run(main())
131
+ ```
132
+
133
+ ## Error handling
134
+
135
+ ```python
136
+ from cortexdb import (
137
+ Cortex,
138
+ V1Error, # base
139
+ V1APIError, # non-2xx envelope
140
+ V1AuthError, # 401 / actor mismatch
141
+ V1PolicyDeniedError, # 403 — missing capability
142
+ V1RateLimitError, # 429 (carries retry_after)
143
+ V1NotConfiguredError,# 503 — feature not configured
144
+ V1ConnectionError,
145
+ V1TimeoutError,
146
+ )
147
+
148
+ with Cortex("http://localhost:3141") as c:
149
+ try:
150
+ c.experience("ws:demo", text="important data")
151
+ except V1RateLimitError as e:
152
+ print(f"rate limited; retry after {e.retry_after}s")
153
+ except V1PolicyDeniedError as e:
154
+ print(f"missing capability: {e}")
155
+ except V1APIError as e:
156
+ print(f"API error [{e.status_code}]: {e}")
157
+ ```
158
+
159
+ ## Constructor
160
+
161
+ | Parameter | Type | Default | Description |
162
+ |-----------|------|---------|-------------|
163
+ | `api_url` | `str` | `http://localhost:3141` | CortexDB v1 surface URL |
164
+ | `actor` | `str` | `user:default` | Sent as `X-Cortex-Actor`; must match the token subject when authed |
165
+ | `bearer` | `str \| None` | `None` | PASETO v4 public / JWT bearer (omit for auth-disabled dev) |
166
+ | `timeout` | `float` | `30.0` | Request timeout (seconds) |
167
+
168
+ ## Links
169
+
170
+ - [Documentation](https://docs.cortexdb.ai)
171
+ - [Issue Tracker](https://github.com/cortexdb/cortexdb/issues)
172
+
173
+ ## License
174
+
175
+ Apache-2.0
@@ -0,0 +1,140 @@
1
+ # CortexDB Python SDK
2
+
3
+ **The Long-Term Memory Layer for AI Systems.**
4
+
5
+ CortexDB gives your AI agents persistent, structured memory. Capture experiences, then recall a stratified pack (events, facts, beliefs, episodes, concepts) or get a grounded answer — all scoped to a hierarchical `scope` path.
6
+
7
+ [![PyPI version](https://img.shields.io/pypi/v/cortexdbai.svg)](https://pypi.org/project/cortexdbai/)
8
+ [![Python](https://img.shields.io/pypi/pyversions/cortexdbai.svg)](https://pypi.org/project/cortexdbai/)
9
+ [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](https://github.com/cortexdb/cortexdb/blob/main/LICENSE)
10
+
11
+ This SDK targets the **v1 API** (`/v1/experience`, `/v1/recall`, `/v1/answer`, …), PASETO auth, and hierarchical scopes. The pre-0.3 `remember()`/`tenant_id` client was retired — `Cortex` is now an alias of `V1Client`.
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ pip install cortexdbai
17
+ ```
18
+
19
+ ## Quick start
20
+
21
+ ```python
22
+ from cortexdb import Cortex
23
+
24
+ # Local `docker run` with auth disabled (CORTEX_API_KEY unset on the server):
25
+ with Cortex("http://localhost:3141") as c:
26
+ c.experience("ws:demo", text="Priya at Acme signed for 200 seats. Q3 close.")
27
+ pack = c.recall("ws:demo", query="How many seats did Acme sign for?")
28
+ print(pack["context_block"])
29
+ ```
30
+
31
+ ### Hosted / multi-tenant (PASETO bearer + actor)
32
+
33
+ ```python
34
+ with Cortex(
35
+ "https://api-v1.cortexdb.ai",
36
+ actor="user:alice",
37
+ bearer="v4.public…", # PASETO v4 public or JWT (RS256/ES256)
38
+ ) as c:
39
+ out = c.answer(
40
+ "org:initech/user:alice",
41
+ "What did Alice say about coffee?",
42
+ )
43
+ print(out["answer"])
44
+ ```
45
+
46
+ ### One-call signup (no prior credentials)
47
+
48
+ ```python
49
+ from cortexdb import Cortex
50
+
51
+ c = Cortex.signup() # POST /v1/auth/signup → free-tier PASETO
52
+ c.experience(c.actor, text="hello, memory!")
53
+ print(c.recall(c.actor, query="what did I say?")["context_block"])
54
+ ```
55
+
56
+ ## Core operations
57
+
58
+ ```python
59
+ # Write — async by default (202); pass wait= for synchronous indexing.
60
+ c.experience("ws:demo", text="Deployed payments-service v3.1 to prod.")
61
+ c.experience("ws:demo", text="Rolled back auth-gateway.", wait="indexed")
62
+
63
+ # Recall — returns a StratifiedPack { context_block, layers, provenance }.
64
+ pack = c.recall("ws:demo", query="recent deploys", view="holistic")
65
+
66
+ # Answer — recall + LLM render with citations.
67
+ ans = c.answer("ws:demo", "What changed in payments recently?")
68
+
69
+ # Forget — GDPR erasure. confirm_all wipes the whole scope.
70
+ c.forget("ws:demo", confirm_all=True, cascade="redact_events",
71
+ audit_note="GDPR Article 17 request")
72
+
73
+ # Layer reads (paginated { items, has_more }).
74
+ c.events("ws:demo")
75
+ c.facts("ws:demo")
76
+ c.beliefs("ws:demo")
77
+ c.episodes("ws:demo")
78
+ c.understanding("ws:demo")
79
+ ```
80
+
81
+ ## Async usage
82
+
83
+ `AsyncCortex` mirrors every method:
84
+
85
+ ```python
86
+ import asyncio
87
+ from cortexdb import AsyncCortex
88
+
89
+ async def main():
90
+ async with AsyncCortex("http://localhost:3141") as c:
91
+ await c.experience("ws:demo", text="async memory works great")
92
+ pack = await c.recall("ws:demo", query="what works?")
93
+ print(pack["context_block"])
94
+
95
+ asyncio.run(main())
96
+ ```
97
+
98
+ ## Error handling
99
+
100
+ ```python
101
+ from cortexdb import (
102
+ Cortex,
103
+ V1Error, # base
104
+ V1APIError, # non-2xx envelope
105
+ V1AuthError, # 401 / actor mismatch
106
+ V1PolicyDeniedError, # 403 — missing capability
107
+ V1RateLimitError, # 429 (carries retry_after)
108
+ V1NotConfiguredError,# 503 — feature not configured
109
+ V1ConnectionError,
110
+ V1TimeoutError,
111
+ )
112
+
113
+ with Cortex("http://localhost:3141") as c:
114
+ try:
115
+ c.experience("ws:demo", text="important data")
116
+ except V1RateLimitError as e:
117
+ print(f"rate limited; retry after {e.retry_after}s")
118
+ except V1PolicyDeniedError as e:
119
+ print(f"missing capability: {e}")
120
+ except V1APIError as e:
121
+ print(f"API error [{e.status_code}]: {e}")
122
+ ```
123
+
124
+ ## Constructor
125
+
126
+ | Parameter | Type | Default | Description |
127
+ |-----------|------|---------|-------------|
128
+ | `api_url` | `str` | `http://localhost:3141` | CortexDB v1 surface URL |
129
+ | `actor` | `str` | `user:default` | Sent as `X-Cortex-Actor`; must match the token subject when authed |
130
+ | `bearer` | `str \| None` | `None` | PASETO v4 public / JWT bearer (omit for auth-disabled dev) |
131
+ | `timeout` | `float` | `30.0` | Request timeout (seconds) |
132
+
133
+ ## Links
134
+
135
+ - [Documentation](https://docs.cortexdb.ai)
136
+ - [Issue Tracker](https://github.com/cortexdb/cortexdb/issues)
137
+
138
+ ## License
139
+
140
+ Apache-2.0
@@ -16,7 +16,7 @@ Quick start::
16
16
 
17
17
  # Hosted / multi-tenant deployment with PASETO bearer + actor header:
18
18
  with Cortex(
19
- "https://api.cortexdb.ai",
19
+ "https://api-v1.cortexdb.ai",
20
20
  actor="user:alice",
21
21
  bearer="eyJ...",
22
22
  ) as c:
@@ -49,7 +49,7 @@ from cortexdb import v1 # the explicit submodule namespace
49
49
  Cortex = V1Client
50
50
  AsyncCortex = AsyncV1Client
51
51
 
52
- __version__ = "0.3.0"
52
+ __version__ = "0.3.2"
53
53
  __all__ = [
54
54
  # Clients (preferred top-level names)
55
55
  "Cortex",
@@ -12,7 +12,7 @@ Quick start:
12
12
  from cortexdb.v1 import V1Client
13
13
 
14
14
  client = V1Client(
15
- api_url="https://api.cortexdb.ai", # or http://localhost:3142 for v1 surface
15
+ api_url="https://api-v1.cortexdb.ai", # or http://localhost:3142 for v1 surface
16
16
  actor="user:alice",
17
17
  bearer="eyJ...", # PASETO v4 public or JWT (RS256/ES256)
18
18
  )
@@ -62,6 +62,22 @@ def _build_headers(
62
62
  return h
63
63
 
64
64
 
65
+ def _capture_sdk_error(exc: BaseException) -> None:
66
+ """Best-effort client-side error tracking (observability plan, Phase 6).
67
+
68
+ If the host application uses Sentry, forward SDK transport/API errors to
69
+ it so failures users hit are visible to the operator. This is a NO-OP when
70
+ ``sentry_sdk`` isn't installed or isn't initialized — the SDK never
71
+ initializes Sentry itself (the app owns that decision and the DSN)."""
72
+ try:
73
+ import sentry_sdk
74
+
75
+ if sentry_sdk.Hub.current.client is not None:
76
+ sentry_sdk.capture_exception(exc)
77
+ except Exception:
78
+ pass
79
+
80
+
65
81
  def _raise_for_response(status: int, text: str) -> None:
66
82
  """If the response is non-2xx, raise the most-specific V1APIError
67
83
  subclass derived from the v1 error envelope. Otherwise return None."""
@@ -71,7 +87,9 @@ def _raise_for_response(status: int, text: str) -> None:
71
87
  body = json.loads(text) if text else {}
72
88
  except json.JSONDecodeError:
73
89
  body = {"error_code": "UNKNOWN", "message": text[:500]}
74
- raise V1APIError.from_response(status, body)
90
+ err = V1APIError.from_response(status, body)
91
+ _capture_sdk_error(err)
92
+ raise err
75
93
 
76
94
 
77
95
  def _envelope(
@@ -260,11 +278,18 @@ class V1Client:
260
278
  self,
261
279
  scope: str,
262
280
  items: Iterable[Mapping[str, Any]],
281
+ *,
282
+ wait: Optional[str] = None,
263
283
  ) -> dict:
264
284
  """``POST /v1/experience/bulk`` — accepts up to 1000 envelopes per
265
285
  request. ``items`` is a sequence of dicts with at least ``text``
266
286
  (or ``json_data``) plus optional ``role`` / ``observed_at`` /
267
- ``labels`` / ``idempotency_key`` keys."""
287
+ ``labels`` / ``idempotency_key`` keys.
288
+
289
+ ``wait`` turns the batch into a barrier: pass ``"indexed"`` (or
290
+ ``"consolidated"`` etc.) to block until every accepted event reaches
291
+ that stage before returning — the batch analogue of
292
+ :meth:`experience`'s ``wait``, ideal for bulk-ingest-then-recall."""
268
293
  envelopes = [
269
294
  _envelope(
270
295
  scope=str(item.get("scope", scope)),
@@ -278,7 +303,8 @@ class V1Client:
278
303
  )
279
304
  for item in items
280
305
  ]
281
- return self._post("/v1/experience/bulk", {"items": envelopes})
306
+ path = "/v1/experience/bulk" + (f"?wait={wait}" if wait else "")
307
+ return self._post(path, {"items": envelopes})
282
308
 
283
309
  # ── recall + answer ───────────────────────────────────────────────
284
310
 
@@ -323,9 +349,21 @@ class V1Client:
323
349
  answer_max_tokens: Optional[int] = None,
324
350
  use_pack_id: Optional[str] = None,
325
351
  temporal: Optional[Mapping[str, Any]] = None,
352
+ diagnostics: str = "none",
326
353
  ) -> dict:
327
- """``POST /v1/answer`` — runs recall + LLM render."""
328
- body: dict = {"scope": scope, "view": view, "question": question}
354
+ """``POST /v1/answer`` — runs recall + LLM render.
355
+
356
+ ``diagnostics`` matches the semantics of :meth:`recall` (audit FRI-1):
357
+ defaults to ``"none"`` so free-tier tokens don't hit the
358
+ ``diagnostics.read`` gate. Pass ``"summary"`` or ``"full"`` when
359
+ you hold the elevated capability.
360
+ """
361
+ body: dict = {
362
+ "scope": scope,
363
+ "view": view,
364
+ "question": question,
365
+ "diagnostics": diagnostics,
366
+ }
329
367
  if question_type:
330
368
  body["question_type"] = question_type
331
369
  if question_date:
@@ -656,8 +694,16 @@ class AsyncV1Client:
656
694
  question_type: Optional[str] = None,
657
695
  question_date: Optional[str] = None,
658
696
  view: str = "holistic",
697
+ diagnostics: str = "none",
659
698
  ) -> dict:
660
- body: dict = {"scope": scope, "view": view, "question": question}
699
+ """``POST /v1/answer``. ``diagnostics`` defaults to ``"none"`` so
700
+ free-tier tokens succeed (audit FRI-1)."""
701
+ body: dict = {
702
+ "scope": scope,
703
+ "view": view,
704
+ "question": question,
705
+ "diagnostics": diagnostics,
706
+ }
661
707
  if question_type:
662
708
  body["question_type"] = question_type
663
709
  if question_date:
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "cortexdbai"
7
- version = "0.3.0"
7
+ version = "0.3.2"
8
8
  description = "The Long-Term Memory Layer for AI Systems"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
cortexdbai-0.3.0/PKG-INFO DELETED
@@ -1,235 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: cortexdbai
3
- Version: 0.3.0
4
- Summary: The Long-Term Memory Layer for AI Systems
5
- Project-URL: Homepage, https://cortexdb.ai
6
- Project-URL: Documentation, https://docs.cortexdb.ai
7
- Project-URL: Repository, https://github.com/cortexdb/cortexdb
8
- Project-URL: Issues, https://github.com/cortexdb/cortexdb/issues
9
- Project-URL: Changelog, https://github.com/cortexdb/cortexdb/blob/main/CHANGELOG.md
10
- Author-email: Prashant Malik <prashant@cortexdb.ai>
11
- License-Expression: Apache-2.0
12
- Keywords: ai,cortexdb,event-sourcing,knowledge-graph,llm,memory
13
- Classifier: Development Status :: 4 - Beta
14
- Classifier: Intended Audience :: Developers
15
- Classifier: Programming Language :: Python :: 3
16
- Classifier: Programming Language :: Python :: 3.10
17
- Classifier: Programming Language :: Python :: 3.11
18
- Classifier: Programming Language :: Python :: 3.12
19
- Classifier: Programming Language :: Python :: 3.13
20
- Classifier: Topic :: Database
21
- Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
- Classifier: Typing :: Typed
23
- Requires-Python: >=3.10
24
- Requires-Dist: httpx>=0.24
25
- Requires-Dist: pydantic>=2.0
26
- Requires-Dist: requests>=2.31
27
- Requires-Dist: tenacity>=8.0
28
- Provides-Extra: async
29
- Requires-Dist: httpx[http2]; extra == 'async'
30
- Provides-Extra: dev
31
- Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
32
- Requires-Dist: pytest>=8.0; extra == 'dev'
33
- Requires-Dist: ruff>=0.4; extra == 'dev'
34
- Description-Content-Type: text/markdown
35
-
36
- # CortexDB Python SDK
37
-
38
- **The Long-Term Memory Layer for AI Systems.**
39
-
40
- CortexDB gives your AI agents persistent, searchable memory. Store conversations, decisions, incidents, and domain knowledge as structured episodes. Retrieve relevant context with a single call.
41
-
42
- [![PyPI version](https://img.shields.io/pypi/v/cortexdb.svg)](https://pypi.org/project/cortexdbai/)
43
- [![Python](https://img.shields.io/pypi/pyversions/cortexdb.svg)](https://pypi.org/project/cortexdbai/)
44
- [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](https://github.com/cortexdb/cortexdb/blob/main/LICENSE)
45
-
46
- ## Installation
47
-
48
- ```bash
49
- pip install cortexdbai
50
- ```
51
-
52
- For HTTP/2 support (recommended for async workloads):
53
-
54
- ```bash
55
- pip install cortexdbai[async]
56
- ```
57
-
58
- ## Quick Start
59
-
60
- ```python
61
- from cortexdb import Cortex
62
-
63
- # Connect to CortexDB
64
- cortex = Cortex("http://localhost:3141", api_key="your-api-key")
65
-
66
- # Remember something
67
- cortex.remember("The payments service was migrated to Kubernetes on March 15th.")
68
-
69
- # Recall relevant memories
70
- result = cortex.recall("When did we migrate payments?")
71
- for match in result.matches:
72
- print(f"[{match.confidence:.0%}] {match.content}")
73
-
74
- # Forget when needed (GDPR, cleanup, etc.)
75
- cortex.forget(query="old deploy logs", reason="quarterly cleanup")
76
-
77
- # Search with filters
78
- results = cortex.search(
79
- "deploy failure",
80
- source="github",
81
- time_range="7d",
82
- limit=10,
83
- )
84
- print(results.context)
85
- ```
86
-
87
- ## Async Usage
88
-
89
- Every method has an async counterpart via `AsyncCortex`:
90
-
91
- ```python
92
- import asyncio
93
- from cortexdb import AsyncCortex
94
-
95
- async def main():
96
- async with AsyncCortex("http://localhost:3141", api_key="your-api-key") as cortex:
97
- await cortex.remember("Async memory storage works great.")
98
-
99
- result = await cortex.recall("How does async work?")
100
- for match in result.matches:
101
- print(match.content)
102
-
103
- asyncio.run(main())
104
- ```
105
-
106
- ## Episode Ingestion
107
-
108
- For structured data, use episodes with full metadata:
109
-
110
- ```python
111
- from cortexdb import Cortex, IngestEpisodeRequest, Actor, Source, ActorType, EpisodeType
112
-
113
- cortex = Cortex("http://localhost:3141")
114
-
115
- # Ingest a structured episode
116
- episode = IngestEpisodeRequest(
117
- content="PR #412: Add retry logic to payment processor",
118
- episode_type=EpisodeType.CODE_CHANGE,
119
- actor=Actor(id="ci-bot", name="CI Bot", actor_type=ActorType.SERVICE),
120
- source=Source(connector="github", external_id="pr-412", url="https://github.com/org/repo/pull/412"),
121
- metadata={"branch": "main", "files_changed": 3},
122
- )
123
- response = cortex.ingest_episode(episode)
124
- print(f"Episode {response.episode_id} ingested.")
125
-
126
- # Or use the smart store shorthand
127
- cortex.store("Plain text goes through remember().")
128
- cortex.store({
129
- "content": "Dict data goes through ingest_episode().",
130
- "type": "deployment",
131
- "source": "slack",
132
- })
133
- ```
134
-
135
- ## Entity Lookup
136
-
137
- Explore entities and their relationships in the knowledge graph:
138
-
139
- ```python
140
- cortex = Cortex("http://localhost:3141")
141
-
142
- # Look up an entity
143
- entity = cortex.entity("payments-service")
144
- print(f"{entity.name} ({entity.entity_type})")
145
- print(f" Episodes: {entity.episode_count}")
146
- print(f" First seen: {entity.first_seen}")
147
-
148
- # Browse relationships
149
- for rel in entity.relationships:
150
- print(f" {rel.relationship} -> {rel.target_entity_id} ({rel.confidence:.0%})")
151
-
152
- # Create explicit relationships
153
- cortex.link(
154
- source_entity_id="payments-service",
155
- target_entity_id="auth-service",
156
- relationship="DEPENDS_ON",
157
- fact="Payments calls auth for token validation",
158
- confidence=0.95,
159
- )
160
- ```
161
-
162
- ## Error Handling
163
-
164
- The SDK provides a structured exception hierarchy:
165
-
166
- ```python
167
- from cortexdb import Cortex
168
- from cortexdb.exceptions import (
169
- CortexError, # Base exception
170
- CortexAPIError, # HTTP 4xx/5xx errors
171
- CortexAuthError, # HTTP 401/403
172
- CortexRateLimitError, # HTTP 429 (includes retry_after)
173
- CortexConnectionError,# Network failures
174
- CortexTimeoutError, # Request timeouts
175
- )
176
-
177
- cortex = Cortex("http://localhost:3141")
178
-
179
- try:
180
- cortex.remember("important data")
181
- except CortexRateLimitError as e:
182
- print(f"Rate limited. Retry after {e.retry_after}s")
183
- except CortexAuthError as e:
184
- print(f"Authentication failed: {e.message}")
185
- except CortexConnectionError:
186
- print("Cannot reach CortexDB server")
187
- except CortexAPIError as e:
188
- print(f"API error [{e.status_code}]: {e.message}")
189
- ```
190
-
191
- Transient errors (429, 502, 503, 504) and connection failures are automatically retried with exponential backoff. Configure retry behavior at client initialization:
192
-
193
- ```python
194
- cortex = Cortex(
195
- "http://localhost:3141",
196
- max_retries=5, # default: 3
197
- timeout=60.0, # default: 30.0 seconds
198
- )
199
- ```
200
-
201
- ## Configuration
202
-
203
- ### Constructor Parameters
204
-
205
- | Parameter | Type | Default | Description |
206
- |----------------|---------|--------------------------|------------------------------------|
207
- | `base_url` | `str` | `http://localhost:3141` | CortexDB server URL |
208
- | `api_key` | `str` | `None` | Bearer token for authentication |
209
- | `timeout` | `float` | `30.0` | Request timeout in seconds |
210
- | `max_retries` | `int` | `3` | Max retries for transient failures |
211
-
212
- ### Environment Variables
213
-
214
- | Variable | Description |
215
- |---------------------|----------------------------------------------|
216
- | `CORTEXDB_API_KEY` | Fallback API key when none is passed directly |
217
-
218
- ## Convenience Methods
219
-
220
- | Method | Description |
221
- |-----------------------|-------------------------------------------------------|
222
- | `cortex.memory(q)` | Alias for `recall()` -- the GTM one-liner |
223
- | `cortex.store(data)` | Smart dispatch: `str` -> `remember()`, `dict` -> `ingest_episode()` |
224
- | `cortex.context(q)` | Recall with higher token budget (8192) for LLM agents |
225
-
226
- ## Links
227
-
228
- - [Documentation](https://docs.cortexdb.ai)
229
- - [GitHub Repository](https://github.com/cortexdb/cortexdb)
230
- - [Issue Tracker](https://github.com/cortexdb/cortexdb/issues)
231
- - [Changelog](https://github.com/cortexdb/cortexdb/blob/main/CHANGELOG.md)
232
-
233
- ## License
234
-
235
- Apache-2.0
@@ -1,200 +0,0 @@
1
- # CortexDB Python SDK
2
-
3
- **The Long-Term Memory Layer for AI Systems.**
4
-
5
- CortexDB gives your AI agents persistent, searchable memory. Store conversations, decisions, incidents, and domain knowledge as structured episodes. Retrieve relevant context with a single call.
6
-
7
- [![PyPI version](https://img.shields.io/pypi/v/cortexdb.svg)](https://pypi.org/project/cortexdbai/)
8
- [![Python](https://img.shields.io/pypi/pyversions/cortexdb.svg)](https://pypi.org/project/cortexdbai/)
9
- [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](https://github.com/cortexdb/cortexdb/blob/main/LICENSE)
10
-
11
- ## Installation
12
-
13
- ```bash
14
- pip install cortexdbai
15
- ```
16
-
17
- For HTTP/2 support (recommended for async workloads):
18
-
19
- ```bash
20
- pip install cortexdbai[async]
21
- ```
22
-
23
- ## Quick Start
24
-
25
- ```python
26
- from cortexdb import Cortex
27
-
28
- # Connect to CortexDB
29
- cortex = Cortex("http://localhost:3141", api_key="your-api-key")
30
-
31
- # Remember something
32
- cortex.remember("The payments service was migrated to Kubernetes on March 15th.")
33
-
34
- # Recall relevant memories
35
- result = cortex.recall("When did we migrate payments?")
36
- for match in result.matches:
37
- print(f"[{match.confidence:.0%}] {match.content}")
38
-
39
- # Forget when needed (GDPR, cleanup, etc.)
40
- cortex.forget(query="old deploy logs", reason="quarterly cleanup")
41
-
42
- # Search with filters
43
- results = cortex.search(
44
- "deploy failure",
45
- source="github",
46
- time_range="7d",
47
- limit=10,
48
- )
49
- print(results.context)
50
- ```
51
-
52
- ## Async Usage
53
-
54
- Every method has an async counterpart via `AsyncCortex`:
55
-
56
- ```python
57
- import asyncio
58
- from cortexdb import AsyncCortex
59
-
60
- async def main():
61
- async with AsyncCortex("http://localhost:3141", api_key="your-api-key") as cortex:
62
- await cortex.remember("Async memory storage works great.")
63
-
64
- result = await cortex.recall("How does async work?")
65
- for match in result.matches:
66
- print(match.content)
67
-
68
- asyncio.run(main())
69
- ```
70
-
71
- ## Episode Ingestion
72
-
73
- For structured data, use episodes with full metadata:
74
-
75
- ```python
76
- from cortexdb import Cortex, IngestEpisodeRequest, Actor, Source, ActorType, EpisodeType
77
-
78
- cortex = Cortex("http://localhost:3141")
79
-
80
- # Ingest a structured episode
81
- episode = IngestEpisodeRequest(
82
- content="PR #412: Add retry logic to payment processor",
83
- episode_type=EpisodeType.CODE_CHANGE,
84
- actor=Actor(id="ci-bot", name="CI Bot", actor_type=ActorType.SERVICE),
85
- source=Source(connector="github", external_id="pr-412", url="https://github.com/org/repo/pull/412"),
86
- metadata={"branch": "main", "files_changed": 3},
87
- )
88
- response = cortex.ingest_episode(episode)
89
- print(f"Episode {response.episode_id} ingested.")
90
-
91
- # Or use the smart store shorthand
92
- cortex.store("Plain text goes through remember().")
93
- cortex.store({
94
- "content": "Dict data goes through ingest_episode().",
95
- "type": "deployment",
96
- "source": "slack",
97
- })
98
- ```
99
-
100
- ## Entity Lookup
101
-
102
- Explore entities and their relationships in the knowledge graph:
103
-
104
- ```python
105
- cortex = Cortex("http://localhost:3141")
106
-
107
- # Look up an entity
108
- entity = cortex.entity("payments-service")
109
- print(f"{entity.name} ({entity.entity_type})")
110
- print(f" Episodes: {entity.episode_count}")
111
- print(f" First seen: {entity.first_seen}")
112
-
113
- # Browse relationships
114
- for rel in entity.relationships:
115
- print(f" {rel.relationship} -> {rel.target_entity_id} ({rel.confidence:.0%})")
116
-
117
- # Create explicit relationships
118
- cortex.link(
119
- source_entity_id="payments-service",
120
- target_entity_id="auth-service",
121
- relationship="DEPENDS_ON",
122
- fact="Payments calls auth for token validation",
123
- confidence=0.95,
124
- )
125
- ```
126
-
127
- ## Error Handling
128
-
129
- The SDK provides a structured exception hierarchy:
130
-
131
- ```python
132
- from cortexdb import Cortex
133
- from cortexdb.exceptions import (
134
- CortexError, # Base exception
135
- CortexAPIError, # HTTP 4xx/5xx errors
136
- CortexAuthError, # HTTP 401/403
137
- CortexRateLimitError, # HTTP 429 (includes retry_after)
138
- CortexConnectionError,# Network failures
139
- CortexTimeoutError, # Request timeouts
140
- )
141
-
142
- cortex = Cortex("http://localhost:3141")
143
-
144
- try:
145
- cortex.remember("important data")
146
- except CortexRateLimitError as e:
147
- print(f"Rate limited. Retry after {e.retry_after}s")
148
- except CortexAuthError as e:
149
- print(f"Authentication failed: {e.message}")
150
- except CortexConnectionError:
151
- print("Cannot reach CortexDB server")
152
- except CortexAPIError as e:
153
- print(f"API error [{e.status_code}]: {e.message}")
154
- ```
155
-
156
- Transient errors (429, 502, 503, 504) and connection failures are automatically retried with exponential backoff. Configure retry behavior at client initialization:
157
-
158
- ```python
159
- cortex = Cortex(
160
- "http://localhost:3141",
161
- max_retries=5, # default: 3
162
- timeout=60.0, # default: 30.0 seconds
163
- )
164
- ```
165
-
166
- ## Configuration
167
-
168
- ### Constructor Parameters
169
-
170
- | Parameter | Type | Default | Description |
171
- |----------------|---------|--------------------------|------------------------------------|
172
- | `base_url` | `str` | `http://localhost:3141` | CortexDB server URL |
173
- | `api_key` | `str` | `None` | Bearer token for authentication |
174
- | `timeout` | `float` | `30.0` | Request timeout in seconds |
175
- | `max_retries` | `int` | `3` | Max retries for transient failures |
176
-
177
- ### Environment Variables
178
-
179
- | Variable | Description |
180
- |---------------------|----------------------------------------------|
181
- | `CORTEXDB_API_KEY` | Fallback API key when none is passed directly |
182
-
183
- ## Convenience Methods
184
-
185
- | Method | Description |
186
- |-----------------------|-------------------------------------------------------|
187
- | `cortex.memory(q)` | Alias for `recall()` -- the GTM one-liner |
188
- | `cortex.store(data)` | Smart dispatch: `str` -> `remember()`, `dict` -> `ingest_episode()` |
189
- | `cortex.context(q)` | Recall with higher token budget (8192) for LLM agents |
190
-
191
- ## Links
192
-
193
- - [Documentation](https://docs.cortexdb.ai)
194
- - [GitHub Repository](https://github.com/cortexdb/cortexdb)
195
- - [Issue Tracker](https://github.com/cortexdb/cortexdb/issues)
196
- - [Changelog](https://github.com/cortexdb/cortexdb/blob/main/CHANGELOG.md)
197
-
198
- ## License
199
-
200
- Apache-2.0
File without changes
File without changes