Metadata-Version: 2.4
Name: qaiss-sdk
Version: 0.1.1
Summary: Official Python SDK for QAISS — Non-blocking telemetry, observability, and passive auditing for AI agents and LLMs.
License-Expression: Apache-2.0
Project-URL: Homepage, https://qaiss.com
Project-URL: Documentation, https://docs.qaiss.com
Project-URL: Repository, https://github.com/QodeRepo/qaiss-tools-sdk
Project-URL: Changelog, https://github.com/QodeRepo/qaiss-tools-sdk/blob/main/CHANGELOG.md
Project-URL: Issues, https://github.com/QodeRepo/qaiss-tools-sdk/issues
Keywords: llm,ai-agents,observability,telemetry,opentelemetry,guardrails,monitoring,hallucination-detection,fastapi,flask,django
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
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 :: System :: Monitoring
Classifier: Framework :: AsyncIO
Classifier: Typing :: Typed
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: opentelemetry-api>=1.20.0
Requires-Dist: opentelemetry-sdk>=1.20.0
Requires-Dist: httpx>=0.24.0
Requires-Dist: pydantic<3.0.0,>=1.10.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Requires-Dist: respx>=0.20.0; extra == "dev"
Dynamic: license-file

# QAISS SDK Monorepo (`QodeRepo-sdk`)

Welcome to the **QAISS SDK Monorepo**. This repository contains the lightweight, non-blocking client SDKs that power the **QAISS LLM Security & Observability Platform**.

---

## 🎯 The Mission
QAISS is an AI observability and auditing platform. The Python SDK captures selected LLM, HTTP, database, and explicitly wrapped tool activity. Capture depth depends on the integration: automatic database hooks generally record query metadata, while wrapped application tools can capture their returned values. A compatible event-ingestion and evaluation backend is required for judge results; the SDK itself records telemetry and does not produce those verdicts.
The QAISS backend can assess observed tool choice, identity mismatches, and a
limited set of answer claims. A missing event or an unknown verdict is not a pass.
The current output check compares one structured order-status result with one
final response; it does not verify every claim in an answer.

---

## 📂 Repository Structure

```text
QodeRepo-sdk/
├── python/
│   ├── pyproject.toml             # Packaging & build configuration (v0.1.1)
│   └── qaiss/
│       ├── __init__.py            # 1-line init (`qaiss.init()`) & public exports
│       ├── core.py                # Pure Python framework-agnostic request engine
│       ├── asgi.py                # Universal ASGI 3.0 middleware (FastAPI, Litestar, Quart)
│       ├── wsgi.py                # Universal WSGI PEP 3333 middleware (Flask, Bottle, Falcon)
│       ├── django_middleware.py   # Django native middleware (with request.user visibility)
│       ├── middleware.py          # Backward-compat shim
│       ├── client.py              # QaissClient core runtime & lifecycle manager
│       ├── context.py             # Async/thread-isolated ContextVar security context
│       ├── decorator.py           # @client.track_tool & @client.track_agent decorators
│       ├── instrumentation.py     # Universal choke-point monkey-patching & noise filtering
│       ├── models.py              # Pydantic wire schema (QaissEventModel, SecurityContext)
│       ├── redaction.py           # PII scrubber (Luhn credit cards, SSN, Emails, sensitive keys)
│       ├── truncation.py          # Smart structural field-level payload truncator (64 KB)
│       └── transport.py           # Non-blocking bounded background worker (micro-batching)
├── tests/                         # Comprehensive unit, integration, and concurrency test suite
├── docs/                          # Architecture & client integration guides
├── shared/
│   └── schema.json                # Universal JSON Schema contract
└── README.md
```

---

## 🌐 Framework Support: Universal Protocol Architecture

QAISS provides **framework independence** via protocol-level adapters built over a single, zero-dependency core engine (`QaissRequestEngine`):

### 1. Universal Coverage (Zero SDK Code for New Frameworks)
- **`QaissASGIMiddleware` (ASGI 3.0)**: Supports **every** current and future ASGI framework (FastAPI, Starlette, Litestar, Quart, BlackSheep, Sanic, Django ASGI). Features immediate chunk passthrough so token-by-token streaming (SSE) is never delayed.
- **`QaissWSGIMiddleware` (WSGI PEP 3333)**: Supports **every** current and future WSGI framework (Flask, Bottle, Pyramid, Falcon, CherryPy, Django WSGI).

### 2. Optional Enhanced Integration
- **`QaissDjangoMiddleware`**: A thin translator over `QaissRequestEngine` that extracts Django's post-auth `request.user` which is only visible within Django's internal middleware pipeline.

---

## 🚀 Quickstart (Python)

### 1. Installation
```bash
pip install qaiss-sdk
```

### 2. Framework-Independent Integration

#### A. FastAPI / Starlette / Litestar / Quart (ASGI)
```python
from fastapi import FastAPI
import qaiss
from qaiss import QaissASGIMiddleware

app = FastAPI()
client = qaiss.init(api_key="your_api_key", environment="production")
app.add_middleware(QaissASGIMiddleware, qaiss_client=client)
```

