Metadata-Version: 2.4
Name: neuromesh-ai
Version: 0.3.0
Summary: Open-source universal recommendation infrastructure for any application
Author-email: Amit Chandra <theamitchandra@gmail.com>
License: MIT License
        
        Copyright (c) 2026 Amit Chandra
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://github.com/TheAmitChandra/NeuroMesh-AI
Project-URL: Repository, https://github.com/TheAmitChandra/NeuroMesh-AI
Project-URL: Issues, https://github.com/TheAmitChandra/NeuroMesh-AI/issues
Keywords: recommendation,machine-learning,ai,nlp,vector-search,fastapi
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
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
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: fastapi>=0.110.0
Requires-Dist: uvicorn[standard]>=0.29.0
Requires-Dist: scikit-learn>=1.4.0
Requires-Dist: pydantic>=2.6.0
Requires-Dist: pydantic-settings>=2.2.0
Requires-Dist: slowapi>=0.1.9
Requires-Dist: numpy>=1.26.0
Provides-Extra: embedding
Requires-Dist: sentence-transformers>=2.7.0; extra == "embedding"
Requires-Dist: torch>=2.2.0; extra == "embedding"
Requires-Dist: faiss-cpu>=1.8.0; extra == "embedding"
Provides-Extra: collaborative
Requires-Dist: implicit>=0.7.2; extra == "collaborative"
Requires-Dist: scipy>=1.12.0; extra == "collaborative"
Provides-Extra: qdrant
Requires-Dist: qdrant-client>=1.8.0; extra == "qdrant"
Provides-Extra: chroma
Requires-Dist: chromadb>=0.4.24; extra == "chroma"
Provides-Extra: db
Requires-Dist: sqlalchemy[asyncio]>=2.0.0; extra == "db"
Requires-Dist: asyncpg>=0.29.0; extra == "db"
Requires-Dist: aiosqlite>=0.20.0; extra == "db"
Requires-Dist: alembic>=1.13.0; extra == "db"
Provides-Extra: cache
Requires-Dist: redis[asyncio]>=5.0.0; extra == "cache"
Provides-Extra: odoo
Provides-Extra: shopify
Requires-Dist: httpx>=0.27.0; extra == "shopify"
Provides-Extra: prometheus
Requires-Dist: prometheus-fastapi-instrumentator>=0.21.0; extra == "prometheus"
Provides-Extra: pgvector
Requires-Dist: pgvector>=0.2.0; extra == "pgvector"
Provides-Extra: all
Requires-Dist: neuromesh-ai[cache,chroma,collaborative,db,embedding,pgvector,prometheus,qdrant,shopify]; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
Requires-Dist: pytest-cov>=5.0.0; extra == "dev"
Requires-Dist: httpx>=0.27.0; extra == "dev"
Requires-Dist: black>=24.0.0; extra == "dev"
Requires-Dist: isort>=5.13.0; extra == "dev"
Requires-Dist: mypy>=1.9.0; extra == "dev"
Requires-Dist: pip-audit>=2.7.0; extra == "dev"
Requires-Dist: build>=1.2.0; extra == "dev"
Requires-Dist: twine>=5.0.0; extra == "dev"
Dynamic: license-file

<div align="center">

<img src="neuromesh-ai.png" alt="NeuroMesh AI Banner" width="100%"/>

# NeuroMesh AI

### AI INFRASTRUCTURE MADE SIMPLE.

**Open-source, schema-agnostic recommendation infrastructure —
TF-IDF · Semantic Embeddings · Collaborative Filtering · Hybrid · Real-time learning.**

```bash
pip install neuromesh-ai
```

