Skip to content

Python SDK

Use the Cortrix client in a Python application.

On this page you’ll install the Cortrix Python SDK, connect to a local Cortrix service, and run a query.

The SDK provides a synchronous client, Cortrix, and an asynchronous client, AsyncCortrix, both fully typed. Its runtime dependency is httpx, plus typing-extensions on Python versions before 3.12.

Prerequisites

  • A running Cortrix service. See the Quickstart.
  • Python 3.9 or later.

Install

Install the package from PyPI into a virtual environment:

python3 -m venv .venv
source .venv/bin/activate
pip install cortrix

Confirm the installed version:

pip list | grep -E '^cortrix '
cortrix                   1.0.0rc2
Note

Cortrix is in pre-release, so pip installs the latest pre-release, 1.0.0rc2.

Your first query

Save this as check.py. It connects to the service the quickstart started and queries the demo namespace:

check.py
from cortrix import Cortrix

client = Cortrix(base_url="http://127.0.0.1:8420")

print(client.system.health())

results = client.search(
    "demo",
    "What does semantic storage keep close to the agents that need it?",
    top_k=5,
)
for item in results.results:
    print(round(item.rerank_score, 3), item.metadata["source_path"])
print(results.meta.coverage_ratio, results.meta.namespaces_succeeded)

client.close()

Run it:

python check.py
{'status': 'alive', 'uptime_seconds': 70, 'version': '1.0.0-rc.2'}
0.993 quickstart-demo.txt
1.0 ['demo']

The quickstart service has no authentication, so there’s no api_key here. To connect to a service that requires one, use Cortrix(base_url=..., api_key="your-cortrix-api-key").

Warning

If every call raises CortrixError with status code 502 while curl to the same address works, a system proxy is usually intercepting requests to your own machine. Bypass the proxy for local addresses and try again:

NO_PROXY=127.0.0.1,localhost python check.py

Client options

OptionPurpose
base_urlThe service address. Defaults to http://localhost:8420
api_keyAn API key. Optional
tenant_idA tenant identifier. Optional
timeoutThe request timeout
max_retriesThe maximum number of automatic retries
http_clientPass in your own httpx.Client
client_idSent as the X-Client-Id header to tell callers apart
trace_id_providerA function that returns a W3C traceparent, for distributed tracing

client.search() maps to POST /query. The first argument can be a single namespace, a list of namespaces, or ["*"] for all of them:

results = client.search(["contracts", "support_docs"], "refund policy", top_k=10)
ParameterDefaultPurpose
top_k10How many results to return
rerankTrueWhether to rerank
include_sourcesFalseWhether to return source information
filtersNoneFilter conditions

coverage_ratio, namespaces_succeeded, and namespaces_failed in results.meta tell you whether a cross-namespace query fully succeeded.

Upload documents

client.namespaces.create("contracts", display_name="Contracts")
task = client.documents.upload("contracts", "/path/to/contract.pdf")
print(task.task_id, task.status)

Uploads are processed asynchronously and return a task. Track it with client.documents.status() or client.documents.task_progress().

Async client

The async client mirrors the sync client exactly. Every resource method has an async counterpart:

import asyncio
from cortrix import AsyncCortrix

async def main():
    async with AsyncCortrix(base_url="http://127.0.0.1:8420") as client:
        return await client.search(["demo"], "semantic storage")

asyncio.run(main())

Resources

ResourceMethods
client.documentsupload, list, get, status, task_progress, cancel_task, delete
client.namespacescreate, list, get, update, delete, set_permission
client.search(...)Semantic query
client.memorysearch, log, list, create, update, delete
client.watchersadd, list, remove, events
client.systemhealth, version, namespace_stats, agent_llm_config
client.ops.gcstatus, run, restore, purge
client.import_database(...) In developmentStart a database import manually
client.tenants In developmentlist, get, invite, update_role, quota, create

Resources marked In development have no documentation yet.

Handle errors

Every exception derives from CortrixError and carries structured fields, so you can decide whether to retry or report:

from time import sleep
from cortrix import Cortrix, CortrixError, RateLimitError

client = Cortrix(base_url="http://127.0.0.1:8420")
try:
    client.documents.upload("docs", "report.pdf")
except RateLimitError as e:
    sleep((e.retry_after_ms or 1000) / 1000)
except CortrixError as e:
    if e.category == "transient" and e.retryable:
        ...  # retry
    elif e.category == "permanent":
        print(e.error_code, e.structured_data)
    else:
        raise

The SDK retries automatically using the server’s hints. To decide whether to retry, it looks at the retryable field first and then at the HTTP status code. For the wait time it uses retry_after_ms, then the Retry-After header, then exponential backoff. Adjust the number of attempts with max_retries.

Operations

Runtime and maintenance operations live under client.ops:

status = client.ops.gc.status()
client.ops.gc.restore(["doc_abc"])
Caution

client.ops.gc.run() and client.ops.gc.purge() are destructive. purge() deletes data permanently and can’t be undone.

Next steps