#### B. Flask / Bottle / Falcon / Pyramid (WSGI)
```python
from flask import Flask
import qaiss
from qaiss import QaissWSGIMiddleware

app = Flask(__name__)
client = qaiss.init(api_key="your_api_key", environment="production")
app.wsgi_app = QaissWSGIMiddleware(app.wsgi_app, qaiss_client=client)
```

#### C. Django (`settings.py`)
```python
MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    # ... other middlewares ...
    "qaiss.django_middleware.QaissDjangoMiddleware",  # ⬅️ Add 1 line
]

QAISS_API_KEY = "your_api_key"
QAISS_ENVIRONMENT = "production"
```

---

## ⚙️ Key Technical Guarantees
1. **Automatic hooks for supported entry points:** `qaiss.init()` patches selected LLM, HTTP, and agent-framework APIs. Arbitrary application functions must be passed to `wrap_tools(...)` or decorated with `track_tool`.
2. **ASGI response streaming:** The ASGI middleware forwards response chunks immediately while keeping a bounded internal copy for supported response parsing. This does not guarantee capture of streamed final text.
3. **Request context isolation:** Request-scoped `ContextVar` state isolates SDK context across async requests when integrations use the same client and request context.
4. **Local redaction and truncation:** Selected PII and credential patterns are scrubbed before serialization; this is a best-effort filter, not a guarantee that every secret format is detected.
5. **Bounded background delivery:** Events are queued and batched for upload. Queue overflow, backend rejection, prolonged outages, or process termination can still lose events.

`client.flush()` now returns `True` only after queued batches receive complete
QAISS acknowledgements. `client.delivery_status()` exposes pending, accepted,
acknowledged, failed-batch, and dropped-event counts. Delivery remains in memory;
an outage does not create a durable replay queue.

For wrapped tools, QAISS records the tool input and returned value in the event.
When identity fields are present, `security_context.tool_target_identity_id`
records the requested target and `security_context.returned_owner_ids` records
owner-like IDs observed in the returned data. These are logged observations;
the backend needs the application's access policy to decide whether an access
or disclosure is permitted.

## Tool-choice Action Judge

Create an SDK installation in the QAISS backend with `POST /api/v1/sdk/installations`
using your QAISS user token. The response returns a `qsk_...` key once. Supply that
key as `QAISS_API_KEY` or `qaiss.init(api_key=...)`; do not use your chatbot's user ID
or a target API credential as the SDK key. The default ingestion URL is
`https://api.qaiss.com/api/v1/events`; set `QAISS_BACKEND_URL` for a different deployment.

With the ASGI, WSGI, or Django request adapter, the SDK records the user question
before the bot runs and groups later events under a `turn_id`. `@client.track_agent`
does the same for an agent function outside HTTP middleware. Supported OpenAI and
Anthropic non-streaming hooks observe offered tool definitions and selected tool
calls; wrapped tools report their executed name and available Python/framework
metadata. The SDK sends observations only. QAISS evaluates tool relevance in its
backend Action Judge and exposes the report at
`GET /api/v1/sdk/installations/{installation_id}/turns/{turn_id}/action-report`.
Missing prompts, tool metadata, streamed selections, or unobserved code paths are
reported as incomplete evidence, not a guaranteed pass.

#### Exact tool selection-to-execution links

The SDK records the provider's selected tool-call ID. When a supported agent
framework passes that same ID to a wrapped function as `tool_call_id` or
`tool_use_id`, the SDK records it with the execution and links it to the LLM
decision. QAISS confirms the exact execution only when the ID is unique and the
selected and executed tool names and captured JSON arguments match. Different
arguments are reported as a mismatch; arguments that cannot be compared remain
unknown.
If the framework does not expose the ID, or IDs are duplicated or conflicting,
the report says the link is unknown. It never treats an order/customer/resource
ID, matching tool name, or event order as a provider call ID. This observation
does not alter the bot's arguments or dispatch behavior.

## Cross-user observations

The SDK compares no identities locally. It records separate evidence for the
request actor, the model's selected arguments, the executed tool's target, and
owner-like fields in returned data. QAISS makes the comparison in
`GET /api/v1/sdk/installations/{installation_id}/turns/{turn_id}/cross-user-report`;
the Action Judge report also includes a `cross_user` section. The SDK needs no
customer database credentials. Wrapped tool outputs and supported SQLite,
SQLAlchemy, Django, and PyMySQL fetch hooks inspect only data already returned
to the bot; database hooks send bounded owner-field evidence, not full rows.

The report distinguishes an observed ID mismatch from an authorization
violation. It returns unknown when no trustworthy actor, comparable owner field,
or linked fetch is observed. `X-User-ID` headers and JWTs without full claim
validation are unverified actor evidence. A returned `order_id` or `account_id`
alone cannot establish who owns the order or account. Unsupported drivers and
unobserved code paths remain coverage gaps.
