Metadata-Version: 2.4
Name: smart-knowledge
Version: 1.2.1
Summary: Official Python 3.10+ SDK for the Smart Knowledge 5-Brain Autonomous Platform
Author-email: Catalin Batrinu <bcatalin@gmail.com>
License: MIT
Project-URL: Homepage, https://ztrust.eu
Project-URL: Documentation, https://github.com/chdlabs/smart-knowledge
Project-URL: Repository, https://github.com/chdlabs/smart-knowledge
Keywords: smart-knowledge,rag,hybrid-search,knowledge-graph,paoa,autonomous-agent,memgraph,qdrant,llm
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.28.0
Dynamic: license-file
Dynamic: requires-python

# Smart Knowledge Python SDK (`smart-knowledge`)

[![Python Version](https://img.shields.io/badge/python-%3E%3D3.10-blue.svg)](https://www.python.org)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![PyPI](https://img.shields.io/badge/pypi-v1.1.0-blue.svg)](https://pypi.org/project/smart-knowledge/)
[![Typing](https://img.shields.io/badge/typing-PEP%20561-informational.svg)](https://peps.python.org/pep-0561/)

Official **Python 3.10+** client library for the **Smart Knowledge 5-Brain Cognitive Platform**.

Provides direct programmatic access to:
- **`ask()`**: Grounded 5-Brain RAG Question Answering with primary citations.
- **`search()`**: Multi-Modal Hybrid Search across Knowledge Graph, BM25, and semantic vectors.
- **`agentask`**: Autonomous Problem Solver (PAOA) multi-step reasoning missions.
- **`documents`**: Streamlined enterprise document ingestion pipeline with full server-side pagination.

---

## 🚀 Installation

```bash
pip install smart-knowledge
```

> **Requirements:** Python **3.10** or higher.

---

## ⚡ Quickstart

```python
from smart_knowledge import SmartKnowledge

sk = SmartKnowledge(
    api_key="sk_live_...",        # Or export SMART_KNOWLEDGE_API_KEY
    base_url="https://ztrust.eu", # Or 'http://localhost:5000' for local dev
)

# 1. Ask a question with 5-Brain verified grounding
response = sk.ask(
    question="What are the main supplier liability terms under Section 8.2?",
    include_sources=True,
)

print("Answer:", response.answer)
print("Grounding Score:", response.grounding_score)
for citation in response.citations:
    print(f"[{citation.source_name}] {citation.text}")
```

---

## Modules & API Reference

### 1. `client.ask(options)`
Performs verified question answering using the 5-Brain RAG engine (Post-Quantum TLS, SPOC Knowledge Graph, Semantic Vectors, BM25 keyword index, and Exact Fact Ledger).

```python
response = sk.ask(
    question="Summarize our supply chain compliance obligations under the German LkSG.",
    include_sources=True,
)

print("Answer:", response.answer)
print("Grounding Score:", response.grounding_score)
if response.finops:
    print("Total Tokens:", response.finops.total_tokens)
    print("Cost EUR:", response.finops.cost_eur)
```

#### Parameters:
- `question` *(str, required)*: Question to synthesize.
- `include_sources` *(bool, optional, default: True)*: Include primary chunk passages.
- `timeout` *(float, optional)*: Override request timeout in seconds.

---

### 2. `client.search(options)`
Performs raw multi-modal retrieval across all 5 brains with optional automated compound query decomposition.

```python
results = sk.search(
    query="indemnity limits for software licensing agreements",
    decompose=True, # Decomposes complex multi-part queries
    limit=10,
)

print("Graph Facts (Triplets):", len(results.triplets))
for triplet in results.triplets:
    print(f" - ({triplet.subject}) -[{triplet.relation}]-> ({triplet.target})")

print("Vector Passages:", len(results.vector_results))
print("Keyword Matches (BM25):", len(results.bm25_results))
```

---

### 3. `client.agentask` (Autonomous Problem Solver / PAOA)
Dispatches multi-iteration autonomous research missions executing Plan-Act-Observe-Answer (PAOA) loops.

#### Synchronous Auto-Polling Execution:
```python
result = sk.agentask.run(
    task="Audit the 2025 financial report and verify whether EBITDA margin targets were met.",
    max_iterations=5,
    poll_interval_sec=2.0, # Check status every 2 seconds
    timeout_sec=90.0,       # Timeout after 90 seconds
    on_progress=lambda p: print(f"[{p.phase.upper()}] {p.step_name or 'Working...'}")
)

print("Final Synthesized Answer:", result.answer)
print("Iterations count:", result.iterations_count)
print("Observe score:", result.observe_score)
```

#### Asynchronous Webhook-Driven Execution:
```python
# Dispatch mission and return immediately
dispatch_res = sk.agentask.dispatch(
    task="Analyze vendor contract renewals for Q4 and extract price revision clauses.",
    max_iterations=4,
    observe_threshold=85,
    webhook_url="https://api.mycompany.com/v1/webhooks/paoa-callback",
)

print(f"Dispatched mission ID: {dispatch_res.task_id}")

# Query progress on demand
status_res = sk.agentask.get_status(dispatch_res.task_id)
print(f"Status: {status_res.status}")
```

---

### 4. `client.documents` (Document Ingestion & Library)
Uploads enterprise documents (PDF, DOCX, TXT, CSV, etc.) for OCR, chunking, PQC encryption, and SPOC graph triplet extraction.

```python
from pathlib import Path

# 1. Upload from local file path, opened file, or bytes
upload = sk.documents.upload(
    file=Path("./quarterly_report_2026.pdf"),
    extract_spoc=True, # Extract knowledge graph triplets into Memgraph
)
print(f"Uploaded file ID: {upload.file_id}")

# 2. Check live processing status
status = sk.documents.get_status(upload.file_id)
print(f"Ingestion status: {status.status}") # 'queued' | 'processing' | 'completed'

# 3. List uploaded documents with selectable pagination (10, 20, 50 items/page)
res = sk.documents.list(
    page=1,
    limit=20, # User selectable: 10, 20, or 50 items per page
    search="quarterly",
    status="completed",
)

print(f"Page {res.pagination.page} of {res.pagination.total_pages} ({res.pagination.total} total documents)")
for f in res.files:
    print(f" - {f.name} ({f.ingest_status}) | Tokens: {f.tokens_used:,} | Cost: €{f.cost_eur:.4f}")
```

---

## Error Handling

The SDK exposes clean, strongly typed error classes:

```python
from smart_knowledge import SmartKnowledge
from smart_knowledge.errors import (
    AuthenticationError,
    RateLimitError,
    QuotaExceededError,
    ValidationError,
    APIConnectionError,
    NotFoundError,
)

sk = SmartKnowledge(api_key="sk_...")

try:
    answer = sk.ask("Synthesize regulatory filing...")
except AuthenticationError:
    print("API key is invalid or revoked.")
except QuotaExceededError:
    print("Tenant monthly LLM token quota is exhausted.")
except RateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after_sec} seconds.")
except ValidationError as e:
    print(f"Parameter validation error: {e.message}")
except APIConnectionError as e:
    print(f"Network error: {e.message}")
```

---

## License

MIT License. Copyright (c) 2026 Catalin Batrinu / CHD Labs.
