adaptensor 0.2.0
Private Document AI Platform with AdaptHex compression
License: MIT
Requires Python: >=3.8
Keywords: ai, document-ai, vector-search, embeddings, rag, semantic-search, nlp, machine-learning, private-ai

# Adaptensor Python SDK

[![PyPI version](https://badge.fury.io/py/adaptensor.svg)](https://badge.fury.io/py/adaptensor)
[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

**Private Document AI Platform** — Upload, index, and search your documents with AI. 100% self-hosted, no external APIs.

## Features

- 🔒 **100% Private** — Your data never leaves your infrastructure
- ⚡ **Fast Search** — Sub-150ms semantic queries across thousands of documents
- 📦 **AdaptHex Compression** — 4-8x smaller vectors with 99.6% accuracy
- 🔌 **Simple API** — Upload, index, search in 3 lines of code
- 🚀 **TPU Accelerated** — 25% cheaper than GPU clouds

## Installation

```bash
pip install adaptensor
```

## Quick Start

```python
from adaptensor import Adaptensor

# Initialize client
client = Adaptensor(api_key="your-api-key")

# Upload documents
client.documents.upload("contract.pdf")
client.documents.upload("report.docx")

# Build search index
result = client.documents.index()
print(f"Indexed {result.total_chunks} chunks")

# Search
results = client.query("liability clauses", top_k=5)

for chunk in results:
    print(f"[{chunk.score:.2f}] {chunk.text[:100]}...")
```

## Authentication

Set your API key via environment variable or pass directly:

```bash
# Environment variable
export ADAPTENSOR_API_KEY="your-api-key"
```

```python
# Or pass directly
client = Adaptensor(api_key="your-api-key")
```

## Upload Documents

### Single File

```python
doc = client.documents.upload("report.pdf")
print(f"Uploaded: {doc.doc_id} ({doc.size_bytes:,} bytes)")
```

### Multiple Files

```python
docs = client.documents.upload_many([
    "doc1.pdf",
    "doc2.pdf",
    "doc3.pdf"
], on_progress=lambda c, t, d: print(f"{c}/{t}: {d.filename}"))
```

### Supported Formats

- PDF (`.pdf`)
- Word (`.docx`)
- Text (`.txt`)
- HTML (`.html`)
- Markdown (`.md`)
- CSV (`.csv`)

## Build Index

After uploading documents, build the search index:

```python
result = client.documents.index()

print(f"Status: {result.status}")
print(f"Documents: {result.documents_processed}")
print(f"Chunks: {result.total_chunks}")
print(f"Time: {result.elapsed_seconds:.1f}s")
```

## Search

### Basic Search

```python
results = client.query("contract termination", top_k=5)

for chunk in results:
    print(f"Score: {chunk.score:.3f}")
    print(f"Text: {chunk.text}")
    print(f"Source: {chunk.metadata.get('filename')}")
    print("---")
```

### Search Result Object

```python
results = client.query("machine learning")

print(f"Query: {results.query}")
print(f"Results: {results.count}")
print(f"Time: {results.elapsed_ms:.1f}ms")

# Iterate through results
for chunk in results:
    print(chunk.text)
```

## Embeddings

Generate embeddings with optional AdaptHex compression:

```python
# With compression (default)
result = client.embed("machine learning algorithms")
print(f"Dimensions: {result.dimensions}")
print(f"Hex: {result.hex_embedding[:50]}...")

# Without compression
result = client.embed("machine learning", quantize=False)
print(f"Vector: {result.embedding[:5]}...")
```

### Compression Modes

| Mode | Compression | Accuracy |
|------|-------------|----------|
| `hex8` | 4x | 99.6% |
| `hex4` | 8x | 95.8% |
| `binary` | 32x | ~85% |

```python
# Use different compression modes
result = client.embed("text", mode="hex4")  # 8x compression
```

## RAG Chat (Coming Soon)

```python
response = client.chat("What are the key terms in the contract?")
print(response)
```

## Error Handling

```python
from adaptensor import (
    Adaptensor,
    AdaptensorError,
    AuthenticationError,
    DocumentNotFoundError,
    APIError
)

try:
    client = Adaptensor(api_key="invalid-key")
    client.query("test")
except AuthenticationError:
    print("Invalid API key")
except APIError as e:
    print(f"API error: {e} (status: {e.status_code})")
except AdaptensorError as e:
    print(f"General error: {e}")
```

## Configuration

```python
client = Adaptensor(
    api_key="your-api-key",
    base_url="https://your-instance.adaptensor.com",  # Custom endpoint
    timeout=600  # Request timeout in seconds
)
```

## Health Check

```python
if client.health():
    print("API is healthy")
else:
    print("API is down")
```

## Usage Statistics

```python
stats = client.stats()
print(f"Documents: {stats['documents']}")
print(f"Chunks: {stats['chunks']}")
print(f"Queries: {stats['queries']}")
```

## Full Example

```python
from adaptensor import Adaptensor

# Initialize
client = Adaptensor()

# Upload a batch of legal documents
docs = client.documents.upload_many([
    "contracts/agreement_2024.pdf",
    "contracts/amendment_1.pdf",
    "contracts/amendment_2.pdf",
])
print(f"Uploaded {len(docs)} documents")

# Index everything
result = client.documents.index()
print(f"Indexed {result.total_chunks} chunks in {result.elapsed_seconds:.1f}s")

# Search for specific clauses
results = client.query("indemnification obligations", top_k=10)

print(f"\nFound {results.count} results in {results.elapsed_ms:.1f}ms:\n")
for i, chunk in enumerate(results, 1):
    print(f"{i}. [{chunk.score:.2f}] {chunk.metadata.get('filename')}")
    print(f"   {chunk.text[:150]}...")
    print()
```

## Requirements

- Python 3.8+
- requests >= 2.25.0

## Links

- **Documentation**: [docs.adaptensor.com](https://docs.adaptensor.com)
- **API Reference**: [docs.adaptensor.com/api](https://docs.adaptensor.com/api)
- **GitHub**: [github.com/adaptensor/adaptensor-python](https://github.com/adaptensor/adaptensor-python)
- **PyPI**: [pypi.org/project/adaptensor](https://pypi.org/project/adaptensor)

## License

MIT License - see [LICENSE](LICENSE) for details.

---

**Adaptensor** — Your Data. Your Infrastructure. Your AI.