Metadata-Version: 2.5
Name: nvisionx
Version: 0.3.0
Summary: Python client for the NVISIONx Nx Platform API: ingest, search, agents and chat over your business records.
Project-URL: Homepage, https://platform.us.nvisionx.ai
Project-URL: Repository, https://github.com/Nvision-x/nx-saas-platform-api-python
Project-URL: Issues, https://github.com/Nvision-x/nx-saas-platform-api-python/issues
Author: NVISIONx
License-Expression: MIT
License-File: LICENSE
Keywords: api,mcp,nvisionx,nx,rag,records,sdk,search
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx<1,>=0.27
Requires-Dist: pydantic<3,>=2.7
Requires-Dist: typing-extensions>=4.7
Description-Content-Type: text/markdown

# NVISIONx Nx Platform Python library

[![CI](https://github.com/Nvision-x/nx-saas-platform-api-python/actions/workflows/ci.yml/badge.svg)](https://github.com/Nvision-x/nx-saas-platform-api-python/actions/workflows/ci.yml)

The official Python client for the [NVISIONx Nx Platform](https://platform.us.nvisionx.ai) API
([API docs](https://platform.us.nvisionx.ai/docs)). Nx turns the documents in your data
estate into **business records** (record type, owner, sensitivity, retention), makes them searchable, and exposes them
to agents.

This library covers the data plane, which is everything an API token can call: ingest, documents, jobs, search,
hosted agents, chat, data sources, MCP settings, models, usage and budgets. It ships typed models, sync and async clients, automatic retries,
cursor pagination and streaming chat.

## Install

```sh
pip install nvisionx
```

Python 3.10 or newer.

## Quickstart

Create an API token in the Nx console under **API tokens**, then:

```sh
export NX_API_KEY="nx_live_…"
```

```python
from nvisionx import Nx

nx = Nx()

job = nx.documents.ingest(file="Northwind_MSA_2024.pdf", metadata={"department": "legal"})
job = nx.jobs.wait(job.id)
print(job.status, job.record_types)

results = nx.search("indemnification cap in vendor contracts", limit=5)
for result in results.results:
    print(result.title, result.record_type, result.score)
```

## Authentication

Every call sends the token as `Authorization: Bearer …`. Pass it as `api_key=` or set `NX_API_KEY`; set `NX_BASE_URL`
(or `base_url=`) for an API origin other than the default.

### Workspaces

A token reaches the workspaces chosen when it was created. A token that reaches one workspace acts on it. A token that
reaches several needs the workspace for each call: pass `workspace=` (or set `NX_WORKSPACE`), and use
`with_options(workspace=…)` to switch. The option sends the `Nx-Workspace` header, so setting the header yourself with
`default_headers` works too.

```python
nx = Nx(workspace="ws_legal")
finance = nx.with_options(workspace="ws_finance")  # shares the connection pool

nx.with_options(default_headers={"Nx-Workspace": "ws_finance"})  # the same thing
```

### Short-lived tokens from MCP

An agent connected to the Nx MCP server can mint a token for code it writes: the `create_api_token` tool, when the
connection allows it, returns a token for one workspace that expires after 15 minutes by default (60 at most), holds
only the scopes and data sources asked for, and comes with a ready snippet:

```python
from nvisionx import Nx

nx = Nx(
    api_key="nx_live_…",
    base_url="https://platform.us.nvisionx.ai",
)
```

Such a token reaches exactly one workspace, so it needs no `workspace=`. When it expires, calls raise
`AuthenticationError`; ask for a new one.

## Configuration

```python
from nvisionx import Nx

nx = Nx(
    api_key="nx_live_…",
    timeout=30.0,
    max_retries=3,
)
```

| Option | Environment variable | Default |
| --- | --- | --- |
| `api_key` | `NX_API_KEY` | required |
| `base_url` | `NX_BASE_URL` | `https://platform.us.nvisionx.ai` |
| `workspace` | `NX_WORKSPACE` | the token's workspace; required for a token that reaches several |
| `timeout` | | 60 s; 300 s for agent runs and chat answers; no write timeout for uploads |
| `max_retries` | | 2 |
| `default_headers` | | |
| `http_client` | | your own `httpx.Client` / `httpx.AsyncClient` (proxies, transports, limits) |

`with_options` returns a copy that shares the connection pool:

```python
nx.with_options(timeout=120.0, max_retries=0).search("retention schedule")
```

## Ingest

Pass `url=` for a document Nx should fetch, or `file=` to upload. `file=` accepts a path, bytes, an open binary file,
a `(filename, content)` or `(filename, content, content_type)` tuple, or a list of any of these.

```python
job = nx.documents.ingest(url="https://files.example.com/signed/msa.pdf")

job = nx.documents.ingest(
    file=["contracts/msa.pdf", ("notes.txt", b"Renewal due Q3", "text/plain")],
    metadata={"department": "legal"},
    classify=True,
)

job = nx.jobs.wait(job.id, poll_interval=2.0, timeout=600.0)
if job.status == "completed":
    for doc in job.classified or []:
        print(doc)
```

`jobs.wait` returns the job once it is `completed` or `failed`, and raises `JobTimeoutError` if it is neither by the
timeout. `jobs.summary()` reports jobs by status, the documents still in the pipeline and the last 24 hours of ingest.

## Documents

```python
for doc in nx.documents.list(source_id="src_123", q="msa"):
    print(doc.name, doc.size, doc.ingest_status)

detail = nx.documents.get("doc_123")
parsed = nx.documents.parsed("doc_123")
print(parsed.parser, parsed.page_count, parsed.text[:200])

print(nx.documents.summary())
```

`documents.parsed` raises `NotFoundError` until the document has been parsed. It returns up to 1 MB of the Markdown;
read on with `offset=parsed.next_offset`, or download the whole text with `documents.parsed_text`:

```python
parsed = nx.documents.parsed("doc_123")
text = parsed.text
while parsed.next_offset is not None:
    parsed = nx.documents.parsed("doc_123", offset=parsed.next_offset)
    text += parsed.text

markdown = nx.documents.parsed_text("doc_123")
```

### Matches in a document

`documents.matches` finds every match of one or more patterns in a document's parsed text, in document order, with
the text around each. Send several patterns in one call; each match's `pattern` is its index in `patterns`. A search
result's `id` is a document id here.

```python
for m in nx.documents.matches("doc_123", patterns=[r"SUBJ-\d{4}", r"CASE-\d{6}"], context_chars=80):
    print(m.pattern, m.text, m.before, m.after, m.start)
```

`mode="literal"` matches exact text instead of RE2 regular expressions, and `case_sensitive=False` ignores case. A page
can hold fewer than `limit` matches, or none, while more follow, so iterate the page (or call `next_page()`) rather
than stopping at a short one. Each page is billed as a search. `byte_start` is the offset to pass to
`documents.parsed` to read on from a match.

### Chunks

`documents.chunks` lists the passages a document was split into for search, in document order, with their place in
the parsed text, pages, section and heading:

```python
chunks = nx.documents.chunks("doc_123", limit=200)
print(chunks.body.total)
for chunk in chunks:
    print(chunk.ordinal, chunk.page_start, chunk.section, chunk.text[:80])
```

A search passage's `ordinal` is a chunk's `ordinal`. If the document is indexed again while you page, the next page
raises `ConflictError`: start over.

### Delete and re-parse

Delete one document with `documents.delete`, or up to 200 at once by id. To delete by filter, run a dry run first,
then send its count back as `expected_count`. If the matching documents change in between, nothing is deleted and the
call raises `ConflictError`:

```python
nx.documents.delete_many(ids=["doc_1", "doc_2"])

preview = nx.documents.delete_many(filter={"source_id": "src_123", "q": "draft"}, dry_run=True)
nx.documents.delete_many(filter={"source_id": "src_123", "q": "draft"}, expected_count=preview.matched)
```

`documents.reparse` reads failed documents again from their stored originals, by id or by filter, with the same dry
run and `expected_count` rules:

```python
preview = nx.documents.reparse(filter={"source_id": "src_123"}, dry_run=True)
nx.documents.reparse(filter={"source_id": "src_123"}, expected_count=preview.matched)
```

## Search

```python
from nvisionx.types import SearchFilters

response = nx.search(
    "termination for convenience",
    mode="hybrid",
    filters=SearchFilters(record_type=["contract"], sensitivity=["confidential"]),
    limit=10,
)
```

`filters` also accepts a plain `dict`. `dense_mode` picks how the semantic part reads vectors: `full` (exact),
`fast` (an approximate index, for large workspaces) or `auto` (the default).

Every mode pages: pass the response's `next_cursor` back as `cursor`, with the same arguments, until it is `None`.
Each page is billed as a search.

```python
response = nx.search("data retention", limit=50)
while response.next_cursor:
    response = nx.search("data retention", limit=50, cursor=response.next_cursor)
```

### Regex search

`mode="regex"` finds documents with a passage matching an RE2 regular expression, one result per document, most matches
first. `regex.patterns` searches several patterns together instead of `query`, and `require="all"` keeps only documents
where every pattern matches. `passages_per_document` returns up to 20 matching passages per result.

```python
from nvisionx.types import RegexOptions

response = nx.search(
    mode="regex",
    regex=RegexOptions(patterns=[r"SUBJ-\d{4}", r"PROT-[A-Z]{2}\d{3}"], require="all", passages_per_document=3),
)
for result in response.results:
    print(result.title, result.document_match_count, result.document_pattern_counts)
    for passage in result.passages or []:
        for h in passage.highlights:
            print(passage.ordinal, h.pattern, passage.snippet[h.start : h.end])
```

`match_count` and `pattern_counts` count the result's best passage; `document_match_count`,
`document_passage_count` and `document_pattern_counts` count the whole document (`counts_are_lower_bound` when the
engine stopped counting early). A highlight's `pattern` is the index of the pattern that matched there. To get every
match in one document, use `documents.matches`.

## Chat

Conversations keep context across questions. Answers cite records with `[n]` markers that match
`citations[].marker`.

```python
conversation = nx.chat.conversations.create(title="Vendor risk")

answer = nx.chat.messages.create(conversation.id, content="Which vendor contracts cap indemnity below $2M?")
print(answer.content)
for citation in answer.citations or []:
    print(citation.marker, citation.title)
```

Stream the answer as the agent works:

```python
with nx.chat.messages.stream(conversation.id, content="Summarize the Northwind MSA") as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
    message = stream.until_done()
```

Iterate the stream itself to see every `ChatStreamEvent`: `status`, `step`, `delta` and `complete`. A failed answer
raises `StreamError`.

## Agents

```python
run = nx.agents.run(
    "Which vendor contracts cap indemnity below $2M?",
    tools=["search_records", "get_record"],
    max_tool_calls=10,
)
print(run.answer, run.citations, run.cost_usd)
```

## MCP

To connect an agent framework to Nx over the [Model Context Protocol](https://modelcontextprotocol.io), use the
official `mcp` package with the hosted endpoint and your token:

```python
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client

async with streamablehttp_client(
    "https://platform.us.nvisionx.ai/mcp", headers={"Authorization": f"Bearer {api_key}"}
) as (read, write, _):
    async with ClientSession(read, write) as session:
        await session.initialize()
        tools = await session.list_tools()
```

A token or OAuth connection that reaches several workspaces works with one MCP connection: the server lists the
workspaces in its instructions and in the `list_workspaces` tool, and every other tool takes a `workspace` argument (a
name or id), so a prompt can say "search the Finance workspace for …".

This library manages the workspace's MCP server:

```python
server = nx.mcp.get()
nx.mcp.update_tool("ingest_document", enabled=False)
```

## Data sources

```python
for source in nx.sources.list().data:
    print(source.name, source.provider, source.status)

nx.sources.sync("src_123")
estate = nx.sources.estate("src_123")
for node in nx.sources.nodes("src_123", q="contracts"):
    print(node)
```

Connecting a new source is an OAuth consent flow: `sources.authorizations.create`, send the person to the returned
URL, then `sources.authorizations.verify` with the callback parameters and `sources.create`.

## Language models

```python
models = nx.models.list()
for model in models.data:
    print(model.id, model.allowed, model.input_price_per_1m_usd)
print(models.preferred)
```

## Usage and budgets

```python
usage = nx.billing.usage(period="2026-10")
print(usage.total_usd, usage.forecast_usd)

nx.budgets.create(scope={"type": "workspace"}, type="soft", limit_usd=500, alert_thresholds=[50, 80, 100])
```

## Pagination

List methods return a page. Iterating a page fetches the following pages as needed:

```python
for job in nx.jobs.list(status="completed"):
    print(job.id)

page = nx.jobs.list(limit=20)
print(page.data, page.next_cursor)
if page.has_next_page():
    page = page.next_page()
```

`page.body` is the whole response of that page, for fields beside the items, such as `total` on
`documents.chunks` or `cost_usd` on `documents.matches`.

## Async

`AsyncNx` has the same surface:

```python
import asyncio
from nvisionx import AsyncNx


async def main() -> None:
    async with AsyncNx() as nx:
        results = await nx.search("data processing agreement")

        async for job in nx.jobs.list():
            print(job.id)

        page = await nx.jobs.list(limit=10)

        stream = await nx.chat.messages.stream("conv_123", content="What changed in the MSA?")
        async with stream:
            async for text in stream.text_stream:
                print(text, end="")


asyncio.run(main())
```

## Errors

Every non-2xx response raises a subclass of `APIStatusError`. Each one carries `status_code`, `type` (the API's error
type), `message`, `detail` (the full typed error body) and `response`.

| Status | Exception | Error types |
| --- | --- | --- |
| 400, 413 | `BadRequestError` | `invalid_request` |
| 401 | `AuthenticationError` | `unauthenticated` |
| 402 | `PaymentRequiredError` | `budget_exceeded`, `spend_limit_reached`, `insufficient_balance` |
| 403 | `PermissionDeniedError` | `insufficient_scope`, `permission_denied` |
| 404 | `NotFoundError` | `not_found` |
| 409 | `ConflictError` | `conflict` |
| 422 | `UnprocessableEntityError` | `unprocessable` |
| 429 | `RateLimitError` | `rate_limited` |
| 5xx | `InternalServerError` | `internal_error` |

Network failures raise `APIConnectionError` (or `APITimeoutError`). Everything derives from `NxError`.

```python
from nvisionx import PaymentRequiredError, PermissionDeniedError

try:
    nx.search("board minutes")
except PermissionDeniedError as e:
    print("token is missing scope", e.required_scope)
except PaymentRequiredError as e:
    print(e.type, e.detail.resolve if e.detail else e.message)
```

## Retries and idempotency

Connection errors, timeouts, 408, 429 and 5xx responses are retried up to `max_retries` times. Retries back off
exponentially, or wait as long as the `Retry-After` header says (up to 60 s). Every `POST`, `PUT`, `PATCH` and `DELETE`
sends an `Idempotency-Key`, and the key stays the same across retries, so a retried write is never applied twice. To
control the key yourself, for example to deduplicate across processes, pass it to `ingest`:

```python
nx.documents.ingest(url=url, idempotency_key=f"ingest-{document_id}")
```

## Models

Responses are [Pydantic](https://docs.pydantic.dev) models, and every model is importable from `nvisionx.types`. Fields
the API adds after a release are kept: read them with `model.model_extra` or `model.model_dump()`.

## Development

```sh
python -m venv .venv && source .venv/bin/activate
pip install -e . --group dev
make check
```

The models in `src/nvisionx/_models.py` and the exports in `src/nvisionx/types.py` are generated from
`openapi/openapi.yaml`, so don't edit them by hand. Run `make generate` after changing the spec.

## License

[MIT](LICENSE)
