Metadata-Version: 2.4
Name: aitrix-sdk-py
Version: 0.1.0
Summary: Aitrix Python SDK — a thin, typed, OpenAI-compatible client that surfaces inline governance metadata (cost, PII/redaction, policy, latency) and a stable error taxonomy.
Author-email: Aitrix <info@aitrix.ai>
Maintainer-email: Aitrix <info@aitrix.ai>
License-Expression: Apache-2.0
Project-URL: Homepage, https://aitrix.ai
Project-URL: Documentation, https://github.com/aitrixsecurity/aitrix-sdk-py/blob/main/docs/USER-GUIDE.md
Project-URL: Repository, https://github.com/aitrixsecurity/aitrix-sdk-py
Project-URL: Issues, https://github.com/aitrixsecurity/aitrix-sdk-py/issues
Keywords: aitrix,llm,ai-gateway,governance,ai-security,openai-compatible,pii,dlp,guardrails
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
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: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Security
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx>=0.27.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
Requires-Dist: ruff>=0.4.0; extra == "dev"
Dynamic: license-file

# Aitrix Python SDK (`aitrix-sdk-py`)

A thin, typed, **OpenAI-compatible** client for the Aitrix gateway. The hard part
— governance (multi-engine DLP/PII, policy + quota, trajectory) — is server-side.
This SDK just exposes the contract: an OpenAI-shaped response **plus inline
governance metadata**, and a stable, typed error taxonomy.

## Install

```bash
pip install aitrix-sdk-py
```

Single runtime dependency: `httpx`; ships a typed wheel (`py.typed`), no
install-time code. Full [user guide](docs/USER-GUIDE.md).

**Self-hosted / air-gapped gateways** can serve this same wheel from the
gateway's built-in private index instead of public PyPI:

```bash
pip install --extra-index-url https://<your-gateway>/sdk/simple/ \
            --trusted-host <your-gateway> aitrix-sdk-py
```

`--extra-index-url` pulls `aitrix-sdk-py` from your gateway and `httpx` from
PyPI. Drop `--trusted-host` for a CA-trusted cert. Browse
`https://<your-gateway>/sdk/` for the portal + user guide.

## Usage

```python
from aitrix.sdk import Aitrix

client = Aitrix(api_key="sk-...", base_url="https://gateway.example/v1")
resp = client.chat.create(
    model="openai/gpt-4o-mini",
    messages=[{"role": "user", "content": "hi"}],
)

print(resp.content)                          # assistant text
print(resp.aitrix_metadata.cost_usd)         # what it cost
print(resp.aitrix_metadata.pii_detected)     # was PII found/redacted
print(resp.aitrix_metadata.latency.total_ms) # latency breakdown
print(resp.usage.prompt_tokens)              # real token split
```

- `client.chat.completions.create(...)` is a deliberate OpenAI drop-in alias.
- Config resolves from args → env (`AITRIX_API_KEY`, `AITRIX_BASE_URL`) → default.
- `base_url` includes the `/v1` prefix (e.g. `https://host:8443/v1`).
- Async: `from aitrix.sdk import AsyncAitrix` — identical API with `await`.

### Governance metadata (`resp.aitrix_metadata`)

| Field | Meaning |
|---|---|
| `request_id` | correlate with gateway audit logs |
| `provider_selected` / `model_resolved` | what actually served the request |
| `cost_usd` / `input_cost_usd` / `output_cost_usd` | billed cost |
| `pii_detected` / `redaction_applied` / `entity_types_detected` | DLP outcome |
| `input_violation` / `output_violation` / `output_action` | guardrail outcome |
| `policy_rule_id` | which policy rule matched |
| `is_agent` | agent-session flag |
| `cached` | served from semantic cache |
| `latency` | `{ total_ms, input_guardrails_ms, provider_ms, output_guardrails_ms, pii_ms }` |
| `tokens` | `{ prompt, completion, total }` |

Unknown fields a newer server adds are preserved on `aitrix_metadata.raw` and
ignored by the typed fields (forward-compatible).

## Error handling

Every error subclasses `AitrixError` and carries `status_code`, `code`, `request_id`:

```python
from aitrix.sdk import Aitrix, PolicyBlockError, QuotaExceededError, RateLimitError

try:
    resp = client.chat.create(model="...", messages=[...])
except PolicyBlockError as e:
    print("blocked:", e.code, e.policy_result)
except QuotaExceededError as e:
    print("out of budget:", e.request_id)
except RateLimitError:
    ...
```

| Exception | Trigger |
|---|---|
| `AuthenticationError` | 401 |
| `PermissionDeniedError` | 403 policy-rule denial (`POLICY_DENIED`, `IMPLICIT_DENY`, …) |
| `PolicyBlockError` | guardrail/DLP/content block, `INTEGRATION_FAILURE` |
| `QuotaExceededError` | 402 / quota codes |
| `RateLimitError` | 429 |
| `ModelNotFoundError` | 404/400 unknown model (`suggested_model`, `allowed_models`) |
| `UpstreamError` | 502 provider failure |
| `APIError` | other 5xx |

## Streaming

```python
stream = client.chat.create(model="openai/gpt-4o-mini",
                            messages=[{"role": "user", "content": "hi"}], stream=True)
for piece in stream:          # yields assistant text deltas
    print(piece, end="", flush=True)
print(stream.aitrix_metadata.cost_usd)   # governance metadata from the final chunk
print(stream.usage.total_tokens)
```

Async: `s = await client.chat.create(..., stream=True)` then `async for piece in s`.

> The gateway runs the **full governance pipeline** before streaming, so all
> guardrails apply — the response is complete (and checked) before the first
> chunk. You get the OpenAI SSE wire-format and final `aitrix_metadata`, but not
> token-by-token latency yet (true passthrough is future work).

## Listing models

```python
for m in client.models.list(provider="openai", capability="vision"):
    print(m.id, m.context_window, m.input_cost_per_token)
```

Filters: `family` (substring of id), `capability` (`thinking` / `web_search` / `vision`), `provider`.

## Notes

- For self-signed gateways in testing, pass `verify=False` or your own
  `http_client=httpx.Client(...)`.

## License & contact

Apache-2.0 — see [LICENSE](LICENSE). The SDK is a thin open client; the
governance pipeline it talks to is the [Aitrix](https://aitrix.ai) gateway.

Questions, support, security reports: **info@aitrix.ai**
