API Documentation

How to Enqueue a Job

Fluxrails uses an asynchronous job queue to process AI-powered requests in the background. When you submit a job, it’s stored in DB, enqueued for execution, and you immediately receive a job ID. Your client can then poll or query the status and result at your convenience.

1. Submit Your Job

Send a POST /enqueue request with:

curl -X POST https://api.fluxrails.app/enqueue \
  -H "Content-Type: application/json" \
  -H "X-API-ID: <your_api_id>" \
  -H "X-API-SECRET: <your_api_secret>" \
  -d '{
    "api_route": "/predict/churn",
    "payload": {
      "customerId": 12345,
      "features": { "age": 30, "tenure": 12 }
    },
    "callback_url": "https://yourapp.com/webhook"
  }'

A successful call returns 202 Accepted and a response body containing your _id (the job ID).

2. Workflow Behind the Scenes
  1. Persist: Job document is inserted into jobs (MongoDB).
  2. Enqueue: Celery sends a task to tasks.execute_job with your job ID :contentReference[oaicite:2]{index=2}.
  3. Execute: Worker fetches the job, calls your AI core server, and updates the document’s status and result.
  4. Billing: Each request & response is recorded in billing for metering and audit.
  5. Callback (optional): If you provided a callback_url, we POST the completed job payload back to you.

After enqueueing, you can check progress via:

