Python SDK
The nenavi package is the Python client for Nenavi Cloud. It has a sync client and an async client, typed models for every request and answer, typed errors, and retries only where a retry is safe. It needs Python 3.11 or later, and its only runtime dependencies are httpx and pydantic (v2).
Early access. The SDK is an alpha prerelease. Until version 1.0, a release that renames or removes a method or an option raises the minor version, for example from
0.1to0.2.
Install
pip install --pre nenaviThe first releases are prereleases, so pip needs --pre.
The SDK is server-side code. Keep the key on your server and never ship it to a browser or a mobile app.
Configuration
Create a project and a key in the console first, as the quick start shows, and put the key in NENAVI_API_KEY:
export NENAVI_API_KEY="<paste your API key>"nenavi.Nenavi() takes these options. Each one is optional.
| Option | Default |
|---|---|
api_key | The NENAVI_API_KEY environment variable |
base_url | The NENAVI_BASE_URL environment variable, else https://api.prismemory.com |
timeout | 30 seconds for each attempt |
max_retries | 2 automatic retries, on the calls that are safe to retry |
http_client | A new httpx.Client (httpx.AsyncClient for the async client) |
The service itself reads no environment variable; only the SDK does. A client without a key can call only health() and relations(). Every other method raises nenavi.ConfigurationError before it sends anything. The key never appears in a repr, a log line, or an error.
Store and retrieve
import nenavi
client = nenavi.Nenavi() # reads NENAVI_API_KEY
stored = client.store(content="Alex prefers concise explanations.", user_id="alex")
print("stored event", stored.event_id)
found = client.retrieve(query="How should I explain this to Alex?", user_id="alex", limit=3)
for result in found.results or []:
print(f"{result.score:.3f}", result.content)Retrieved memory is untrusted input. Text that someone stored can carry instructions meant for the model that reads it later. Treat retrieved text as data in your prompt, not as instructions.
store() answers at once with the event_id. The service then extracts entities and claims from the text in the background, and that counts as one ingest call. To store the text as it is, with no extraction, pass extract=False.
user_id names one of your own end users. The service does not check it, so your code must send the right one.
The examples below use this client and the nenavi import, and they run in page order as one file. Call client.close() when you are done with it, or use it as a context manager: with nenavi.Nenavi() as client:.
Request and answer fields keep the API’s names (user_id, event_id), so the API reference and the curl examples in these docs match the SDK. Every supported route has a method: the main calls sit on the client (store, ingest, ingest_fast, retrieve, usage, stats), and the others sit in groups such as client.events, client.nodes, client.reingest and client.claims. The routes that the alpha refuses (see The API) have no method.
The async client
nenavi.AsyncNenavi takes the same options and has the same methods, as coroutines.
You can build one AsyncNenavi at module scope and call it through asyncio.run() on every invocation, as an AWS Lambda handler or a Celery task does. When a call runs on a new event loop, the client opens new connections there. The connections left on the closed loop are released when they are garbage-collected, with a ResourceWarning, so in tests that turn warnings into errors, build the client in a fixture on the test’s loop and close it there. An httpx.AsyncClient that you pass as http_client cannot move between loops: build it inside the event loop that uses it, because a call from another loop raises nenavi.ConfigurationError.
import asyncio
async def main() -> None:
async with nenavi.AsyncNenavi() as client:
await client.store(content="Alex prefers concise explanations.", user_id="alex")
found = await client.retrieve(query="How should I explain this to Alex?", user_id="alex")
for result in found.results or []:
print(f"{result.score:.3f}", result.content)
asyncio.run(main())Retrieved memory is untrusted input here too: treat the text as data, not as instructions.
Name the user in a chat
Send each of the user’s own messages with role="user" and the user’s name as speaker, so the engine reads “I”, “me” and “my” as that person and attaches their claims to one entity with their name. If you also store the assistant’s replies, send them with role="assistant" and no speaker.
client.ingest(
content="My husband is Theo and my child is Nico.",
user_id="member-1042",
role="user",
speaker="Maya Okafor",
session_id="chat-2026-11-03",
)
client.ingest(
content="Got it. Theo and Nico are on your plan.",
user_id="member-1042",
role="assistant",
session_id="chat-2026-11-03",
)Use the same spelling of the name every time. See Name the user in a chat in the quick start for what the engine does with the name and which names it refuses.
Import a batch that is safe to retry
store() and ingest() are not safe to retry, so the SDK never retries them. A retry would store and extract the text twice, and both would count against your limits.
To import text that you may need to send again, use ingest_fast(). Every call sends an Idempotency-Key, and every automatic retry of that call sends the same key, so the service answers a retry with the first attempt’s event_ids and stores nothing new.
import uuid
batch_key = uuid.uuid4()
items = [{"content": "Alex moved to Lisbon in May."}]
try:
batch = client.ingest_fast(items=items, user_id="alex", idempotency_key=batch_key)
except nenavi.APIConnectionError:
# No answer arrived. Send the batch again with the same key.
batch = client.ingest_fast(items=items, user_id="alex", idempotency_key=batch_key)
print(batch.accepted, batch.event_ids)When you pass no idempotency_key, the SDK makes a new UUID for the call, and every error that call raises carries it as error.idempotency_key. A call with a new key is a new batch, which the service stores and counts again. Using one key with different items raises nenavi.ConflictError (409).
The SDK never retries a timeout, because the timeout is your budget for one attempt. A large batch can time out after the service has stored it. If you did not choose a key, send the batch again with the key the first call sent:
try:
batch = client.ingest_fast(items=items, user_id="alex")
except nenavi.APITimeoutError as error:
# A timeout error carries the key the call sent.
if error.idempotency_key is None:
raise
batch = client.ingest_fast(items=items, user_id="alex", idempotency_key=error.idempotency_key)A 502 or 504 answer (nenavi.InternalServerError) leaves the same doubt, because the batch may be stored, and it carries the key too. Send the batch again with that key in the same way.
If you wrap ingest_fast() in your own retry, such as a tenacity decorator or a backoff loop, make the key and the items once, before the first attempt, and pass the same key and items on every attempt, as the first example does. A wrapper that calls ingest_fast() without a key sends a new key on each attempt, so after a timeout the service stores the batch twice and counts it twice against your limits, and nothing tells you that it happened.
If you cancel ingest_fast() yourself, for example with asyncio.wait_for() around the async client, the error that reaches you comes from asyncio and carries no key. Pass your own idempotency_key in that case, and reuse it to send the batch again.
Fast ingest saves the text for retrieval and runs no extraction.
Wait for extraction
ingest() answers once the text is saved. Extraction runs in the background, and client.events.wait_for_extraction() waits for it:
answer = client.ingest(content="Alex is learning Portuguese.", user_id="alex")
status = client.events.wait_for_extraction(answer.event_id, timeout=300)
print(status.status) # "complete" or "failed"The helper polls GET /v1/events/{event_id}/extraction-status every 2 seconds (interval) and returns the last status. A failed extraction is returned, not raised. When timeout seconds run out first, it raises nenavi.WaitTimeoutError, with the last status as error.last_status. It stops at any status other than pending or running, so a status the service adds later is returned too, and reingest.run() does the same with a run’s state. The polls count against a rate limit of their own, not the one your writes use, so to wait on many events at once, read Helpers and the rate limit first.
Re-ingest
A re-ingest run processes one end user’s stored memories again and replaces the claims derived from them. Preview it first:
preview = client.reingest.preview(user_id="alex")
print(preview.selected, "memories,", preview.estimated_ingest_calls, "ingest calls")
run = client.reingest.run(user_id="alex")
print(run.state, run.processed, "processed,", run.remaining, "remaining")preview() never starts a run and is not counted. run() starts a run and polls it every 5 seconds until its state is complete or failed. Each memory the run takes counts as one ingest call. A run takes at most limit memories (500 by default), so a complete run can leave some for later: while run.remaining is above 0, call run() again with the same arguments. A second run for the same user while one is working raises nenavi.ConflictError with reason_code reingest_running. When the helper’s timeout (one hour by default) runs out, it raises nenavi.WaitTimeoutError, and the run itself goes on. A poll that fails raises that call’s error, and the run goes on then too: the error’s last_status is the last status read before it, so client.reingest.wait(error.last_status.run_id) goes on waiting for the run. Calling run() again instead raises ConflictError until the run ends, and that error’s run_id is the run that is working: when the run is lost some other way (the answer to run()’s start is lost, the task is cancelled, or an outside timeout such as a Lambda limit stops it), call client.reingest.latest(user_id="alex"), which starts nothing and returns the user’s newest run whether or not it has ended, usually the lost one (see Find a run you lost). Calling run() again finds the lost run only while it works, through error.run_id; once the run has ended, that call starts the next run instead (or returns when nothing is left to re-derive). The status holds the run’s user_id, so where your end users’ ids must stay out of logs, log the error’s message and request_id, not the error object.
Wait for a run you already have
client.reingest.wait() polls a run by its id and starts nothing. Use it after start(), or to go on with a run whose id an error gave you:
started = client.reingest.start(user_id="alex")
if started.run_id is not None:
try:
run = client.reingest.wait(started.run_id, timeout=840)
print(run.state, run.error)
except nenavi.WaitTimeoutError as error:
print("still working; wait again on", started.run_id)It polls at once and then every 5 seconds (interval), and stops at the same states as run(): a failed run is returned with its error, not raised, and any state other than pending or running is returned too. When timeout (one hour by default) runs out first, it raises nenavi.WaitTimeoutError with the last status as error.last_status, or None when no poll was answered, and the run goes on. Each poll gets no more than the time left, so in an AWS Lambda function pass a timeout below the function’s own limit (at most 900 seconds), as above, and call wait() again with the same id in the next invocation. A poll that fails raises that call’s error with last_status set the same way. An id that names no run of your project raises nenavi.NotFoundError with reason_code reingest_run_not_found, and a value that is not a run id at all (such as None passed as text) raises nenavi.UnprocessableEntityError, so check run_id is not None first, as above.
Find a run you lost
client.reingest.latest() returns the user’s newest run, the same status get() returns, whether it is still working or has ended. Use it when the run’s id is gone, for example in the next invocation of a function whose run() was cut short:
last = client.reingest.latest(user_id="alex")
print(last.run_id, last.scope, last.started_at) # check this is the start you sent
if last.state == "running" and last.run_id is not None:
last = client.reingest.wait(last.run_id, timeout=840)
print(last.state, last.error)The newest run is not always the one you lost: another caller, or the console, may have started a newer one for the same user since, and a start that wrote no run (nothing needed re-deriving, or the start was refused or never arrived) leaves an older one as the newest. Compare its started_at and scope with the start you sent before you treat it as that run. It starts nothing and reads only runs of your project. A user with no run raises nenavi.NotFoundError with reason_code reingest_run_not_found. It counts against the key’s ordinary request rate limit, not the one the polls use, so wait on a working run with wait(), as above.
Read every node
client.nodes.scan_all() reads every page of GET /v1/nodes/scan and yields each node:
for node in client.nodes.scan_all(user_id="alex", limit=1000):
print(node.id)limit is the page size: 100 nodes by default and at most 1,000. Each page is one call, so pass limit=1000 to read a large store: 50,000 nodes take 50 calls instead of 500. While a page’s has_more is true, the helper sends its next_cursor as the next after_id. A page that has more but gives no new cursor raises nenavi.NenaviError, so a scan never ends early without saying so.
Build and read a profile
A profile is what the memory knows about one person, quoted from the user’s stored memories that mention them. Building one makes no model call. Build after new turns, then read it by name:
built = client.profiles.build(user_id="alex", entity_names=["Theo", "Nico"])
print(built.published, "profiles")
try:
profile = client.profiles.get(user_id="alex", name="Theo")
print(profile.text)
except nenavi.NotFoundError:
print("No profile of Theo yet")Leave out entity_names to profile the people extraction found in the user’s memories, at most 20; built.names says which. A name that fewer than two memories mention gets no profile, so get() raises nenavi.NotFoundError with reason_code profile_not_found. build() is never retried automatically. When a memory changes while it runs, or while another build of the project runs or the server is already running as many builds as it can, it raises nenavi.ConflictError with reason_code profile_stale or profile_build_running, and the same call builds again once the other ends. error.body["at_capacity"] is True when the server was busy with other projects’ builds and your build did not run; send it again after error.headers["retry-after"] seconds. A build can take up to a minute. Releases after 0.1.0a2 wait 90 seconds for build() (or the client’s timeout, when that is longer); with 0.1.0a2 or earlier, pass timeout=90 to build(). Build again after you archive a memory a profile quotes; profile.stale is True when a memory the profile quotes was archived, replaced, deleted, or marked contested since it was built. It does not see newer memories. A build that finds no memory short enough to quote keeps the profile as it was, so it stays stale, and lists it in built.kept_stale with reason no_source_fits; stop rebuilding that profile on stale until the user’s memories change, and still rebuild it now and then, for example once a day. A summary memory saved before the service reserved entity_profile, with a value such as "yes" instead of true, blocks the profile of its name: a build that names that person raises nenavi.UnprocessableEntityError with reason_code profile_metadata_invalid, and error.body["node_ids"] lists those memories, and a build without names leaves the person out and lists them in built.skipped, each entry with name, reason profile_metadata_invalid and node_ids. Archive those memories with nodes.archive(), then build again; archiving cannot be undone, so check first that your application no longer needs them. Profiles on the API page has the details and the bounds.
Organize and process
client.organize(), client.materializations.process() and client.extractions.process() run a job for the project: work that goes on for the call’s budget_ms (at most 30 seconds) and then finishes the step it started last, such as one model call. A run locks the user_id it names: each user runs one job at a time, and a run of one user does not refuse another user’s, so a loop over your users is not held up by one long run (the service may still run them one after another). A client.organize() without a user_id runs over the whole project and locks it: it is refused while any user’s run is going, and every user’s run is refused while it is going, so pause a loop over your users to run one. Each server runs at most 4 job runs of one project at once: one more raises nenavi.ServiceUnavailableError with reason_code job_requests_busy, runs nothing, and is not counted. Run at most 4 users at a time, and call again after error.headers["retry-after"] seconds. A call that raised nenavi.JobRunningError (below) is still running and still counts toward the 4 until it ends.
When the run is still going after about 45 seconds, the service answers before the connection times out and the run goes on in the background. The call then raises nenavi.JobRunningError, with the run’s id as error.run_id, and client.jobs.latest(user_id=...) tells you when it ends:
import time
try:
done = client.extractions.process(user_id="alex", budget_ms=30000)
print(done.processed, "processed,", done.pending, "left")
except nenavi.JobRunningError as error:
run = client.jobs.latest(user_id="alex")
while run.state == "running" and str(run.run_id) == error.run_id:
time.sleep(5)
run = client.jobs.latest(user_id="alex")
print(run.state, run.finished_at)state stays running until the run ends, then is succeeded or failed. With user_id, jobs.latest() reads the newest run that user’s next job call would wait for: the user’s own, or one over the whole project, whichever started last; without it, the project’s newest run. The answer’s user_id is the user the run locks, None for the whole project. Read with the user_id your call named, as above, a different run_id means your run ended and a newer one started; without it, the newest run can be another user’s. It can also be the service’s own organize of the user, whose job is automatic_organize, not your call’s (see Organize and process runs that outlive the request). The run’s own answer, such as the counts above, is not kept, so read what it did with the usual calls, such as events.extraction_status(). A job call that arrives while a run of the same user, or one over the whole project, is going (for a call without a user_id, any run of the project) raises nenavi.ConflictError with reason_code job_running, error.run_id set to the running run, and a Retry-After of 15 seconds, or, when the running run is the service’s own automatic_organize, the seconds until it is expected to end (at most 30). The same call sent again after that is admitted unless one of your own runs that it overlaps has started meanwhile, or the run takes longer than expected, which answers a short Retry-After again. It runs nothing and is not counted. None of these calls is retried automatically. Releases after 0.1.0a2 wait 60 seconds for these calls (or the client’s timeout, when that is longer), so the answer arrives; with 0.1.0a2 or earlier, pass timeout=60, and read the answer with client.with_raw_response: a status of 202 means the run goes on, and data is not the call’s usual answer.
The service also organizes each user’s memories on its own, with no call. client.auto_organize.get() says when it last did and what each job did, and starts nothing:
organized = client.auto_organize.get(user_id="user-1")
if organized.last_run is None:
print("not organized yet")
else:
print(organized.last_run.outcome, organized.last_run.finished_at)
for job in organized.last_run.jobs:
print(job.job, job.nodes_processed, job.nodes_modified, job.details)last_run is None before the user’s first automatic organize. outcome is finished, budget (its time ran out, and the next run goes on with pending_jobs) or failed (a later run tries again, and error says why). resumes lists the jobs of pending_jobs that stopped partway through their memories, with how many runs in a row left each so (runs) and the memories it looked at in the newest run (nodes_processed) and in all of them (nodes_processed_total). due_since is when the service first found the user’s memories needing an organize that has not finished, or None. Organize calls you make yourself are not in it. The call is retried automatically like any read.
Helpers and the rate limit
Every poll and every scan page is an ordinary call, with that call’s retries and errors. They count against two different rate limits (see Limits and errors):
- The polls read
GET /v1/events/{event_id}/extraction-statusandGET /v1/reingest/{run_id}. Those two status reads, andclient.jobs.latest(), have a rate limit of their own per key and per project, as many a minute as the request rate limit (60 by default), so polling never uses up the requests your other calls need. - A scan page, like every other call, counts against the key’s request rate limit, which is 60 requests a minute by default, and your application’s other calls with the same key share that limit.
| Helper | Calls at the defaults | Counts against |
|---|---|---|
events.wait_for_extraction() | 30 a minute for each event you wait on, one every 2 seconds | Status reads |
reingest.run() | 12 a minute while the run works, one every 5 seconds | Status reads |
reingest.wait() | 12 a minute while the run works, one every 5 seconds | Status reads |
nodes.scan_all() | One for every 100 nodes, sent as fast as you read them | Requests |
When the polls use up the status read limit, only polls get 429 rate_limited. The SDK retries each poll after Retry-After, at most twice by default, so the waits slow down, and a poll that is still refused after its retries raises nenavi.RateLimitError from the helper. Two waiters at the default interval use the whole status read limit, so wait on many events with a longer interval, or one after another. With asyncio.gather(), ten waiters at interval=20 use half of it.
When scans or your own calls use up the request limit, your other calls get 429 rate_limited. The SDK retries GET calls and ingest_fast() after Retry-After, at most twice by default, but it never retries store(), ingest() or retrieve(), so those raise nenavi.RateLimitError. The service refuses a rate_limited call before it does any work, so that write stored nothing: you can send it again after error.retry_after seconds. Do not send a write again after nenavi.APITimeoutError, because the first one may have been stored. To leave room for your calls:
- Pass
limit=1000toscan_all(). - A second key does not add requests. Both rate limits are kept per key and per project, so a large import, a scan or a re-ingest on another key shares the project’s 60 a minute with your other calls, as it shares the monthly limits and the memory cap. A separate key still helps you tell the work apart and revoke it on its own. If background work needs more room, see Limits and errors for how to raise a limit.
Errors
Every error the SDK raises is a nenavi.NenaviError. When the service answers with an error, the SDK raises a subclass of nenavi.APIError, which has status, reason_code (None for errors that the engine raises), detail, and request_id.
| Error | When |
|---|---|
BadRequestError | 400 |
AuthenticationError | 401: the key is missing, invalid, or revoked, or its project was deleted |
PermissionDeniedError | 403 |
NotFoundError | 404 |
ConflictError | 409, for example reingest_running or job_running |
PayloadTooLargeError | 413 |
UnprocessableEntityError | 422: a refused value, or a request that does not validate |
RateLimitError | 429 rate_limited, with retry_after in seconds |
QuotaExceededError | 429 for a monthly limit or the memory cap. Waiting seconds does not clear it |
ServiceUnavailableError | 503 |
InternalServerError | Another 5xx |
APIConnectionError | No answer arrived: a DNS, connection, or TLS failure |
APITimeoutError | No answer within the timeout. A subclass of APIConnectionError |
nenavi.JobRunningError is not an APIError: the service accepted an organize or process call whose run goes on in the background (see Organize and process).
An id passed as a path parameter, such as node_id or event_id, that is empty, . or .., or contains / raises nenavi.ConfigurationError before anything is sent, because it cannot be sent as one path segment. Ids the service returns never do. The message does not repeat the id.
try:
client.store(content="Alex prefers concise explanations.", user_id="alex")
except nenavi.QuotaExceededError as error:
print("a monthly limit is reached:", error.reason_code)
except nenavi.APIError as error:
print(error.status, error.reason_code, error.detail, "request", error.request_id)
except nenavi.APIConnectionError:
print("no answer arrived; the memory may or may not be stored")Limits and errors lists every reason_code.
Retries
The SDK retries a call by itself only when the call is safe to retry and the failure is one that can clear:
- Calls it retries: every
GETmethod, such asusage(),nodes.get()andevents.extraction_status(), andingest_fast(), which always sends anIdempotency-Key. - Failures it retries: a
429rate_limited, after theRetry-Afterseconds; a503withreason_codedatabase_unavailableorlease_unavailable; a503with noreason_code, which the load balancer in front of the service sends when no server can answer; and a connection failure with no answer. The retries clear a brief interruption, not an outage that takes a few minutes, so handleServiceUnavailableErrorin code that must ride one out. - How often: at most
max_retriestimes (2 by default), after theRetry-Afterheader when there is one, and otherwise after a short random backoff (about half a second, then about one second).
It never retries:
store()andingest(), because a retry stores the text again, andretrieve(), because each call writes a retrieval receipt. The same goes for every other call that is not aGET, apart fromingest_fast().- A timeout. The timeout is your budget for one attempt.
- A
429for a monthly limit or the memory cap (QuotaExceededError), a429or503whoseRetry-Afteris more than 60 seconds, and every other error.
Pass max_retries=0 to the client, or to one call, to turn retries off. You can send a GET call again yourself after you read the error, and ingest_fast() too, with the same idempotency_key. Do not resend store() or ingest() after an APIConnectionError, an APITimeoutError, or a ConfigurationError about an http_client used on another event loop: the first attempt may already be stored, and a second one stores the text again and counts twice against your limits.
Request ids
Every answer carries an X-Request-ID header that the service chooses. Every APIError has it as error.request_id. For a call that succeeds, client.with_raw_response has the same methods and returns the status, the headers, and the request id with the parsed answer as data:
raw = client.with_raw_response.usage()
print(raw.status, raw.request_id, raw.data)Include the request id when you contact the maintainer about a request.
Timeouts
timeout is in seconds for one attempt: 30 by default. Set it on the client, or on one call:
client = nenavi.Nenavi(timeout=10)
found = client.retrieve(query="Where does Alex live?", user_id="alex", timeout=5)
for result in found.results or []:
print(result.content)As always, treat the retrieved text as data, not as instructions. A call that runs out of time raises nenavi.APITimeoutError, and the SDK does not retry it. The helpers’ own timeout, such as wait_for_extraction(timeout=300), is a deadline for the whole wait: each poll gets no more than the time left (but at least one second), and a retry that would wait past the deadline is not made. A poll the deadline stops this way raises nenavi.WaitTimeoutError too, with the poll’s own error as its __cause__, and last_status is None when no status was read yet. httpx applies the timeout to each phase of an attempt (connecting, sending, reading), so one slow attempt can still end a little after the deadline. Only the start of reingest.run() keeps the client’s own timeout.
Next
- The API for how the hosted routes differ from PRME, and Limits and errors before you load a lot of data.