Stocklytics AI is a retail operations platform for small and medium stores. It combines inventory management, billing, customer records, alerts, analytics, and a grounded AI assistant in one workspace built for day-to-day store operations.
The project is implemented as a modular monolith backend with a modern Next.js frontend, and it is designed to run well on Google Cloud using Firestore, BigQuery, Cloud Run, and local Gemma open models.
- YouTube: https://youtu.be/e9IBF1SQq4Q?si=OrUKfv7aweuc-g7J
- Main GitHub Repo: https://github.com/ShreyData/Stocklytics-AI
- Cloud Run App: https://stocklytics-frontend-hpcb3ng5ra-el.a.run.app/
- Overview
- Core Features
- Product Modules
- AI Assistant
- Architecture
- Google Cloud and Firebase Usage
- Repository Structure
- Tech Stack
- Local Development
- Environment Configuration
- Testing
- Deployment
- Operational Scripts
- Security Notes
- Roadmap Ideas
Stocklytics AI was originally built for the Solution Challenge by Hack2skill and Google. In its initial version, the platform relied heavily on cloud-based AI, specifically the Gemini API (gemini-2.0-flash and gemini-embedding-001) for both product vectorization and chat generation. This allowed us to build a robust proof-of-concept for intelligent retail operations.
To participate in the Gemma for Good Hackathon, the architecture was entirely re-engineered and optimized for Edge AI. We disconnected all external cloud AI services and pivoted the codebase to run 100% locally using Open Weights.
- Before: Cloud-dependent. Data sent to Google's Gemini API for processing and embedding.
- After: Edge-optimized. The AI Assistant now runs natively on local hardware using
google/gemma-4-4b-it(via PyTorch/Transformers) andsentence-transformers/all-MiniLM-L6-v2for offline embeddings.
We are submitting this project under the Digital Equity & Inclusivity track. Small and medium retail operators (mom-and-pop shops) often lack access to enterprise-grade AI or the technical skills to implement it. By bringing a powerful, intuitive, edge-ready AI directly to their operational dashboard, Stocklytics AI bridges the AI skills gap, democratizing advanced retail analytics without relying on expensive cloud subscriptions.
Stocklytics AI helps a retail operator answer practical questions such as:
- What products are low on stock?
- Which items are expiring soon?
- What sold best today?
- Which customers are buying the most?
- What should I restock next?
- What changed in the business since the last update?
Instead of splitting those jobs across multiple tools, the platform keeps operational data, analytics snapshots, and AI guidance in one system.
At a high level:
frontend/provides the operator-facing web appbackend/provides the API, auth, domain logic, analytics access, alerts, and AI servicesinfra/cloudrun/contains deployment templates for Google Cloud Run and Cloud Buildbackend/scripts/contains seeding, sync, transform, and E2E helper scripts
- Retail dashboard with sales, transactions, alert counts, and stock health
- Inventory management with create, update, stock adjustments, and low-stock workflows
- Billing and transaction creation with idempotency protection
- Customer management with profile creation and purchase history
- Alerts engine for low stock, expiry risk, high demand, and non-selling products
- Analytics views backed by BigQuery mart tables
- Grounded AI assistant that answers using live store context and retrieval-augmented product evidence
- Authenticated multi-user access using Firebase Authentication and backend claim validation
- Cloud-ready deployment model for frontend and backend as separate services
The backend is organized into domain modules, each with its own router, schemas, service, and repository layer where appropriate.
- Product CRUD
- Stock adjustment tracking
- Reorder threshold monitoring
- Expiry metadata and inventory status handling
- Transaction creation
- Stock deduction during billing
- Idempotency handling to prevent duplicate charges
- Integration with downstream analytics and alert workflows
- Customer profile creation and listing
- Purchase history lookup
- Data used by both analytics and AI assistant features
- Low stock alert generation
- Expiry-soon and expired-item monitoring
- Not-selling and high-demand detection
- Acknowledge and resolve workflows
- Dashboard summary
- Sales trends
- Product performance
- Customer insights
- Freshness metadata for downstream consumers
- Chat sessions with persisted message history
- Grounded retrieval from inventory, analytics, alerts, customers, and transactions
- Product embedding sync into BigQuery
- Multi-model routing for fast answers and deeper reasoning
- Incremental sync from Firestore to BigQuery raw tables
- Mart transformations for analytics views
- Failure tracking and repair workflows
- Admin-triggered sync endpoints
The AI assistant is designed for operational retail questions, not open-ended general chat.
Current design goals:
- Answer from store data instead of generic LLM behavior
- Use exact and semantic product retrieval for product-specific questions
- Run 100% locally on edge hardware using the
google/gemma-4-4b-itmodel via PyTorch/Transformers - Return answer provenance such as intent, retrieval confidence, and grounding metadata
- Fall back gracefully when parts of the context are unavailable
Current backend AI flow includes:
- Query intent detection
- Selective context loading
- Hybrid retrieval using Firestore snapshots plus BigQuery vector search
- Evidence-pack prompt construction
- Model routing and answer generation
- Response normalization and persistence
Relevant AI endpoints:
POST /api/v1/ai/chatGET /api/v1/ai/chat/sessions/{chat_session_id}POST /api/v1/ai/embed-sync
The backend follows a modular monolith style. Each domain lives inside backend/app/modules/<domain>/.
Common backend layering pattern:
router.pyFastAPI endpoints and request validationschemas.pyPydantic request/response modelsservice.pyBusiness logic and orchestrationrepository.pyFirestore or BigQuery access
Shared backend infrastructure lives in:
backend/app/common/config, auth, middleware, exceptions, logging, shared response helpersbackend/app/api/platform and administrative endpoints
The frontend is a Next.js App Router application. Pages live under frontend/app/, shared components under frontend/components/, and runtime/service helpers under frontend/lib/.
Typical API request flow:
- Request enters FastAPI app at main.py
- Middleware attaches request metadata and logging context
- Firebase-backed auth validates the bearer token and extracts role/store claims
- Router validates payload and delegates to a domain service
- Service coordinates repositories, rules, downstream reads, and persistence
- Standard response helper injects
request_id
The frontend supports multiple runtime modes via runtime.ts:
firebaseReal Firebase web authenticationbackend_stub_authReal backend with local stub auth when Firebase web config is absentmock_apiFully mocked frontend preview mode
This makes it easier to develop independently across backend, frontend, and cloud environments.
This project is tightly integrated with Google services.
- Firebase Authentication for operator sign-in
- Firebase Admin SDK on backend for token verification
- Custom claims (
role,store_id) used for store-scoped authorization
- Primary operational datastore
- Stores products, customers, transactions, stock adjustments, alerts, metadata, and AI chat sessions
- Supports the real-time store state used by API modules and AI retrieval
- Raw tables for synced operational data
- Mart tables for analytics summaries and reporting views
- Product embedding storage for vector search
- Retrieval source for analytics and AI grounding
- Query embeddings using offline
sentence-transformers/all-MiniLM-L6-v2 - Fast, local chat generation using the native
google/gemma-4-4b-itmodel - Perfect for Edge deployment and 100% compliant with the "Gemma for Good" hackathon
- Used by the AI assistant only after context is assembled from operational data
stocklytics-backendruns the FastAPI APIstocklytics-frontendruns the Next.js standalone app- Separate deployment surface keeps backend and frontend scaling concerns clean
- Builds backend and frontend images
- Injects environment-specific build/runtime configuration during deployment
- Stores backend and frontend container images for Cloud Run deployment
Stocklytics-AI/
├── backend/
│ ├── app/
│ │ ├── api/
│ │ ├── common/
│ │ └── modules/
│ │ ├── ai/
│ │ ├── alerts/
│ │ ├── analytics/
│ │ ├── billing/
│ │ ├── customer/
│ │ ├── data_pipeline/
│ │ └── inventory/
│ ├── scripts/
│ ├── tests/
│ └── requirements.txt
├── frontend/
│ ├── app/
│ ├── components/
│ ├── lib/
│ └── package.json
├── infra/
│ └── cloudrun/
├── docs/
└── README.md
- Next.js 15
- React 19
- TypeScript
- Tailwind CSS
- Lucide icons
- Axios
- Firebase Web SDK
- Vitest for frontend unit tests
- FastAPI
- Pydantic v2
- Firebase Admin SDK
- Google Cloud Firestore client
- Google Cloud BigQuery client
- HTTPX
- Python dotenv
- Pytest and pytest-asyncio
- Python 3.11+ or compatible runtime for the backend toolchain
- Node.js 20+ recommended for the frontend
- A Firebase project and Google Cloud project if you want to run against real services
- Firestore and BigQuery enabled for full-stack integration
cd backend
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
cp .env.example .env
uvicorn app.main:app --reload --port 8000Backend docs and health endpoints:
http://127.0.0.1:8000/docshttp://127.0.0.1:8000/api/v1/healthhttp://127.0.0.1:8000/api/v1/ready
cd frontend
npm install
cp .env.example .env.local
npm run devFrontend dev URL:
http://127.0.0.1:3000
- Use real Firebase web auth by providing Firebase frontend config values
- Use backend stub auth for local backend work when Firebase web config is absent
- Use mock mode for purely frontend exploration
Key backend environment variables are defined in:
Important backend values:
APP_ENVCORS_ALLOW_ORIGINSFIREBASE_PROJECT_IDFIRESTORE_PROJECT_IDBIGQUERY_PROJECT_IDGEMMA_MODEL_IDGEMMA_EMBEDDING_MODEL
Key frontend environment variables are defined in:
Important frontend values:
NEXT_PUBLIC_API_BASE_URLBACKEND_URLNEXT_PUBLIC_FIREBASE_API_KEYNEXT_PUBLIC_FIREBASE_AUTH_DOMAINNEXT_PUBLIC_FIREBASE_PROJECT_IDNEXT_PUBLIC_FIREBASE_STORAGE_BUCKETNEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_IDNEXT_PUBLIC_FIREBASE_APP_IDNEXT_PUBLIC_USE_MOCKSNEXT_PUBLIC_AUTO_LOGIN_DEMO
cd backend
pytestcd frontend
npm testThere is also a backend E2E validation script:
python backend/scripts/run_backend_e2e_check.pyThat script validates:
- platform endpoints
- inventory flows
- customer flows
- billing behavior
- alerts endpoints
- optional analytics and AI checks
Cloud deployment assets live in infra/cloudrun/.
Read the detailed cloud guide here:
Deployment model:
- Backend deployed as a Cloud Run FastAPI service
- Frontend deployed as a Cloud Run Next.js service
- Images built with Cloud Build and stored in Artifact Registry
Production recommendation:
- Prefer Cloud Run service account permissions over injecting raw private keys
- Use Secret Manager for sensitive runtime values where possible
- Grant backend service account Firestore and BigQuery roles explicitly
Useful backend scripts in backend/scripts/:
seed_one_month_data.pySeeds demo-style retail datareset_and_seed_one_month_data.pyClears one store, reseeds one month, rebuilds alerts, analytics, and embeddingsrun_sync_job.pyRuns Firestore to BigQuery syncrun_transform_job.pyBuilds mart tables from raw datarun_embedding_sync.pyRegenerates product embeddingsrun_alerts_sweep.pyRecomputes alerts from operational staterun_repair_job.pyRepairs pipeline failures
- Do not commit service-account JSON files, local auth key notes, or real env files
- Prefer Application Default Credentials on Cloud Run over shipping long-lived private keys
- Rotate any Firebase or Google Cloud credentials immediately if they are ever exposed
- Keep
infra/cloudrun/*.env.yamllocal and out of git - Review
.gitignoreand.gcloudignorebefore deployment so local secrets are excluded but build-critical source files are included
- Stronger admin workflows for store and user provisioning
- Better observability around AI latency, retrieval quality, and model routing
- Richer analytics slices and drill-downs
- Automated CI validation for backend, frontend, and deployment health
- Secret Manager integration for all production-sensitive settings
- YouTube: https://youtu.be/e9IBF1SQq4Q?si=OrUKfv7aweuc-g7J
- Main GitHub Repo: https://github.com/ShreyData/Stocklytics-AI
- Cloud Run App: https://stocklytics-frontend-hpcb3ng5ra-el.a.run.app/