Route Description Business Usage Actions
/api/anomaly_accounts • Unsupervised anomaly detection for account-level profiles: flags the top-weird accounts based on IsolationForest, LOF, or Auto-Encoder bake-off. • `contamination` sets the expected anomaly rate and decision threshold. • Returns per-account `anomaly_score` (higher ⇒ more anomalous) and boolean `fraud_flag`. • Provides batch KPIs: `detected_pct` and optional `auc` on labeled subset. • Delivers a human-readable `interpretation` summarizing model, threshold, and flag rate. • Stream your account-behavior metrics into this route for real-time risk triage. • Sort `details` by `anomaly_score` to prioritize suspicious accounts for your trust & safety team. • Monitor `detected_pct` drift to tune `contamination` or feature set. • Feed confirmed labels back on the next call—model selection becomes data-driven and AUC improves. • Automate review workflows or step-up authentication for high-score accounts. View
/api/anomaly_graph • Flags the top-N most connected “hub” nodes in any undirected interaction graph. • Computes each node’s weighted degree (sum of edge weights) and marks the top `contamination` fraction. • Returns per-node `anomaly_score` and boolean `flag`. • Provides a human summary of how many nodes crossed the threshold. • Submit device↔account, IP↔email, wallet↔merchant edge lists to catch mule-account rings or botnet controllers. • Sort `details` by `anomaly_score` to investigate the most over-connected nodes first. • Adjust `contamination` for stricter (e.g. 0.02) or broader (e.g. 0.20) review scopes. • Enrich edge weights with transaction counts or data volumes for finer-grained detection. • Combine with `/api/anomaly_accounts` to blend graph-based signals with profile anomalies. View
/api/anomaly_transactions • Unsupervised anomaly scoring for transactions: flags the top-weird rows based on IsolationForest, LOF, or Auto-Encoder bake-off. • `contamination` sets the expected anomaly rate (decision threshold). • Returns per-transaction `anomaly_score` (higher = more anomalous) and boolean `fraud_flag`. • Provides batch KPIs: `detected_pct` and optional `auc` on labeled subset. • Delivers a one-line `interpretation` summarizing model choice, threshold, and flag rate. • Stream real-time transaction feeds into this route for instant fraud triage. • Sort `details` by `anomaly_score` to prioritize high-risk reviews. • Monitor `detected_pct` drift to adjust `contamination` or feature set. • Feed back confirmed labels to improve model selection (higher AUC). • Integrate high-score flags into your risk engine for blocking or step-up authentication. View
/api/channel_attribution • Computes causal or pseudo-causal incremental lift (ATE) per marketing channel. • Distinguishes true drivers from last-click bias by controlling for confounders. • Falls back to elastic-net logistic regression if doubleml isn’t installed. • Allocate budget to channels with positive lift (“↗ strong driver”). • Identify under-performers (“↘ drag on conversions”) for creative or strategy tweaks. • Track AUC to ensure model robustness and guard-rail against under-sampling (< min_events). • Integrate into your weekly marketing performance dashboard for data-driven re-budgeting. View
/api/churn_label Generate a binary churn label per customer snapshot using: - **ecommerce**: 90 days since last purchase - **saas**: subscription_cancelled = true - **prepaid**: zero balance & no top-up in cycle • Build true/false datasets for `/api/churn_risk` • Automate “new churn” KPI tracking • Trigger retention campaigns exactly on churn event View
/api/churn_risk Predict churn risk by benchmarking logistic regression, random forest, XGBoost and CatBoost; return per-customer churn probabilities, chosen model, driver insights and recommended retention actions. - High risk (≥0.60): offer discounts, priority support, concierge call - Medium risk (0.25–0.59): send usage tips, light promotions - Low risk (<0.25): maintain standard nurturing - Feed results into CRM/CS for automated retention journeys and track save-rate KPIs in BI dashboards. View
/api/credit_risk_explain • Generates a local explainability report for one applicant. • Uses your supplied training_sample to fit a local surrogate (LIME) or Tree‐SHAP explainer. • Returns the PD, per‐feature contributions, and a human‐readable interpretation. 1. Slice ~50 historical labeled applicants from your last /credit_risk_score batch. 2. POST the applicant plus the slice to /credit_risk_explain. 3. Receive probability, explanation (feature impacts), and interpretation string. 4. Surface these details to credit officers or regulators for decision justification. View
/api/credit_risk_score • Rapidly prototype a Probability‐of‐Default model without MLOps. • Accepts mixed labeled/unlabeled JSON; auto‐encodes, trains bake-off (LogReg, RF, XGB, CatBoost), selects by AUC. • Outputs AUC, champion model, per‐applicant PDs with SHAP explanations, and a human summary. 1. POST historical applicants with labels → training + scoring + SHAP. 2. Store best_model for audit. 3. For daily scoring, resend same schema without labels. 4. Embed PDs into risk/pricing systems; archive SHAP outputs for compliance. 5. Monitor AUC drift; retrain when below threshold. View
/api/cross_sell_matrix Return a conditional-probability matrix confidence(i→j)=#orders_with_both(i,j)/#orders_with(i) at item or category level, global or per customer. • PDP “Frequently Bought Together” → +8–18% attach rate • Dynamic checkout bundles → +5–12% AOV • Assortment & planogram design → higher shelf penetration • Category-to-category email flows → +10–25% CTR View
/api/customer_clv_features Extracts BG/NBD + Gamma-Gamma inputs per customer: frequency (repeat orders), recency (days between first & last), T (age in days), and average monetary_value. Optionally flags churned and assigns a clv_potential_tier (High/Medium/Low). • Pipe directly into /api/customer_clv_forecast for 6/12/36-month CLV predictions. • Optimize CAC bids by targeting High-tier look-alikes and throttling Low-tier. • Combine monetary_value with RFM tiers for “High-Margin Champions.” • Feed recency/frequency into churn models or CRM workflows. View
/api/customer_clv_forecast Derives CLV features (frequency, recency, T, monetary) Splits data time-aware, trains BG/NBD+Gamma-Gamma vs. Gradient Boosted Regression Selects lowest out-of-sample MAE as best_algorithm Forecasts dollar-value CLV (and optional txn count or avg margin) over the horizon Honors churn_date by zeroing post-churn revenue High CLV: premium concierge, extended credit (▶ +15 % retention) Medium CLV: cross-sell bundles, subscription upsells (▶ +7 % margin) Low CLV: automated win-back, feedback surveys, reduce CAC bids (▶ −12 % wasted spend) View
/api/customer_features Rolls up each customer’s transactions (and optional loyalty_score) into six KPIs—total spend, visit count, avg ticket, distinct products, loyalty score, and days since last purchase—ready for ML or BI. • Rapid segmentation via /purchasing_segmentation • CLV or churn models (/customer_clv_forecast, /churn_risk) • Personalized campaigns (e.g. recency_days ≤ 7 ⇒ “Welcome back”) • Loyalty tier upgrades (score > 0.8 + diversity ≥ 10) View
/api/customer_loyalty Computes a weighted, min–max–scaled loyalty index per customer and assigns tier labels (Platinum, Gold, Silver, Bronze, At-Risk) based on default thresholds. • Drive CRM tiers and dynamic campaigns by loyalty_score • Prioritize perks for top decile (score ≥ top_decile_threshold) • Trigger win-back flows for At-Risk segment • Monitor cohort health via summary.mean_score on dashboards View
/api/customer_rfm Computes Recency (days since last order), Frequency (order count), Monetary (spend) per customer; bins each metric into 1…bins (recency inverted), concatenates into an RFM class (e.g. “335”), sums to rfm_total and maps to tiers (Champion, Loyal, Potential, Promising, At-Risk). Returns thresholds for reproducibility. • Identify Champions for VIP perks and early-access offers • Trigger win-back campaigns for At-Risk segment • Feed RFM scores into CRM or personalization engines • Monitor cohort health by shifts in rfm_tier proportions View
/api/customer_segmentation View
/api/dynamic_pricing_recommend - **best_price**: Optimal price to publish. - **outcomes**: Forecast units, revenue & profit per candidate price. - **model_info**: Selected model, MAPE, #history rows. - **interpretation**: One-line rationale. Automate daily or flash-sale calls using recent sales data, push `best_price` to your platform, and monitor week-over-week margin improvements. View
/api/forecast_cost Forecast daily total cost (COGS, OPEX, or any cost series) out to a multi-month horizon. The endpoint auto-benchmarks ARIMA, ETS, Prophet, TBATS, tree-based ML, and aggregation defaults, selects the lowest-error model, and returns month-level calendar and business-day forecasts with diagnostics. • Cash-flow Planning & Treasury: Model daily burn-rate vs. budget for funding and hedging. • Finance Model Validation: Automate model selection to ensure trust in forecasts. • GL Accruals & Staffing: Use business-day series for payroll, AP accruals, and headcount planning. Perguntar ao ChatGPT View
/api/forecast_cost_improved An extended 9-month daily cost forecaster that auto-benchmarks time-series (ARIMA, ETS, Prophet, TBATS) and tree-ML models, selects the champion by RMSE, and returns calendar & business-day forecasts plus key business indicators (trend, volatility, growth) for Finance & FP&A dashboards. • Long-Horizon Planning: Project up to 12 months of COGS/OPEX for treasury and cash-flow models. • Dashboard Health Read-Out: Business Indicators block surfaces trend direction, volatility, and growth %. • Staffing & Accruals: Use business-day forecasts for workforce planning and AP accruals; calendar view for top-line burn analysis. View
/api/forecast_revenue This endpoint generates a multi‑model revenue forecast over a specified horizon (e.g. 12 months). Under the hood it: Cleans and fills the historical series (≥ 60 days). Applies a model zoo (ARIMA, ETS, Prophet, TBATS, Croston, Aggregation). Runs rolling‑origin cross‑validation (4 folds) to score RMSE & MAPE. Selects the champion model by weighted RMSE (60 % calendar, 40 % business). Post‑processes to enforce non‑negativity and restore outliers. It returns both calendar‑day and business‑day (ex‑weekends/holidays) forecasts, error diagnostics, chosen algorithm, and run time. • “How much cash do we book next quarter?” – Feed calendar forecasts (with 80 % & 95 % CIs) into top‑line decks. • “Which model should we trust?” – Automatically benchmarks and explains best model choice. • “Ops needs both calendar & business views.” – Provides separate matrices for staffing and capacity planning. • Automate weekly runs, store forecast.calendar in BI layer, and trigger alerts if actuals deviate by ± 10 % for two consecutive weeks. View
/api/forecast_units Generate a one-shot, 6-month demand forecast at the SKU level (day-granular, calendar vs. business-day splits). The endpoint auto-benchmarks ARIMA, ETS, Prophet, TBATS, Random Forest, Gradient Boost, and Croston for intermittent demand, selects the best model by RMSE, and returns month-level unit forecasts with diagnostic metrics and run time. • Replenishment Planning: Feed calendar forecasts into PO generation to balance stock-out vs. over-stock. • Workforce Scheduling: Use business-day forecasts for labour and picking slot planning. • Intermittent & Lumpy Items: Auto-select Croston when demand is sparse without custom code. View
/api/inventory_history_improved A comprehensive “one‐stop” ledger that ingests raw purchases and sales, builds a day‐by‐day inventory balance with activity tags and percent‐changes, and delivers a full KPI deck (turnover, DOS, volatility, safety stock, margin, EOQ flags, etc.) plus a lot‐aging dashboard—ideal for operations, finance, and supply-chain teams. text Copiar Editar • Daily Audit & BI: Feed `daily_inventory` into dashboards for balance reconciliation and activity heat-maps. • Replenishment & Safety-Stock: Use turnover ratios, DOS, and safety‐stock metrics to automate reorder points and notifications. • Aging & Obsolescence: Monitor `inventory_aging` buckets to detect slow-moving lots and trigger markdowns or supplier reviews. • Financial Analysis: Leverage margin, price-elasticity, and carrying‐cost KPIs for P&L forecasting and capital‐tie reporting. • Alerting & Automation: Configure alerts when DOS exits target range or when on-hand falls below EOQ reorder level. View
/api/inventory_optimization Automatically computes optimal reorder points, safety stock, EOQ, inventory coverage, demand trends, and financial impact of any shortfall—so supply-chain, operations, and finance teams know exactly when and how much to order, and the cost of under- or over-stocking. • Procurement Automation: Trigger POs when `reorder_point` is breached. • Working-Capital Planning: Use `inventory_value` and `shortfall_cost_details` for cash-flow forecasts. • Demand-Planning Reviews: Adjust marketing, production, and staffing based on `forecast_demand_analysis`. • Service-Level Alerts: Surface `alerts.stock_status_alert` for immediate replenishment actions. • Continuous Optimization: Monitor EOQ and turnover ratios to fine-tune ordering cadence and reduce total cost. View
/api/journey_markov • Converts raw click-stream sessions into a Markov-chain funnel. • Returns per-step transition probabilities and drop-off rates. • Auto-appends absorbing states for success ("Conversion") and failure ("EXIT"). • Provides a natural-language summary of top bottlenecks and average path length. • Identify which funnel steps leak the most traffic and prioritise UX fixes. • Estimate probability of reaching critical stages (e.g. PDP → Cart). • Benchmark different variants (by device, region, campaign) with one API call. • Track improvements by comparing transition/dropp-off deltas over time. View
/api/journey_sequences • Mines all prefix-closed sequences up to `max_len` from your session data. • Prunes any prefix with total occurrences < `min_support`. • Returns the most common user journeys (by raw count), sorted descending. • Provides a one-sentence summary highlighting the #1 path and a next-step nudge. • Identify dominant user flows for conversion rate optimization (CRO). • Power on-site personalization by triggering content based on top prefixes. • Compare frequent patterns across cohorts (e.g. converted vs. non-converted). • Tune minimum support and path length to balance noise vs. insight granularity. View
/api/nlp_analisys_en Automatically transforms your raw JSON (SKU details, inventory, purchases, returns, multi-channel/regional sales, daily history) into a polished, multi-section English report—complete with insights, recommendations and next steps—ready to paste into emails, slide decks or BI tools. Executives & S&OP: Quick overview of stock health versus safety/ROP, margin, and channel/regional performance. Sales & Ops: Single source for channel vs. regional splits, with alignment actions. Finance & Inventory Planning: Justify inventory levels and margin health. Analysts: Save hours of write-up by dumping your BI JSON straight into this endpoint. View
/api/nlp_openai_excess_inventory_report Transforms your raw inventory JSON into a fully drafted, board-ready English report—covering product details, stock coverage, demand trends, financial impact of excess stock, management insights, and a tactical action plan for inventory reduction. • Board Decks & Executive Summaries: Paste `report_text` into slides or emails. • Operations & Supply-Chain: Use insights and alerts to trigger procurement or promotions. • Finance & FP&A: Clearly communicate excess cost implications and recovery strategies. • Marketing & Sales: Leverage the action plan to drive targeted campaigns and measure ROI. View
/api/nps Compute the overall Net Promoter Score by classifying responses into Promoters (9–10), Passives (7–8), and Detractors (0–6), then calculating (promoters% – detractors%) × 100. Optionally group by any categorical field to slice scores by store, region, plan, etc., with rounded percentages and interpretation bands. • Track global and per-group loyalty trends in BI dashboards • Set up real-time alerts on Detractor spikes (>20 %) • Compare performance across stores, channels, or plans • Route Detractor segments to customer success for follow-up • Promote high-NPS groups in marketing materials View
/api/propensity_buy_product Predict each customer’s probability of buying a specific SKU next cycle and assign them to one of five tiers (Very High, High, Medium, Low, Very Low) to drive targeted campaigns, look-alike audiences, and personalised recommendations. • Email optimisations: Target only High & Very High tiers for SKU promotions. • On-site personalisation: Show product banners to users with propensity ≥ 0.7. • Paid media: Export top 10% to seed look-alike audiences. • Sales prioritisation: Push “Very High” B2B accounts into call lists. View
/api/propensity_respond_campaign Forecast each customer’s likelihood to open/click/purchase when you send a specific campaign, returning calibrated probabilities and five-tier propensity labels for precise audience trimming, discount allocation, and incremental lift measurement. • Audience Trimming: Send only to Medium–Very High tiers to protect deliverability • Discount Allocation: Full coupons to top deciles; suppress Very Low to save cost • Channel Mix: SMS for High & Very High; cheaper channels for Medium; suppress Very Low • Hold-out Testing: Reserve a subset of Very High tier to measure true incremental ROI View
/api/propensity_upgrade_plan Predict each customer’s likelihood to upgrade from their current plan to a more lucrative target tier, returning calibrated probabilities, five-tier propensity labels, and concise interpretations for precision upsell targeting. • In-app Nudges: Trigger upgrade pop-ups for High & Very High tiers to maximize conversions • CSM Prioritization: Feed top tiers into account-manager dashboards for personalized outreach • Email Campaigns: Send discount offers only to Medium–High prospects; suppress Very Low to reduce fatigue • Pricing Analysis: Compare probability distributions before/after price changes to inform elasticity strategies View
/api/purchasing_segmentation Benchmark four clustering families (K-Means, Gaussian-Mixture, Agglomerative, DBSCAN), auto-select the best model by silhouette/Davies-Bouldin, and return cluster labels, centroids, marketing-ready personas, and the full dendrogram linkage for charting. Cluster 0 – Value Basket: low spend/mid frequency → product discovery emails Cluster 1 – Power Shoppers: high spend/frequency → VIP tier, bundles Cluster 2 – Tech Whales: highest spend/frequency → concierge & exclusive launches Combine with CLV/churn scores for 360° segmentation. View
/api/purchasing_segmentation_dendrogram Return Ward‐linkage matrix, centroids, and labels via Agglomerative clustering (k=2…10 auto‐selected) for interactive dendrogram and cluster‐explorer UIs. Ideal for visual drill‐downs; feed dendrogram into /api/segment_hierarchy_chart for nodes/links; render in D3/Plotly; save labels to your database; combine with CLV/churn for 360° segmentation. View
/api/recommend_similar_items Blend content-based TF-IDF similarity with collaborative-filtering co-view signals to return the top K catalogue SKUs most similar to a given reference item. • PDP carousels (“You may also like”) → +6–12% add-to-cart • Out-of-stock redirects → recover 30–40% lost sessions • Bundle builders → +8–15% average order value • Category discovery → ↑ pages-per-session & SEO dwell time View
/api/recommend_user_items Generate a ranked list of items most likely to interest a user by combining collaborative filtering (ALS) when data is dense, or content-based TF-IDF fallback for sparse/cold-start scenarios. • PDP Widgets: “You may also like” recommendations on product pages (+9% add-to-cart) • Post-purchase Emails: Top 5 unseen SKUs in follow-up mail (+18% repeat orders) • App Push: Daily single-SKU suggestion per active user (+7% DAU retention) • In-store Kiosks: Live personalized recs after loyalty card scan (+5% basket size) View
/api/segment_cluster_profiles Transform a raw customer → cluster mapping + base features into C-level summary cards that answer: “How big is each segment, what do they buy, how valuable are they, and what should we do next?” • One-click persona cards – drop cluster_profiles into Confluence, Notion, or a PDF. • Revenue skew insight – identify segments that punch above their head in revenue. • Creative brief generator – top_categories + insight = instant copy cues for marketing. • Board dashboards – feed these KPIs to leadership without exposing row-level data. View
/api/segment_hierarchy_chart Transforms a raw dendrogram into front-end–ready `nodes`, `links`, and `cluster_legend` arrays—no extra parsing needed in D3, Plotly, ECharts, or React. Ideal for interactive cluster explorers: load `nodes` & `links` into your force-graph or radial dendrogram; use `cluster_legend` for tooltips or side panels. View
/api/segment_subsegment_explore Performs a secondary K-Means sweep inside each parent cluster (or specified target_cluster), auto-selecting k by silhouette/Davies-Bouldin, and returns subcluster benchmarks, centroids, labels, legends, and English interpretations. • Tiered loyalty perks • Hyper-personalized recommendations • “Segment-of-one” exploratory analysis View
/api/segmentation_report_json?lang=en End-to-End Narrative Generator – auto-writes a complete JSON report (exec summary, cluster KPIs, marketing guidance, slide copy) from raw segmentation artefacts. • CMO / VP Marketing: 3-min board-ready briefs • Growth Manager: campaign copy & cross-sell ideas • Merchandising Lead: data-backed bundle suggestions • Data-Ops: automate PPT/BI dashboard generation View
/api/sentiment_realtime • Real-time triage of single messages (chat lines, tweets, reviews). • Returns sentiment polarity, dominant emotion, extracted topics. • Provides a one-liner “priority” hint (e.g. HIGH urgency for anger/frustration). • Power live support dashboards – flag urgent tickets before escalation. • Automate alerts on spikes of negative/emotion-heavy messages. • Route high-priority items to senior agents for rapid resolution. • Preserve metadata (channel, customer_id) for downstream analytics. • Combine with /api/sentiment_report for macro- vs micro-level monitoring. View
/api/sentiment_report • Analyzes free-text feedback (reviews, tickets, tweets, chat logs). • Classifies each entry by sentiment (negative/neutral/mixed/positive), emotion, and extracts key topics. • Aggregates KPIs over the specified timeframe: sentiment percentages and trending topics. • Provides per-entry details and a concise human-readable summary. • Monitor user satisfaction trends over time (daily alerts, weekly executive summaries). • Identify top pain-points (e.g., checkout failures, app crashes) via `top_topics`. • Drill into negative verbatims (`details` filtered by `sentiment=negative`) to prioritize fixes. • Tune data volume and granularity: batch ≥30 entries for stable topic clustering. • Feed enriched tags (e.g., “#login #bug”) to improve topic extraction. View
/api/uplift_model average_treatment_effect: Global incremental lift (>0 → campaign effective). treatment_cr / control_cr: Conversion rates by cohort. decile_summary: Mean uplift & size for each 10% bucket. details: Per-customer uplift_score & decile for targeting. Email marketing: Send only to top-2 uplift deciles (–30% sends, flat orders). Discount allocation: Offer incentives to high-uplift customers, preserve margin on low uplift. A/B hold-out: Use bottom decile as control for statistically sound lift measurement. View
/api/upsell_suggestions View