Metadata-Version: 2.5
Name: nicia-ai
Version: 0.1.0
Summary: Typed sync and async Python SDK for the Nicia API
Project-URL: Homepage, https://nicia.ai
Project-URL: Documentation, https://nicia.ai/docs/
Project-URL: Repository, https://github.com/nicia-ai/nicia
Project-URL: Issues, https://github.com/nicia-ai/nicia/issues
License-Expression: MIT
License-File: src/nicia/LICENSE
Classifier: Programming Language :: Python :: 3
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx>=0.27
Requires-Dist: pydantic>=2.7
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == 'dev'
Requires-Dist: mypy>=1.11; extra == 'dev'
Requires-Dist: pytest-asyncio>=1; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.11; extra == 'dev'
Requires-Dist: twine>=6; extra == 'dev'
Description-Content-Type: text/markdown

# Nicia Python SDK

Read and write governed knowledge in Nicia with typed, synchronous and
asynchronous clients. Spaces are addressed at `/v1/brains/{handle}` on the HTTP
API. The SDK requires Python 3.10 or newer.

```bash
python -m pip install nicia-ai
```

## Provision a space and read context

Use an organization management key (`nsk_`) to provision a space and mint a
space key (`nbk_`). Give your workload a key with the capabilities it needs.
Pass `organization_id` when a legacy management key needs to select an
organization.

```python
import os

from nicia import DocumentInput, NiciaOrgClient

handle = "tenant:demo"
with NiciaOrgClient(api_key=os.environ["NICIA_MANAGEMENT_KEY"]) as org:
    provisioned = org.put_space(
        handle,
        name="Demo",
        purpose="Decisions and operating knowledge for the demo tenant",
        metadata={"customer": "demo"},
    )
    minted = org.mint_space_key(provisioned.space.handle, name="pipeline")
    # Store minted.secret in your secrets manager. The API shows it once.
    if minted.secret is not None:
        with org.space(handle, key=minted.secret) as space:
            space.write_documents(
                DocumentInput(id="kickoff", title="Kickoff", text="The pilot starts in July.")
            )
            answer = space.context("When does the pilot start?")
            print(answer.text)
            print(answer.citations)
            print(space.receipt_now(answer.receipt).changed)
```

Use `NiciaSpaceClient(handle, api_key=...)` directly when you already have a
space key. Calling `org.space(handle)` without a key uses the management
credential for the selected space. The async clients expose the same methods
with `await`. `org.space()` binds a client without making an HTTP request.

```python
from datetime import date

from nicia import AsyncNiciaSpaceClient


async def pilot_context(space_key: str) -> str:
    async with AsyncNiciaSpaceClient("tenant:demo", api_key=space_key) as space:
        result = await space.context(
            "When did the pilot start?",
            valid_at=date(2026, 7, 15),
            known_at="2026-07-16T00:00:00Z",
        )
        return result.text
```

`valid_at` selects when facts applied. `known_at` selects what Nicia had
recorded by that time. Historical context uses the default branch. Use the
returned `receipt` to check what changed after the read.

## Documents, records, and review

`write_documents` accepts a single `DocumentInput` or a sequence of up to
100. Both forms accept dictionaries. An explicit document ID upserts that
address. Pass a timezone-aware `datetime` or an ISO 8601 timestamp string with an offset as
`occurred_at`. The result has `document` for a single write and `documents`
for a batch.

```python
from nicia import DocumentAddress, DocumentCitation, RecordInput

write = space.write_records(
    RecordInput(
        id="pilot-start",
        kind="decision",
        label="Start the pilot in July",
        citations=[
            DocumentCitation(
                document=DocumentAddress(id="kickoff"),
                quote="The pilot starts in July.",
            )
        ],
    ),
    idempotency_key="pilot-start-v1",
)
print(write.change.status)
record_page = space.query("decision")
```

`batch` is an alias for `write_records`. A batch of up to 20 records is
admitted as a unit. Use a record's returned `token` as `if_match` for a
conditional write. `citations` serializes as `evidence`. Use `links` for
named schema relationships. The optional `grounds` shorthand sets the built-in
`based_on` link. Set `citations=[]` to clear a record's citations.

`list_spaces`, `list_documents`, `query`, `attention`, and `findings`
return one page at a time. Pass the result's `next_cursor` as `cursor` to
fetch the next page. To decide a disagreement, use the exact `receipt` from
`get_finding()` and the finding's `support_fingerprint` as
`reviewed_receipt` and `reviewed_fingerprint` in `decide_finding()`.

`create_branch`, `compare_branch`, and `create_proposal` are **preview**
operations. Branch creation and finding decisions require an
`idempotency_key`.

## Export

```python
from pathlib import Path

started = space.export(idempotency_key="nightly-2026-07-16")
settled = space.wait_for_export(started.id)
if settled.status == "completed":
    Path("space.zip").write_bytes(space.download_export(settled.id))
elif settled.status == "failed":
    print(settled.error)
```

Use `get_export()` to check a job independently. `wait_for_export()` returns
the terminal job and raises `NiciaError` with code `export_timeout` if the
polling window expires. `download_export()` returns the ZIP bytes.

## Authentication, errors, and retries

Both clients send `Authorization: Bearer`. Each accepts a custom `base_url`,
`timeout`, and HTTPX `transport`. By default, each client has its own
connection pool. When an organization client is given a custom transport, its
space clients borrow that transport for the lifetime of the organization
client.

`NiciaError` exposes `status`, `code`, `request_id`, `details`, and
`attempts`. Catch `NiciaAuthError`, `NiciaConflictError`,
`NiciaRateLimitError`, or `NiciaValidationError` for a specific response.
Client-side validation has no HTTP status and records zero attempts.

Transport failures and HTTP 429 and 503 responses are retried for GETs and
replay-safe writes carrying an `Idempotency-Key`. Persist one key per logical
write and reuse it when retrying that write. The SDK sends supplied keys on
space provisioning, document, and proposal writes, where the API has no replay
guarantee. These writes and the receipted context and query POSTs are each sent
once. Omit `mode` when updating a space to keep its current admission mode.
`max_attempts` defaults to three. The client honors `Retry-After` and returns
the error if the requested delay exceeds 60 seconds.

## Development and publishing

From this directory, install the development extras and run the checks.

```bash
python -m pip install '.[dev]'
python -m pytest
python -m ruff check .
python -m mypy --strict
python -m build
python -m twine check --strict dist/*
```

The release workflow builds and checks both distributions for pull requests
that change the SDK and when `pyproject.toml` changes on `main`.
Manual runs can set `dry_run` to build
and retain the distributions as workflow artifacts. Live runs skip versions
already on PyPI.

Configure a PyPI Trusted Publisher for project `nicia-ai`, repository
`nicia-ai/nicia`, workflow `publish-pypi.yml`, and GitHub environment
`pypi`. Use a pending publisher for the first release. The publishing job
uses GitHub OIDC.
