Python SDK
Reference for cortexdbai: V1Client, AsyncV1Client, and the typed exception hierarchy.
The official Python client for CortexDB v1. V1Client is the client, and AsyncV1Client is its async
twin with the same methods: see Async variant.
pip install cortexdbaiRequires Python 3.10+. PyPI package: cortexdbai. Python module:
cortexdb.v1. The SDK version is independent of the server version; see Versioning and SDK compatibility.
Construction
from cortexdb.v1 import V1Client
client = V1Client(
api_url="https://api-v1.cortexdb.ai",
actor="user:alice",
bearer="v4.public.eyJpc3MiOi...",
timeout=30.0,
)| Argument | Default | Notes |
|---|---|---|
api_url | http://localhost:3141 | v1 surface URL. Defaults to a local server; pass https://api-v1.cortexdb.ai for cloud. |
actor | "user:default" | Sent as X-Cortex-Actor; must match the token's sub. |
bearer | None | PASETO v4 public token: or, self-hosted, the server's CORTEX_API_KEY value. Optional only when the server runs with CORTEX_INSECURE_NO_AUTH=1. |
timeout | 60 s | Per-request timeout. |
Use it as a context manager so the underlying requests.Session is cleaned up:
with V1Client(api_url="...", actor="user:alice", bearer=tok) as client:
pack = client.recall(scope="org:acme/user:alice")Auth
client.whoami()
# → { caller, tenant_id, deployment_preset, effective_capabilities, token }
client.mint_token(
subject="user:alice",
scope="org:acme", # the tenant root the token belongs to
ttl_seconds=3600,
scopes=["scope.read:org:acme/user:alice/*", "scope.write:org:acme/user:alice/*"], # optional: confine it
)
# → { "token": "v4.public...", "jti": "jti_...", "expires_at": "2026-05-15T11:42:00Z" }whoami key is effective_capabilities
The capability list is returned under effective_capabilities (snake_case). mint_token accepts
scopes (plural) and caps alongside the singular scope.
Write path
client.experience(
scope="org:acme/user:alice",
text="Acme upgraded to 200 seats.",
role="user",
observed_at="2026-05-15T10:42:00Z",
idempotency_key="alice-chat-001",
wait=None,
)experience() modality is optional
Pass the content with text=, json_data=, transcript=, blob_id=, or triple= (plus role=).
modality= (an open-set label) and source= are optional keywords: if
modality is omitted it is taken from source=, else defaults to conversation.
client.experience_bulk(
scope="org:acme/user:alice",
items=[
{"text": "Acme upgraded to 200 seats.", "role": "user",
"observed_at": "2026-05-15T10:42:00Z", "idempotency_key": "k1"},
{"text": "Renewal is due in March.", "role": "user",
"observed_at": "2026-05-15T10:43:00Z", "idempotency_key": "k2"},
],
)experience_bulk() takes no ordering= parameter
experience_bulk(scope, items, *, wait=None) is the full signature: there is no ordering=
keyword. Items are ingested in list order; encode temporal order in each item's observed_at.
Each item is a flat dict with exactly one of text / json_data / blob_id / triple, plus optional
role, observed_at, labels, idempotency_key, modality, source (not a wire envelope).
wait ∈ None | "accepted" | "captured" | "indexed" | "consolidated" ("accepted" is an
explicit alias for the None default). With wait omitted, a write returns
captured (202) as soon as the WAL append succeeds: it is not fully indexed yet; pass
wait="indexed" to block until BM25 + HNSW have the event. For full envelope shape (subjects,
directives, blob refs, triples) see Experience Envelope.
Read path
client.recall(
scope="org:acme/user:alice",
view="holistic",
query="What did we decide about Acme?",
include=["events", "beliefs", "facts", "episodes"],
budgets={"max_tokens": 4000},
temporal={"natural": "last 30 days"},
)
# → StratifiedPack: layers, context_block, provenance, diagnostics, pack_id
client.answer(
scope="org:acme/user:alice",
question="Did Acme renew?",
view="holistic",
temporal={"natural": "last 30 days"},
)
# → { answer, citations, provenance, diagnostics, pack_id, as_of }answer_model is a cloud default
claude-opus-5-5 is the cloud default model. Self-hosted, /v1/answer routes through whatever
you configure in the answer lane (CORTEX_ANSWER_*). An answer_model= argument is only echoed in
diagnostics.answer_model; the configured model answers (details). /v1/answer is disabled on a self-hosted
instance until that lane is set. See
Self-hosting defaults.
Layer reads
client.events(scope="org:acme/user:alice", view="local", limit=50)
client.episodes(scope="org:acme/user:alice", view="local")
client.facts(scope="org:acme/user:alice", subject="ent_acme_corp", predicate="deal_stage")
client.beliefs(scope="org:acme/user:alice", view="local")
client.belief_why(belief_id="belief_01HX...")
client.understanding(scope="org:acme/user:alice", view="local")facts() takes as_of= and the other fact filters
facts(scope, *, view='local', subject=None, predicate=None, limit=None, cursor=None, as_of=None, min_confidence=None, include_superseded=False, include_vectors=False, include=None, at_least=None) is
the full signature. as_of (RFC 3339) reads the facts valid then, min_confidence
keeps those at or above a confidence, and include_superseded=True keeps superseded facts too; each
page ends with next_cursor (or use pages()). A claim's values over time are
facts_timeline(subject, predicate, scope=…), and one fact by id is fact(fact_id, scope=…).
Facts / Beliefs need enrichment on self-host
On a content-only self-hosted instance the Facts and Beliefs layers stay empty: they are
LLM-derived and require enrichment configured. events/episodes/recall work regardless. See
Self-hosting defaults.
Trigger an async synthesis pass:
client.build_episodes(scope="org:acme/user:alice")
client.build_beliefs(scope="org:acme/user:alice")
client.synthesize(scope="org:acme/dept:eng", topics=["sales_process"])synthesize() signature
synthesize(scope, *, topics=None) is the full signature.
Forget
client.forget(
scope="org:acme/user:alice",
layers=["beliefs"],
predicate="is_likely_to_renew",
cascade="derived_only",
reason="User retracted speculation",
)forget() targets by field
forget() takes explicit targeting fields:
forget(scope, *, layers=None, about_subject=None, about_entity=None,
predicate=None, memory_ids=None, cascade='derived_only',
confirm_all=False, reason=None, from_preview_id=None)Target with predicate=, about_subject=, about_entity=, or memory_ids=[…].
The audit note goes in reason. forget() takes no idempotency key.
To purge specific records, pass their ids:
client.forget(scope="org:acme/user:alice", memory_ids=["evt_01HX...", "fact_01HX..."])If a storage backend fails mid-delete the server returns 502 FORGET_BACKEND_FAILED rather than
reporting success: deletes are idempotent, so retry the same call. For GDPR reference-counted erasure
use the /v1/erasures family directly: see Erasures.
Governed memory
Governed memory lets an application decide what CortexDB's background
enrichment learns from its events, and correct what it learned wrongly. Each method below is on both
V1Client and
AsyncV1Client (also exported as Cortex and AsyncCortex): on the async client you await the
calls, and feed_iter is an async iterator.
Check the capability first
These methods need a server that lists their capability, and none of them checks for you. Against a server without it,
each route answers 404, which reads like "not found". Before the first call, look the route's
capability up in client.capabilities() (GET /v1/admin/version): derivation_policy_v1,
corrections_v1, derivation_review_v1, derivation_rederive_v1, derivation_feed_v1,
derived_by_v1, declared_episodes_v1, derivation_use_rules_v1 or derivation_provenance_v1
(cortexdb.v1 exports most of them as constants, such as CORRECTIONS_V1). They are experimental,
and a server held at data format 10 answers 503 FORMAT_UPGRADE_PENDING on most of
these routes.
| Area | Methods |
|---|---|
Policies and settings (derivation_policy_v1) | derivation_policy(scope): the policy in force, where each rule was set, its hash · derivation_templates() · derivation_taxonomy() · derivation_policy_test(scope, policy=draft, sample=20, max_cost_usd=0.5): a draft run over your own events, writing nothing (its model calls are priced) · changeset_apply(root, id, [derive_record(scope, body)]) stages, previews and activates a policy for scope (root is your tenant root) · derivation_settings, put_derivation_settings(scope, **fields) (a subject's own settings and consents; a put replaces the whole record), delete_derivation_settings · derivation_texts, erase_derivation_texts(scope, ids, reason=) |
Corrections (corrections_v1) | correct(scope, action, target) and its shorthands reject(scope, target, bind=), replace(scope, target, value, valid_from=), pin(scope, target) and confirm(scope, target, valid=); a target is a fact id or a claim · corrections(scope) · correction(scope, id) · undo_correction(scope, id) · resolve_conflict also records its resolution as corrections (correction_ids; loser="wrong" rejects the losers) |
Review (derivation_review_v1) | review(scope): the candidates a policy held · review_decide(scope, decisions), 1 to 100 at once · approve(scope, held_id) · reject_held(scope, held_id, bind=) |
Re-derivation (derivation_rederive_v1) | rederive(scope, "regate"): the policy re-applied to what is stored, with no model call · rederive(scope, "reextract"): the dry run prices a sample and returns an estimate_id; apply with dry_run=False, estimate_id=…, cap_usd=… · rederive_job, rederive_wait, rederive_cancel · derivation_report(scope, since=, until=, csv=) |
The feed and write-backs (derivation_feed_v1, derived_by_v1, declared_episodes_v1) | derivation_feed(scope, consumer, cursor=) · feed_iter(scope, consumer), which follows next_cursor (follow=True keeps polling) · erased_matches(item, held_ids): an erasure item names its events only by hash · feed_consumers(scope) · derived_by="name@version" on a typed triple (experience(…, triple=…)) and on create_belief · derivation_status(scope, derived_by=[name]) · declare_episode(scope, name, summary, events), delete_episode(scope, id) |
What is known (corrections_v1) | memory_about(scope): the subject's facts and beliefs, each with its sources, and by default the scope's corrections and its candidates held for review (include=("corrections", "held")); include=() asks for neither |
How it was made (derivation_provenance_v1) | include=["derivation"] on facts, fact, facts_timeline, beliefs and belief_why · derivation_decisions(scope, event_id): what became of one event |
The use rule (derivation_use_rules_v1) | session= on recall, recall_stream, answer, answer_stream and compose. Where an opt-in read-time use rule is in force, memory from other sessions, or older than the rule's window, is withheld and the read's warnings count it; without session, every memory counts as another session's. A server without that capability refuses session on recall and recall_stream with 422 INVALID_BODY, since those routes deny unknown fields, and ignores it on answer, answer_stream and compose: send it only to a server whose GET /v1/admin/version lists derivation_use_rules_v1 |
A topic rule depends on the extraction model's topic labels, so a denied topic can still be learned when
the model labels a candidate otherwise. Detectors and the structural rules (stages, sources, grounding,
writer rules) are exact. Measure a draft with derivation_policy_test before you activate it.
To fix a wrong memory, correct it rather than forget() it: what a derived_only forget removes can be
learned again from the events that are kept, while a corrected claim stays corrected. This replaces a
wrong value, then undoes the replacement:
from cortexdb.v1 import CORRECTIONS_V1
home = "org:acme/user:alice"
if CORRECTIONS_V1 in client.capabilities(): # an older server answers 404
fact = client.facts(home, predicate="lives_in")["items"][0]
fixed = client.replace(home, fact["id"], "Denver", idempotency_key="alice-moved")
print(fixed["state"], fixed["replacement"]["claim"]["object"]) # applied Denver
undone = client.undo_correction(home, fixed["correction_id"])
print(undone["state"]) # undonePass an idempotency_key with each correction: the same call sent again answers the first attempt
instead of making a second correction.
The reference worker. cortexdb.workers.DerivationWorker derives on your own compute from the change
feed. Subclass it with a name and a version, a derive(event) that returns Triple objects to write
back, and a purge(event_ids) that deletes your own copies, then call run() (run(follow=True) keeps
polling). It takes a V1Client. Each result is written back citing its source event, with your
derived_by stamp and a deterministic idempotency key, so a page delivered again replays instead of
duplicating; purge is called with the events an erasure took; and the cursor (FileCursor(path) keeps
it on disk) is saved only after a page's writes commit.
A Claude memory tool. cortexdb.memory_tool.CortexMemoryTool(client, scope) carries out Anthropic's
memory tool (memory_20250818) on a CortexDB scope: each file is an event CortexDB derives nothing from.
It subclasses the Anthropic SDK's BetaAbstractMemoryTool, so it goes in the tools of the Anthropic
client's beta.messages.tool_runner(...). It needs the extra: pip install 'cortexdbai[anthropic]'
(anthropic 0.69 or later). An on_write(path, text) hook runs before anything is written and can rewrite
the text or refuse the write. CortexMemoryFiles is the same handler without the Anthropic SDK, for your
own tool loop. Give the agent a scope of its own: a directory view lists the scope's events.
The routes in full: Derivation Policies, Corrections, Review, Re-derivation, Change Feed and Memory About.
Voice calls
On a server in voice mode, client.sessions opens a live call, and
recall() takes the voice read path with profile="voice":
caller, call = "ws:acme/caller:9f2c1e", "call_01JF8M2Q7R"
started = client.sessions.start(caller, call, query="billing question") # POST /v1/sessions
system_context = started["brief"]["context_block"]
pack = client.recall(caller, query="what did I order last time", profile="voice", session=call)
client.experience(caller, text="Change my delivery address to Pune.", wait="captured",
labels=[f"session:{call}"])
client.sessions.get(caller, call) # the session and whether its memories are held
client.sessions.end(caller, call) # optional enrich=Truesessions.start(scope, session, *, query=, max_tokens=, include=, deadline_ms=, idle_timeout_s=) takes
the same fields as POST /v1/sessions. recall() also takes alpha=
(0.0 to 1.0, vector search against keyword search) on any recall. A voice recall that finds no capacity
raises RecallOverloadedError (retriable: answer that turn without memory); a session the caller does
not hold raises SessionNotFoundError, and a server not in voice mode VoiceSessionsDisabledError.
Audit
client.audit_list(actor="user:alice", capability="forget.gdpr", limit=100)
client.audit_verify(audit_id="audit_01HX...", body="<canonicalized JSON>")Admin
client.layer_stats() # GET /v1/admin/layers/stats (experimental)
# Online re-embed (trusted operator; single node): a dry run by default
client.admin_reembed("local:potion-multilingual-128M") # the estimate
client.admin_reembed("local:potion-multilingual-128M", dry_run=False) # start the job
client.admin_reembed_status() # {"job": {...}}: state, progress, eta_s, restart_with
client.admin_reembed_cancel() # while building or ready
client.admin_reembed_cleanup() # after a swap that kept the old indexThe target is "provider:model", "provider" alone, or a mapping with provider and model; dims=
sets the target's width. See Online re-embed.
Exception hierarchy
All HTTP errors raise a subclass of cortexdb.v1.V1Error:
from cortexdb.v1 import (
V1Error, # base
V1APIError, # generic API error envelope
V1AuthError, # 401
V1PolicyDeniedError, # 403
V1RateLimitError, # 429
V1NotConfiguredError, # 503
V1ConnectionError, # network failure
V1TimeoutError, # timeout
)
try:
client.experience(scope="...", text="...", observed_at="...", idempotency_key="...")
except V1PolicyDeniedError as e:
print(f"denied: {e.error_code}: {e.message}")
print(e.details) # capability/tier context, when the server provides it
except V1RateLimitError:
time.sleep(1.0)API error attributes
V1APIError and its subclasses carry status, error_code, message, request_id, details, and
retriable. Read policy context on V1PolicyDeniedError from error_code and details.
Two errors to handle on writes and deletes
- A
wait="indexed"(or"consolidated") write that runs out of the server's wait budget raisesWaitTimeoutError(aV1ServerTimeoutError, incortexdb.v1.errors) after about 30 s, before the client's own 60 s timeout, withstatus408,error_codeWAIT_TIMEOUT,retriableTrue anddetails.status_url(details.event_idsfromexperience_bulk). The write is durable: pollwrite_status, or re-send with the sameidempotency_key(see Experience). - A
forget(or erasure) that meets409 AUTHORIZATION_STATE_CHANGEDraisesAuthorizationStateChangedError(aV1ConflictError),retriableTrue. Nothing was deleted; retry after a second. event(event_id, scope=…)reads one event and takes the route's?scope=filter (see Events).
Async variant
AsyncV1Client is backed by httpx.AsyncClient. It mirrors V1Client: the same methods, with the
same names and parameters, and you await each call.
import asyncio
from cortexdb.v1 import AsyncV1Client
async def main():
async with AsyncV1Client(
api_url="https://api-v1.cortexdb.ai",
actor="user:alice",
bearer=tok,
) as client:
pack = await client.recall(scope="org:acme/user:alice", view="holistic")
ans = await client.answer(scope="org:acme/user:alice", question="Did Acme renew?")
asyncio.run(main())The async client mirrors the sync one
Both clients have the same public methods with the same parameters. The layer reads, the
retention and other operator methods, and recall()'s full argument set (include=, budgets=,
temporal=, filters=) are on both. The one difference is closing: the async client has
aclose() instead of close() (or use async with, as above). There pages() and feed_iter()
are async iterators.
Method index
Capabilities, chunks and language fields
version()returns{version, crate_version, …, capabilities}andcapabilities()returns just the capability list (GET /v1/admin/version). Gate every new request field on it: a server that doesn't list a capability refuses its fields with422 INVALID_BODY.event_chunks(event_id)shows how a long event was chunked (GET /v1/admin/events/{id}/chunks):chunk_count,chunker_version,chunks,language,scripts,source_blob_ids,stored_text_bytes.iter_matched_fragments(pack)andfragment_text(text, fragment)(import fromcortexdb.v1, not the package top level) walk a recall pack'smatched_fragmentsand slice each span out of the event's text; an excerpted item yields no span.experience()takeslanguage=,scripts=,timezone=andrefers_to=;recall()takeslanguage=,scripts=andquery_variants=: see Languages & Multilingual Memory, Experience and Recall.delete_blob(blob_id, missing_ok=True)returns{…, "already_deleted": true}for a blob that is already gone instead of raising404 NOT_FOUND.
Retention and WAL operator methods
retention_policy_get / retention_policy_set / retention_policy_delete / retention_status /
retention_sweep / wal_status / wal_compact wrap the operator routes /v1/admin/retention,
/v1/admin/retention/policies, /v1/admin/retention/sweep, /v1/admin/wal and /v1/admin/wal/compact.
Expiry is irreversible erasure, so the
server defaults dry_run to true on each of them. They are on both clients.
The sections above cover the common paths. The full V1Client surface also
includes these, several of which map to endpoints documented elsewhere in this reference:
| Area | Methods |
|---|---|
| Compose | compose → POST /v1/compose |
| Bi-temporal records | query_claims · claim_history · list_conflicts · get_conflict · resolve_conflict → Claims & Conflicts |
| Layer history | belief_history · concept_history |
| Erasure | erase · erasure_preview · forget_preview → /v1/erasures |
| Import | import_data · import_status → /v1/import |
| Blobs | upload_blob · delete_blob → /v1/blobs |
| Beliefs (write) | create_belief |
| Vocabularies | update_vocabulary → /v1/vocabularies |
| Auth | signup · mint_token(subject=, scope=, caps=, scopes=) · whoami → /v1/auth |
| Server | version · capabilities → /v1/admin/version |
| Documents | event_chunks → GET /v1/admin/events/{id}/chunks |
| Audit | audit_chain · audit_chain_verify |
| Write status | write_status: "did my write land?" by idempotency_key or event_id |
| Voice calls | sessions.start · sessions.get · sessions.end → /v1/sessions |
| Re-embed | admin_reembed · admin_reembed_status · admin_reembed_cancel · admin_reembed_cleanup → Online re-embed |
| Lifecycle | close (sync) · aclose (async) |