A multi-agent FastAPI service that monitors SKU stock levels, forecasts 30-day seasonal demand, explains the reorder decision in plain language via a local LLM, and drafts supplier purchase orders — automatically.
🔗 Live Demo: stockai-inky.vercel.app | 📚 API Docs: /docs
Small-to-medium retailers lose sales (and cash) two ways: they stock out of fast movers, or they tie up working capital in slow ones. StockAI is a small, readable reference implementation of the pattern real inventory-automation systems use — a pipeline of narrow, single-responsibility agents rather than one large "do everything" service:
graph LR
A[SKUInventoryItem] --> B["MonitorAgent<br/>reorder point + stockout risk"]
B --> C["ForecastAgent<br/>30-day seasonal demand"]
C --> D["InsightAgent<br/>LLM executive summary"]
D --> E["OrderAgent<br/>PO + vendor email draft"]
E --> F[InventoryAutomationPipelineResult]
Each agent is a plain Python class with one method and no hidden state, orchestrated by StockAIEngine.process_sku(). That makes the whole pipeline unit-testable in isolation (see tests/) and easy to read end-to-end in one sitting.
- Four specialized agents, each independently testable:
MonitorAgent— reorder-point math (ROP = daily_run_rate × lead_time + safety_stock) and stockout ETA.ForecastAgent— 30-day seasonal demand projection and recommended reorder quantity.InsightAgent— turns the numbers above into a short, executive-readable narrative. Tries a local, free Ollama LLM first; if Ollama isn't running, falls back instantly to a deterministic rule-based template. No API key, ever — see AI Insight Generation below.OrderAgent— drafts a purchase order and a ready-to-send vendor reorder email.
- Bilingual interactive dashboard — dark glassmorphic UI (English / Arabic RTL) with live scenario presets, so you can see the whole pipeline run against sample SKUs without touching
curl. - Deploys anywhere — same codebase runs under Docker/Uvicorn (
docker-compose.yml) or as a Vercel serverless function (api/index.py); see Deployment. - 11 passing unit/integration tests covering every agent, the orchestration engine, the FastAPI routes, and both the LLM and template code paths of
InsightAgent.
MonitorAgent and ForecastAgent are deterministic math — that's a feature, not a shortcut (reorder-point calculations shouldn't be probabilistic). But a store owner doesn't want raw numbers, they want to know why they should act. InsightAgent closes that gap:
- It builds a compact prompt from the current stock, risk level, stockout ETA, and forecasted demand, and sends it to a local Ollama server (
llama3.2by default) — free, no API key, runs entirely on your machine. - If Ollama isn't installed/running (e.g. on the live demo above, or in CI),
OllamaClient.generate()fails fast (short timeout, caught exception) andInsightAgenttransparently falls back to a deterministic rule-based template built from the same numbers. - Every
ExecutiveInsightresponse reports its ownsourcefield ("ollama:llama3.2"or"template-fallback") so callers — and the dashboard's badge next to the summary — always know which path produced it. Nothing about the API contract changes either way.
# Optional: run a local LLM so InsightAgent uses it instead of the template
ollama pull llama3.2
ollama serveConfiguration lives in .env.example (OLLAMA_BASE_URL, OLLAMA_MODEL, OLLAMA_DISABLED).
# Clone and install
git clone https://github.com/asadullah48/stockai.git
cd stockai
pip install -r requirements.txt
# Run the API + dashboard
uvicorn stockai.server:app --reload --port 8019
# → http://127.0.0.1:8019 (dashboard)
# → http://127.0.0.1:8019/docs (OpenAPI/Swagger)
# Run the test suite
pytest -qOr with Docker:
docker compose up --build
# → http://localhost:8019| Method | Path | Description |
|---|---|---|
| GET | / |
Interactive bilingual dashboard |
| GET | /healthz |
Liveness probe |
| GET | /readyz |
Readiness probe + active agent count |
| GET | /docs |
Auto-generated OpenAPI/Swagger UI |
| POST | /api/v1/inventory/process-sku |
Runs the full Monitor → Forecast → Insight → Order pipeline for one SKU |
Example request/response
curl -X POST https://stockai-inky.vercel.app/api/v1/inventory/process-sku \
-H "Content-Type: application/json" \
-d '{
"sku": "SKU-4412",
"item_name": "ANC Wireless Headphones",
"current_stock": 4,
"safety_stock_threshold": 30,
"daily_run_rate": 6.0,
"unit_cost_usd": 24.50,
"lead_time_days": 7,
"vendor_name": "Apex Precision Components Ltd",
"vendor_email": "[email protected]"
}'Response includes monitoring (risk/ROP), forecast (30-day demand), insight (the executive summary + its source), and purchase_order (draft PO + vendor email) — see the full InventoryAutomationPipelineResult schema in stockai/core/models.py or at /docs.
stockai/
├── agents/ # One class per pipeline stage
│ ├── monitor_agent.py
│ ├── forecast_agent.py
│ ├── insight_agent.py # LLM (Ollama) + deterministic fallback
│ └── order_agent.py
├── core/
│ ├── models.py # Pydantic schemas shared across the pipeline
│ ├── inventory_monitor.py
│ ├── demand_forecaster.py
│ └── llm_client.py # Defensive Ollama HTTP client
├── orchestration/
│ └── stockai_engine.py # Wires the four agents together
├── static/ # Bilingual dashboard (HTML/CSS/JS, no build step)
└── server.py # FastAPI app + routes
api/index.py # Vercel serverless entrypoint (re-exports the FastAPI app)
tests/ # pytest suite, one file per module
The same FastAPI app object is reused across both targets — nothing is duplicated:
- Docker —
Dockerfile+docker-compose.ymlrun it under Uvicorn on port8019, with a containerHEALTHCHECKagainst/healthz. - Vercel —
api/index.pyre-exportsstockai.server:app; Vercel's Python runtime auto-detects the ASGI app and serves it as a serverless function. The live demo runs this way on Vercel's free tier.
Python 3.10+ · FastAPI · Pydantic v2 · Uvicorn · httpx · Ollama (optional, local LLM) · pytest · Docker · Vercel
- Autonomy —
StockAIEngine.process_sku()runs Monitor→Forecast→ Insight→Order end-to-end per SKU with no human step in between; the agents decide the reorder point, the forecast, the narrative, and the draft PO on their own. - Resilience —
InsightAgenttries a local Ollama LLM first and, if it's unavailable, falls back instantly to a deterministic rule-based template — the pipeline degrades gracefully instead of failing when the LLM step is down, and every response reports which path (source) it actually took. - Adaptivity —
MonitorAgent's reorder-point math andForecastAgent's seasonal projection are both parameterized off live stock/demand data per call, so the same four agents adapt their output per-SKU without any retraining or redeploy.
- Fan
StockAIEngineout across a full catalog concurrently (it currently processes one SKU per call) — the four agents are already stateless and independently testable, so this is an orchestration change, not a rewrite. - Swap the direct Ollama HTTP call in
InsightAgentfor an MCP tool call, so the same insight step can plug into a larger multi-agent supply-chain system instead of only this service. - Move from the current Docker/Vercel targets to a Kubernetes deployment with autoscaling per agent stage, once catalog-wide fan-out is in place.
Apache 2.0 — see LICENSE.