[![Python](https://img.shields.io/badge/Python-3.11+-blue.svg)](https://python.org)
[![FastAPI](https://img.shields.io/badge/FastAPI-0.110+-green.svg)](https://fastapi.tiangolo.com)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
[![Version](https://img.shields.io/badge/version-0.3.0-brightgreen.svg)](https://github.com/TheAmitChandra/NeuroMesh-AI/releases/tag/v0.3.0)
[![Coverage](https://img.shields.io/badge/coverage-83%25-brightgreen.svg)](https://github.com/TheAmitChandra/NeuroMesh-AI/actions)
[![Tests](https://img.shields.io/badge/tests-620%20passing-brightgreen.svg)](https://github.com/TheAmitChandra/NeuroMesh-AI/actions)
[![mypy](https://img.shields.io/badge/mypy-strict%20%E2%80%94%200%20errors-blue.svg)](https://mypy.readthedocs.io)
[![PyPI](https://img.shields.io/badge/PyPI-neuromesh--ai-orange.svg)](https://pypi.org/project/neuromesh-ai)
[![Monthly Downloads](https://static.pepy.tech/badge/neuromesh-ai/month)](https://pepy.tech/project/neuromesh-ai)
[![Total Downloads](https://static.pepy.tech/badge/neuromesh-ai)](https://pepy.tech/project/neuromesh-ai)
[![CI](https://github.com/TheAmitChandra/NeuroMesh-AI/actions/workflows/ci.yml/badge.svg)](https://github.com/TheAmitChandra/NeuroMesh-AI/actions)

---

| 🧩 Multi-Engine | 🗄️ Vector Store Support | 🔍 Semantic Search | 👤 Personalization | 🏢 Multi-Tenancy | 📈 Production-Ready |
|:---:|:---:|:---:|:---:|:---:|:---:|
| TF-IDF · Embedding · Collab · Hybrid | FAISS · Qdrant · ChromaDB · pgvector | Meaning-aware retrieval | Collaborative filtering + cold-start | Tenant-isolated engines | Docker · Redis · Postgres · CI/CD |

---

> **Build AI Systems Faster. Focus on Intelligence, Not Infrastructure.**

**Open Source & Community Driven** — Let's build the future of AI together!
[github.com/TheAmitChandra](https://github.com/TheAmitChandra)

</div>

---

## Table of Contents

1. [What is NeuroMesh AI?](#what-is-neuromesh-ai)
2. [What's New in v0.3.0](#whats-new-in-v030)
3. [Architecture](#architecture)
4. [The Five Engines](#the-five-engines)
5. [Installation](#installation)
6. [Quick Start — SDK](#quick-start--sdk)
7. [Engine Examples](#engine-examples)
8. [Session Recommendations](#session-recommendations)
9. [User Personalization & Cold-Start](#user-personalization--cold-start)
10. [Incremental Learning](#incremental-learning)
11. [Explainability](#explainability)
12. [Model Persistence](#model-persistence)
13. [REST API Server](#rest-api-server)
14. [Multi-Tenancy](#multi-tenancy)
15. [Vector Database Support](#vector-database-support)
16. [Environment Variables](#environment-variables)
17. [Docker Compose Quickstart](#docker-compose-quickstart)
18. [Database & Migrations](#database--migrations)
19. [Prometheus Metrics](#prometheus-metrics)
20. [A/B Testing](#ab-testing)
21. [Integrations (Shopify, Odoo)](#integrations-shopify-odoo)
22. [Testing & CI](#testing--ci)
23. [Benchmarks](#benchmarks)
24. [Contributing](#contributing)

---

## What is NeuroMesh AI?

NeuroMesh AI is an open-source, modular, production-ready recommendation infrastructure platform.
It provides intelligent recommendation capabilities to **any application** with minimal integration
effort — whether you're building an ecommerce store, a video platform, a music app, an ERP system,
or a learning platform.

Unlike most recommendation libraries that tie you to a single algorithm and a fixed schema,
NeuroMesh AI is:

- **Schema-agnostic** — only `id` is required on items. Bring your own fields.
- **Engine-agnostic** — swap between TF-IDF, semantic, collaborative, and hybrid with one parameter.
- **Deployment-agnostic** — run as a Python SDK, a standalone FastAPI server, or inside Docker.
- **Backend-agnostic** — FAISS, Qdrant, ChromaDB, or pgvector for vector storage.

---

## What's New in v0.3.0

| Feature | Details |
|---|---|
| **Persistent multi-tenancy** | `POST /v1/tenants` creates tenant-isolated engines. Tenant state survives restarts via PostgreSQL. |
| **`NEUROMESH_ENGINE` env var** | Configure the default engine for auto-created tenants without code changes. |
| **pgvector support** | Set `NEUROMESH_VECTOR_STORE=pgvector` to store vectors inside your existing PostgreSQL cluster. |
| **Alembic migrations** | `alembic upgrade head` sets up items, interactions, recommendation_log, and tenants tables. |
| **Per-tenant rate limiting** | Each tenant gets its own rate-limit bucket, not shared with other tenants. |
| **SHA-256 model integrity** | `save()` writes a `.sha256` sidecar; `load()` verifies the digest to detect tampering. |
| **Dashboard backend** | Live PostgreSQL queries for items, interactions, and recommendation logs. |
| **8 bug fixes + hardening** | All audit findings resolved: 3 correctness bugs, 5 minor issues, opaque error messages, duplicate-code cleanup. |

---

## Architecture

```
                    ┌───────────────────────┐
                    │      Client Apps      │
                    │  Ecommerce / Video /  │
                    │  Music / ERP / POS    │
                    └──────────┬────────────┘
                               │  REST  /  SDK
                               ▼
                ┌────────────────────────────┐
                │       NeuroMesh SDK        │
                │   from neuromesh import   │
                │        Recommender         │
                └──────────┬─────────────────┘
                           │
      ┌─────────────────────┼──────────────────────┐
      ▼                     ▼                      ▼
 ┌──────────────┐  ┌─────────────────┐  ┌──────────────────┐
 │ API Gateway  │  │ Training Engine │  │  Rec Engines     │
 │  (FastAPI)   │  │ Trainer +       │  │  TF-IDF          │
 │  Auth + RL   │  │ FeatureBuilder  │  │  Embedding       │
 │  Multi-Tenant│  │ Preprocessing   │  │  Collaborative   │
 └──────┬───────┘  └────────┬────────┘  │  Trending        │
        │                   │           │  Hybrid          │
        ▼                   ▼           └────────┬─────────┘
 ┌──────────────┐  ┌─────────────────┐           │
 │  Redis Cache │  │  Incremental    │           ▼
 │  (optional)  │  │  Learner        │  ┌──────────────────┐
 └──────────────┘  └─────────────────┘  │  Post-Engine     │
                                        │  Ranker          │
 ┌──────────────┐  ┌─────────────────┐  │  popularity ×    │
 │  PostgreSQL  │  │  Vector Store   │  │  freshness ×     │
 │  + pgvector  │  │  FAISS / Qdrant │  │  diversity       │
 │  ORM + Migr. │  │  ChromaDB       │  └──────────────────┘
 └──────────────┘  └─────────────────┘
```

---

## The Five Engines

| Engine | Key | Extra | Best For |
|---|---|---|---|
| **TFIDFEngine** | `"tfidf"` | _(core, always installed)_ | Default; fast content-based similarity on any text fields |
| **EmbeddingEngine** | `"embedding"` | `[embedding]` | Semantic meaning — "gaming laptop" matches "high-performance portable PC" |
| **CollaborativeEngine** | `"collaborative"` | `[collaborative]` | User personalization based on shared interaction patterns |
| **TrendingEngine** | `"trending"` | _(core)_ | Popularity × freshness blend for discovery feeds |
| **HybridEngine** | `"hybrid"` | all extras | Multi-signal blend of the above four |

---

## Installation

### Core (TF-IDF + Trending + FastAPI)

```bash
pip install neuromesh-ai
```

### With specific extras

```bash
pip install neuromesh-ai[embedding]       # + SentenceTransformers + FAISS
pip install neuromesh-ai[collaborative]   # + implicit (ALS matrix factorization)
pip install neuromesh-ai[qdrant]          # + Qdrant vector database client
pip install neuromesh-ai[chroma]          # + ChromaDB
pip install neuromesh-ai[pgvector]        # + pgvector (PostgreSQL vectors)
pip install neuromesh-ai[db]              # + SQLAlchemy 2.x async + asyncpg + Alembic
pip install neuromesh-ai[cache]           # + redis[asyncio]
pip install neuromesh-ai[prometheus]      # + prometheus-fastapi-instrumentator
pip install neuromesh-ai[all]             # All of the above (full stack)
```

### Development install

```bash
git clone https://github.com/TheAmitChandra/NeuroMesh-AI.git
cd NeuroMesh-AI
python -m venv .venv
.venv\Scripts\activate      # Windows
# source .venv/bin/activate  # macOS/Linux
pip install -e ".[dev]"
```

---

## Quick Start — SDK

```python
from neuromesh import Recommender

# Any schema — only "id" is required
items = [
    {"id": "1", "title": "Gaming Laptop", "description": "RTX 4080, 32GB RAM", "category": "electronics"},
    {"id": "2", "title": "Gaming Mouse",   "description": "High DPI wireless mouse",  "category": "electronics"},
    {"id": "3", "title": "Mechanical Keyboard", "description": "RGB mechanical gaming keyboard", "category": "electronics"},
    {"id": "4", "title": "Python Cookbook", "description": "Advanced Python programming", "category": "books"},
    {"id": "5", "title": "JavaScript Guide", "description": "Modern JS for developers",  "category": "books"},
]

# Train
rec = Recommender(engine="tfidf")
rec.train(items)

# Item-based recommendations
results = rec.recommend("1", top_k=3)
for r in results:
    print(f"  [{r.rank}] {r.item_id}  score={r.score:.3f}")

# Find similar items
similar = rec.similar("1", top_k=2)

# Trending items
trending = rec.trending(top_k=5)
```

### Launch as REST API

```python
rec.serve(host="0.0.0.0", port=8000)
# → Swagger UI at http://localhost:8000/docs
```

---

## Engine Examples

### TF-IDF (default — no extra install)

```python
rec = Recommender(engine="tfidf")
rec.train(items)
results = rec.recommend("item_1", top_k=5)
```

### Semantic Embeddings

```bash
pip install neuromesh-ai[embedding]
```

```python
rec = Recommender(engine="embedding")
rec.train(items)

# Finds items that *mean* the same thing, not just keyword-match
results = rec.recommend("item_1", top_k=5)
```

Configure the SentenceTransformers model via env var:

```env
NEUROMESH_EMBEDDING_MODEL=all-MiniLM-L6-v2   # default
# NEUROMESH_EMBEDDING_MODEL=all-mpnet-base-v2  # higher quality, slower
```

### Collaborative Filtering (ALS)

```bash
pip install neuromesh-ai[collaborative]
```

```python
interactions = [
    {"user_id": "alice", "item_id": "1", "weight": 1.0},
    {"user_id": "alice", "item_id": "2", "weight": 0.5},
    {"user_id": "bob",   "item_id": "1", "weight": 1.0},
    {"user_id": "bob",   "item_id": "3", "weight": 0.8},
]

rec = Recommender(engine="collaborative")
rec.train(items, interactions=interactions)

# Personalised — users who liked "1" also liked "3"
user_recs = rec.recommend_for_user("alice", top_k=5)
```

### Hybrid Engine (best quality)

```bash
pip install neuromesh-ai[all]
```

```python
rec = Recommender(engine="hybrid")
rec.train(items, interactions=interactions)

# Blends content + semantic + collaborative + trending signals
results = rec.recommend("1", top_k=5)
```

### Trending

```python
rec = Recommender(engine="tfidf")
rec.train(items)

# Optional: filter by category
trending_electronics = rec.trending(top_k=10, category="electronics")
```

---

## Session Recommendations

Session recommendations blend candidates from multiple seed items using a recency-weighted
decay (most-recent item = weight 1.0, each prior item × 0.8).

```python
# User browsed: laptop → keyboard → mouse (most recent last)
session_items = ["laptop_001", "keyboard_007", "mouse_042"]
results = rec.recommend_session(session_items, top_k=5)
```

Via the REST API:

```bash
curl -X POST http://localhost:8000/v1/recommend/session \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your-key" \
  -d '{"session_item_ids": ["laptop_001", "keyboard_007", "mouse_042"], "top_k": 5}'
```

---

## User Personalization & Cold-Start

```python
# Warm user — has interaction history
results = rec.recommend_for_user("alice", top_k=5)

# Cold-start user — falls back to trending automatically
# (via the API; or handle manually in SDK)
try:
    results = rec.recommend_for_user("new_user_999", top_k=5)
except UserNotFoundError:
    results = rec.trending(top_k=5)
```

The REST API handles cold-start automatically:

```bash
curl -X POST http://localhost:8000/v1/recommend/user \
  -H "X-API-Key: your-key" \
  -d '{"user_id": "new_user_999", "top_k": 5}'
# → Returns trending items for unknown users, no 404
```

---

## Incremental Learning

Add items and interactions to a running engine without full retraining.

```python
# Incremental item addition (EmbeddingEngine only supports true fast-path;
# TF-IDF / Collaborative require a full retrain to incorporate new items)
rec.add_item({"id": "new_product", "title": "New Arrival", "category": "electronics"})

# Record interactions in real time
rec.add_interaction("user_123", "new_product", weight=1.0)
```

> **Note:** For TF-IDF and Collaborative engines, `add_item()` buffers items but they are
> not searchable until you call `rec.train(items)` again. Only `EmbeddingEngine` supports
> true incremental item indexing without a full retrain.

Via the REST API:

```bash
# Add item
curl -X POST http://localhost:8000/v1/add-item \
  -H "X-API-Key: your-key" \
  -d '{"item": {"id": "prod_999", "title": "New Gadget"}, "text": "wireless bluetooth speaker"}'

# Record interaction
curl -X POST http://localhost:8000/v1/add-interaction \
  -H "X-API-Key: your-key" \
  -d '{"user_id": "user_123", "item_id": "prod_999", "score": 1.0, "event_type": "purchase"}'
```

---

## Explainability

```python
explanation = rec.explain("item_1", top_k=3)
print(explanation.explanation_text)
# → "Items recommended because they share keywords: gaming, electronics, laptop"

for r in explanation.results:
    print(f"  {r.item_id}: {r.score:.3f} — {r.explanation}")
```

Via the REST API:

```bash
curl -X POST http://localhost:8000/v1/recommend/explain \
  -H "X-API-Key: your-key" \
  -d '{"item_id": "item_1", "top_k": 3}'
```

---

## Model Persistence

Save and load trained models to survive server restarts.

```python
# Save — writes model.joblib + model.joblib.sha256 (integrity sidecar)
rec.save("models/my_model.joblib")

# Load — verifies SHA-256 digest automatically; raises ValueError if tampered
rec = Recommender.load("models/my_model.joblib")
```

> **Security note:** Model files use Python pickle (via joblib). Never load model files from
> untrusted sources. The `.sha256` sidecar is written alongside each saved model and
> verified on load to detect file tampering or corruption.

Configure auto-save via env var — the model is saved automatically after every `/train` call:

```env
NEUROMESH_MODEL_PATH=/var/neuromesh/model.joblib
```

Via the REST API:

```bash
# Trigger a manual save
curl -X POST http://localhost:8000/v1/model/save \
  -H "X-API-Key: your-key"
```

---

## REST API Server

### All Endpoints

| Method | Path | Auth | Rate Limit | Description |
|---|---|---|---|---|
| GET | `/v1/health` | No | — | Health check, engine + DB status |
| POST | `/v1/train` | Yes | 10/min | Train engine on items + interactions |
| POST | `/v1/recommend` | Yes | 60/min | Item-based recommendations |
| POST | `/v1/recommend/user` | Yes | 60/min | User-personalized (cold-start → trending) |
| POST | `/v1/recommend/session` | Yes | 60/min | Recency-weighted multi-item session |
| POST | `/v1/recommend/trending` | Yes | 60/min | Trending items, optional category filter |
| POST | `/v1/recommend/explain` | Yes | 30/min | Recommendations with human-readable explanations |
| POST | `/v1/similar` | Yes | 60/min | Items similar to a seed item |
| POST | `/v1/add-item` | Yes | 120/min | Incremental item addition |
| POST | `/v1/add-interaction` | Yes | 300/min | Record user-item interaction |
| POST | `/v1/feedback` | Yes | 300/min | Record recommendation feedback |
| POST | `/v1/model/save` | Yes | 5/min | Persist model to `NEUROMESH_MODEL_PATH` |
| GET | `/v1/metrics/quality` | No | 30/min | Rolling quality metrics (requires DB) |
| GET | `/v1/tenants` | Yes | 30/min | List registered tenants |
| POST | `/v1/tenants` | Yes | 20/min | Create / activate a tenant |
| DELETE | `/v1/tenants/{id}` | Yes | 10/min | Deactivate tenant (default protected) |
| GET/POST | `/v1/ab` | Yes | — | A/B variant configuration |
| POST | `/v1/webhooks` | Yes | — | Webhook event subscription |
| GET | `/metrics` | — | — | Prometheus metrics |

### Authentication

Pass the API key in the `X-API-Key` header. Leave `NEUROMESH_API_KEY` empty to disable auth
(development mode).

```bash
curl -X POST http://localhost:8000/v1/recommend \
  -H "Content-Type: application/json" \
  -H "X-API-Key: my-secret-key" \
  -d '{"item_id": "product_123", "top_k": 5}'
```

### Response format

```json
{
  "results": [
    {"rank": 1, "item_id": "product_456", "score": 0.921},
    {"rank": 2, "item_id": "product_789", "score": 0.874}
  ],
  "engine": "tfidf",
  "tenant_id": "default"
}
```

---

## Multi-Tenancy

Each tenant gets its own in-memory `Recommender` instance with isolated training data,
model state, and rate-limit bucket. Tenant state is persisted to PostgreSQL and restored
on server restart.

### Create a tenant

```bash
curl -X POST http://localhost:8000/v1/tenants \
  -H "X-API-Key: your-key" \
  -d '{"tenant_id": "shop_A"}'
```

### Use a tenant

```bash
# All requests with X-Tenant-ID use that tenant's engine
curl -X POST http://localhost:8000/v1/train \
  -H "X-API-Key: your-key" \
  -H "X-Tenant-ID: shop_A" \
  -d '{"items": [...]}'

curl -X POST http://localhost:8000/v1/recommend \
  -H "X-API-Key: your-key" \
  -H "X-Tenant-ID: shop_A" \
  -d '{"item_id": "product_1", "top_k": 5}'
```

### Configure the default engine per-tenant

```env
# All auto-created tenants get this engine instead of tfidf
NEUROMESH_ENGINE=hybrid
```

### List tenants

```bash
curl http://localhost:8000/v1/tenants \
  -H "X-API-Key: your-key"
```

> **Multi-worker note:** Tenant state is per-process. With `gunicorn -w 4`, each worker has
> its own model. Use sticky sessions (`--bind` with `gevent` or nginx `ip_hash`) or configure
> `NEUROMESH_MODEL_PATH` to a shared volume for consistent results across workers.

---

## Vector Database Support

Configure via environment variable:

```env
NEUROMESH_VECTOR_STORE=faiss      # default — in-memory, no extra service needed
# NEUROMESH_VECTOR_STORE=qdrant   # requires Qdrant server
# NEUROMESH_VECTOR_STORE=chroma   # requires ChromaDB
# NEUROMESH_VECTOR_STORE=pgvector # uses your PostgreSQL cluster
```

| Backend | Mode | Install | Best For |
|---|---|---|---|
| **FAISS** | In-memory | _(included with `[embedding]`)_ | Local dev, single-node production |
| **Qdrant** | Client-server | `pip install neuromesh-ai[qdrant]` | Scalable, horizontally shardable |
| **ChromaDB** | Embedded or HTTP | `pip install neuromesh-ai[chroma]` | Developer-friendly, easy local setup |
| **pgvector** | PostgreSQL extension | `pip install neuromesh-ai[pgvector]` | Already-running Postgres clusters |

### pgvector setup

```env
NEUROMESH_VECTOR_STORE=pgvector
NEUROMESH_DATABASE_URL=postgresql+asyncpg://user:pass@localhost:5432/neuromesh
```

```sql
-- In your PostgreSQL database:
CREATE EXTENSION IF NOT EXISTS vector;
```

---

## Environment Variables

All variables are prefixed `NEUROMESH_`. Create a `.env` file (see `.env.example`).

| Variable | Default | Description |
|---|---|---|
| `NEUROMESH_ENV` | `development` | `production` enforces CORS and enables JSON logs |
| `NEUROMESH_LOG_LEVEL` | `INFO` | `DEBUG` / `INFO` / `WARNING` / `ERROR` |
| `NEUROMESH_HOST` | `0.0.0.0` | FastAPI bind host |
| `NEUROMESH_PORT` | `8000` | FastAPI bind port |
| `NEUROMESH_API_KEY` | `""` | X-API-Key secret; empty disables auth |
| `NEUROMESH_CORS_ORIGINS` | `http://localhost:3000,...` | Required in production (non-empty) |
| `NEUROMESH_ENGINE` | `tfidf` | Default engine for auto-created tenants |
| `NEUROMESH_DATABASE_URL` | `""` | `postgresql+asyncpg://...` |
| `NEUROMESH_REDIS_URL` | `redis://localhost:6379/0` | Redis connection URL |
| `NEUROMESH_VECTOR_STORE` | `faiss` | `faiss` / `qdrant` / `chroma` / `pgvector` |
| `NEUROMESH_EMBEDDING_MODEL` | `all-MiniLM-L6-v2` | Any SentenceTransformers model name |
| `NEUROMESH_RATE_LIMIT_PER_MINUTE` | `60` | Per-IP + per-Tenant request cap |
| `NEUROMESH_MAX_TENANTS` | `100` | Hard cap on simultaneous in-memory tenants |
| `NEUROMESH_MODEL_PATH` | `""` | Auto-load/save path for the joblib model file |

---

## Docker Compose Quickstart

```yaml
# docker-compose.yml
version: "3.9"
services:
  neuromesh:
    image: ghcr.io/theamitchandra/neuromesh-ai:0.3.0
    ports:
      - "8000:8000"
    environment:
      NEUROMESH_ENV: production
      NEUROMESH_API_KEY: change-me
      NEUROMESH_ENGINE: tfidf
      NEUROMESH_REDIS_URL: redis://redis:6379/0
      NEUROMESH_DATABASE_URL: postgresql+asyncpg://postgres:postgres@db:5432/neuromesh
      NEUROMESH_MODEL_PATH: /var/neuromesh/model.joblib
      NEUROMESH_CORS_ORIGINS: https://your-frontend.com
    volumes:
      - neuromesh_models:/var/neuromesh
    depends_on:
      - redis
      - db

  redis:
    image: redis:7-alpine

  db:
    image: pgvector/pgvector:pg16
    environment:
      POSTGRES_DB: neuromesh
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  neuromesh_models:
  pgdata:
```

```bash
docker compose up -d

# Run migrations
docker compose exec neuromesh python scripts/setup_db.py

# Train via API
curl -X POST http://localhost:8000/v1/train \
  -H "X-API-Key: change-me" \
  -d '{"items": [{"id":"1","title":"Example Product"}]}'
```

---

## Database & Migrations

NeuroMesh AI uses SQLAlchemy 2.x async ORM with Alembic for schema management.

```bash
pip install neuromesh-ai[db]

# Run all migrations (creates items, interactions, recommendation_log, tenants tables)
NEUROMESH_DATABASE_URL=postgresql+asyncpg://... python scripts/setup_db.py

# Or use Alembic directly
alembic upgrade head

# Check migration status
alembic current
```

### ORM Models

| Table | Purpose |
|---|---|
| `items` | Catalog items with metadata |
| `interactions` | User-item events (views, clicks, purchases) |
| `recommendation_logs` | Every recommendation served (for quality metrics) |
| `tenants` | Registered tenants, restored on startup |

---

## Prometheus Metrics

```bash
pip install neuromesh-ai[prometheus]
```

Metrics are available at `GET /metrics` when the `prometheus-fastapi-instrumentator` package
is installed. Standard FastAPI HTTP metrics are exported plus a `neuromesh_recommendations_total`
counter keyed by `engine` and `tenant_id`.

```env
# Prometheus scrape config
- job_name: neuromesh
  static_configs:
    - targets: ['localhost:8000']
  metrics_path: /metrics
```

---

## A/B Testing

Configure recommendation variants and route traffic between engine configurations.

```bash
# Configure an A/B experiment
curl -X POST http://localhost:8000/v1/ab \
  -H "X-API-Key: your-key" \
  -d '{
    "experiment_id": "engine-comparison",
    "variants": [
      {"name": "control", "engine": "tfidf",  "weight": 0.5},
      {"name": "treatment", "engine": "hybrid", "weight": 0.5}
    ]
  }'

# Get current A/B config
curl http://localhost:8000/v1/ab -H "X-API-Key: your-key"
```

Pass `"variant"` in session recommendation requests to tie results to a specific variant:

```bash
curl -X POST http://localhost:8000/v1/recommend/session \
  -H "X-API-Key: your-key" \
  -d '{"session_item_ids": ["item_1", "item_2"], "top_k": 5, "variant": "treatment"}'
```

---

## Integrations (Shopify, Odoo)

### Shopify

```python
from neuromesh.integrations.shopify import ShopifyConnector

connector = ShopifyConnector(
    shop_url="https://your-store.myshopify.com",
    access_token="shpat_xxxx",
)
items = connector.fetch_products()

rec = Recommender(engine="hybrid")
rec.train(items)
```

### Odoo ERP

```python
from neuromesh.integrations.odoo import OdooConnector

connector = OdooConnector(
    url="https://your-odoo.com",
    db="your_db",
    username="admin",
    api_key="your_odoo_api_key",
)
items = connector.fetch_products()
interactions = connector.fetch_orders()

rec = Recommender(engine="collaborative")
rec.train(items, interactions=interactions)
```

---

## Testing & CI

```bash
# Run all unit tests (no Docker needed)
pytest tests/unit/

# Run with coverage report
pytest --cov=neuromesh --cov-report=html

# Integration tests (requires Docker: postgres:16 + pgvector)
pytest tests/integration/

# Type check
mypy neuromesh/ --strict

# Lint
black --check neuromesh/ tests/
isort --check neuromesh/ tests/

# Security audit
pip-audit
```

**v0.3.0 quality snapshot:** 620 unit tests · 83% coverage · `mypy --strict` (0 errors) · 6-job CI

### CI Pipeline (6 jobs)

| Job | What it checks |
|---|---|
| **lint** | `black` formatting + `isort` import order |
| **typecheck** | `mypy --strict neuromesh/` — must be 0 errors |
| **security** | `pip-audit` — no unacknowledged CVEs |
| **unit** | All 620 unit tests |
| **integration** | pgvector tests inside a `pgvector/postgres:16` Docker service |
| **docs** | MkDocs build |

---

## Benchmarks

CPU-only benchmarks (Python 3.11, `top_k=10`). Full results: [`benchmarks/results/`](benchmarks/results/).

### Fit Time

| Catalogue | TF-IDF | Embedding | Hybrid |
|---|---|---|---|
| 100 items | 8.67 ms | 23.4 ms | 37.5 ms |
| 1,000 items | 79.3 ms | 84.6 ms | 119 ms |
| 10,000 items | 665 ms | 1,101 ms | 1,582 ms |

### Recommend Latency

| Catalogue | TF-IDF | Embedding | Hybrid |
|---|---|---|---|
| 100 items | 1.02 ms / 983 rps | 8.10 ms / 123 rps | 10.2 ms / 98 rps |
| 1,000 items | 1.50 ms / 667 rps | 0.49 ms / 2,049 rps | 3.23 ms / 310 rps |
| 10,000 items | 13.1 ms / 76 rps | 0.42 ms / 2,409 rps | 17.9 ms / 56 rps |

> Embedding switches to HNSW ANN at 1,000 items — hence the latency drop at scale.

---

## Tech Stack

| Layer | Technology |
|---|---|
| Language | Python 3.11+ |
| API Framework | FastAPI + Uvicorn |
| ML — Content | scikit-learn (TF-IDF) |
| ML — Semantic | sentence-transformers |
| ML — Collaborative | implicit (ALS) |
| Vector DB | FAISS / Qdrant / ChromaDB / pgvector |
| Cache | Redis (asyncio) |
| Database | PostgreSQL + pgvector |
| ORM | SQLAlchemy 2.x (async) + asyncpg |
| Migrations | Alembic |
| Validation | Pydantic v2 |
| Auth | API Key (X-API-Key header) |
| Rate Limiting | slowapi (per-IP + per-Tenant) |
| Metrics | prometheus-fastapi-instrumentator |
| Frontend | React 18 + Vite + Tailwind |
| Testing | pytest + pytest-asyncio |
| Typing | mypy --strict |

---

## Contributing

Contributions are welcome. Before submitting a PR:

```bash
# All tests must pass
pytest --cov=neuromesh --cov-fail-under=75

# Formatting
black --line-length 100 .
isort .

# Strict type checking (0 errors required)
mypy --strict neuromesh/

# Security
pip-audit
```

See [CONTRIBUTING.md](CONTRIBUTING.md) for detailed guidelines.

---

## License

MIT License — see [LICENSE](LICENSE) for details.

---

## Author

Built by [Amit Chandra](https://github.com/TheAmitChandra)

---

<div align="center">

**NeuroMesh AI v0.3.0 — Production-grade recommendation infrastructure for the modern web.**

[Documentation](https://theamitchandra.github.io/NeuroMesh-AI) · [Issues](https://github.com/TheAmitChandra/NeuroMesh-AI/issues) · [Discussions](https://github.com/TheAmitChandra/NeuroMesh-AI/discussions) · [Changelog](CHANGELOG.md)

*620 tests · 83% coverage · mypy strict · 6-job CI · Docker-ready*

</div>
