NEXORA is a production-grade AI decision and engagement platform that transforms dynamic business context into intelligent, personalized customer interactions. Leveraging structured datasets, trigger-priority orchestration, context-aware prompt engineering, multi-turn conversational intelligence, and enterprise-grade validation, it autonomously generates explainable WhatsApp engagements through a resilient, scalable architecture.
Team: NEXORA Engine Β· Stack: FastAPI Β· MongoDB Β· Redis Β· Groq (Llama 3.3) Β· Next.js
Built on a fully data-driven architecture with intelligent trigger orchestration, explainable AI decisions, resilient conversation state management, and enterprise-grade validation.
- π What is NEXORA?
- π§ How NEXORA Thinks
- ποΈ System Architecture
- βοΈ Technology Stack
- β¨ Feature Highlights
- π Quick Start (Docker)
- π» Local Setup (No Docker)
- π‘ API Reference Summary
- β Error Ingestion & Codes
- π Trigger Priority Ranking
- π Supported Trigger Kinds
- π§ Configuration Environment
- π§ͺ Testing Framework
- π Project Structure
- βοΈ Judge Evaluation Workflow
- π License
NEXORA is a production-grade merchant engagement assistant engineered for magicpinβs AI Challenge. The core service acts as an autonomous cognitive gateway, converting background data events (triggers) into highly personalized, contextual WhatsApp outreach.
Unlike basic templated bots, NEXORA enforces a strict 4-context resolution (Category, Merchant, Customer, Trigger) to anchor all LLM generation. Every number, percentage, date, and name must exist in the context payloads; hallucinations are strictly blocked by the validation pipeline.
By combining low-latency inference on Groq's Llama 3.3 with local cache controls via Redis and persistent audit logging in MongoDB, NEXORA satisfies the challenge's strict 30-second response budget while guaranteeing production safety, conversation state tracking, and rate limiting.
Important
- π₯οΈ Live Operations Dashboard (UI): https://nexorabot-ai.vercel.app/
- β‘ Deployed Backend Engine (API): https://nexora-studio-0aaz.onrender.com/ (Health Endpoint:
/v1/healthz)
| Environment | Backend Endpoint | Frontend Dashboard |
|---|---|---|
| βοΈ Live Production | https://nexora-studio-0aaz.onrender.com/ |
https://nexorabot-ai.vercel.app/ |
| π» Local Development | http://localhost:8080 |
http://localhost:3000 |
graph TD
subgraph Context Ingestion Sources
Cat[Category Context: Voice, Tone, Seasonal Beats]
Mer[Merchant Context: Metrics, Identity, Language]
Cust[Customer Context: Interaction History, Preferences]
Trg[Trigger Context: Event Kind, Urgency, Expiry, Payload]
end
Cat & Mer & Cust & Trg -->|Extracted Concurrently| Assembler[Context Assembler Subsystem]
Assembler -->|Unified Payload Structure| Prompter[Context-Aware Prompt Builder]
Prompter -->|Bilingual Strategy Prompt| LLM[Groq Llama 3.3 Engine]
NEXORA adapts its conversational register dynamically to match the expected tone of different local business categories:
- Dentists (
dentists): Uses a clinical peer voice. Tone is professional and clinical. It references patient segments, clinical studies, and page numbers, strictly avoiding marketing buzzwords like "discount" or "cheap offer." - Salons & Spas (
salons): Employs a warm and practical tone. It emphasizes relaxation, personal care windows, prep durations, and reservation slot convenience. - Gyms & Fitness (
gyms): Communicates as a motivational coach. Emphasizes habit consistency, metric goals, active participation, and slot availability. - Restaurants & Dining (
restaurants): Uses an operator-to-operator register. Discusses delivery margins, covers-per-hour, seasonal spikes, kitchen prep constraints, and match-day forecasts. - Pharmacies (
pharmacies): Adopts a trustworthy and precise tone. Focuses on refill schedules, senior discount programs, batch verification, and molecule safety alerts.
NEXORA follows a systematic workflow to evaluate opportunities and compose messages:
- Ingestion: Real-time system states (contexts) are pushed via an idempotent HTTP API. Stale version numbers are rejected immediately.
- Prioritization: Active trigger signals are prioritized and sorted using a deterministic, multi-dimensional formula (calculating urgency, expiry, business kind, and context richness).
- Assembly: Category voice parameters, merchant metrics, customer history, and trigger payloads are merged into a single multi-dimensional context.
-
Composition: The prompt builder dispatches the assembled context to the LLM (temperature
$T=0$ , running on Groq Llama 3.3). If Groq experiences an outage, it automatically fails over to a secondary Llama 3.1 model. - Verification: The validation engine analyzes the generated message. It strips dangerous URLs, checks for required psychological compulsion levers, corrects mismatching sender scopes, and blocks repetitions.
- Outreach: Compliant actions are returned to the client and logged to MongoDB. Suppression keys are set in Redis to prevent outreach fatigue.
When an inbound reply turn is received via POST /v1/reply, NEXORA executes a pipeline to determine the appropriate response:
- Rate Limit Check: Evaluates both IP limits and conversation turn limits in Redis to prevent loops.
- Active Thread Check: Confirms if the conversation has already been marked as ended in Redis.
- Auto-Reply Detection: Uses pattern matching to identify automatic business canned messages. If detected, it increments a strike counter in Redis and triggers wait or end states.
- Opt-Out Router: Scans the text for hard-stop keywords. If matched, it sets the conversation status to ended and generates a polite exit message.
- Commit Router: Scans for affirmative signals. If matched, it transitions the LLM prompt to Action Mode.
- Language Check: Analyzes characters and Hinglish code-mix markers to adjust translation directives.
- LLM Compilation: Submits the compiled turn history and category constraints to the LLM.
graph TD
Inbound[Inbound Message] --> Limit{Rate Limit Check?}
Limit -->|Exceeded| Block[HTTP 429 Block]
Limit -->|Allowed| AutoCheck{Is Auto-Reply?}
AutoCheck -->|Yes| Strike{Increment Strike: Strike count?}
Strike -->|Strike 1| Nudge[Generate Canned Nudge]
Strike -->|Strike 2| Wait[24-Hour Wait State Lock]
Strike -->|Strike 3| End[Mark Ended & Stop]
AutoCheck -->|No| IntentCheck{Opt-Out or Stop Keyword?}
IntentCheck -->|Yes| OptOut[Mark Ended & Send Exit msg]
IntentCheck -->|No| CommitCheck{Explicit Commit Keyword?}
CommitCheck -->|Yes| ActionPrompt[LLM Strategy: Action Mode]
CommitCheck -->|No| ChatPrompt[LLM Strategy: Discovery Mode]
ActionPrompt & ChatPrompt --> LLM[Llama 3.3 Inference]
graph TD
Client[Client / Judge] -->|REST Request| API[FastAPI Gateway]
API -->|Global Rate Limit Check| Redis[(Redis Cache)]
API -->|Payload Verification| Mongo[(MongoDB)]
subgraph Composition Pipeline
Priority[Trigger Priority Engine]
Assembly[Context Assembler]
Prompt[Prompt Builder]
Groq[Groq Llama Client]
Validator[Output Validator]
Priority --> Assembly --> Prompt --> Groq --> Validator
end
API -->|POST /v1/tick| Priority
Validator -->|Log Audit Trail & Set Suppression| Mongo
Validator -->|Set Suppression Key| Redis
Validator -->|Return Action| API
sequenceDiagram
autonumber
Client->>API: POST /v1/tick {now, triggers}
API->>Mongo: Fetch Triggers Concurrently
Mongo-->>API: Return Trigger Payloads
API->>Priority: Score & Sort Triggers (0-100)
Note over Priority: Urgency + Expiry + Kind + Source + Scope + payload keys
Priority-->>API: Ranked Triggers List
loop For each ranked trigger
API->>Redis: Check Suppression key
Redis-->>API: return is_suppressed
alt not suppressed
API->>Assembly: Assemble (Category + Merchant + Customer)
Assembly-->>API: Combined Context
API->>Prompt: Prompt Builder (Master system + kind addendum)
Prompt-->>API: Prompts System/User
API->>Groq: Query Llama 3.3 (22s timeout, temp=0)
Groq-->>API: JSON Message
API->>Validator: Validate Output
Note over Validator: Strips URLs, validates CTA, corrects send_as
Validator-->>API: Validated Action
API->>Mongo: Save Actions Log
API->>Redis: Set Suppression Key (7-day TTL)
end
end
API-->>Client: Return actions list with processing_ms
stateDiagram-v2
[*] --> Active
Active --> AutoReply1 : Inbound Auto-Reply (1st strike)
AutoReply1 --> Active : Inbound Genuine Message
AutoReply1 --> AutoReply2 : Inbound Auto-Reply (2nd strike)
AutoReply2 --> Active : Inbound Genuine Message
AutoReply2 --> WaitState : Wait 24h timer active
WaitState --> AutoReply3 : Turn during wait window
AutoReply3 --> Ended : Inbound Auto-Reply (3rd strike) -> Close
Active --> Ended : Hard Opt-out ("Stop" / "Exit")
Active --> ActionMode : Explicit Commit ("Yes" / "Confirm")
ActionMode --> Ended : Conversation Finished
- Runtime Framework: FastAPI (Python 3.13)
- Database (Durable Store): MongoDB 7 (Persistent context payloads, action logs, audit trails)
- Cache (In-memory Cache): Redis 7 (Version checking, sliding-window rate limiters, suppression keys)
- Inference Gateway: Groq API client
-
Primary LLM Model: Llama-3.3-70b-versatile (deterministic execution,
$T=0$ ) - Fallback LLM Model: Llama-3.1-8b-instant (automatic failover)
- UI Dashboard: Next.js (App Router, Tailwind v4, TypeScript)
- Deployment: Docker, Docker Compose
- π Strict URL Stripping: Strips any inbound or outbound URLs to comply with Meta's messaging policies, avoiding API penalties.
- β‘ Idempotence & Version Checking: Context updates enforce strict monotonically increasing versions. Out-of-order or duplicate updates are rejected.
- π‘οΈ Resilient Health Checks: The
/v1/healthzendpoint handles database exceptions gracefully, reportingdegradedconnectivity status rather than returning a 500 server error. - π£οΈ Bilingual Hindi-English (Hinglish): Seamless code-mixing for merchants with
"hi"language preferences, mirroring local Indian commerce styles naturally. - π€ Automated Responder Mitigation: Implements a three-strike rule to prevent infinite loops when interacting with automated business reply systems.
- π¬ Diagnostic Decision Auditor: Includes
/v1/action/{id}/explainto expose exactly why actions were taken, which category beats matched, and what compulsion levers were used.
To run the complete stack (FastAPI Backend, Next.js Frontend, MongoDB, Redis):
-
Clone and Configure:
git clone https://github.com/UjjwalSaini07/Nexora-Studio
cd Nexora-Studio cp .env.example .envSet your Groq API Key in
.env:GROQ_API_KEY=gsk_your_groq_api_key_here
Project settings are centralized in config.py & .env and the service modules. If you need the exact deployment values, service wiring, or notification settings & the keys for your environment, contact the author through the Author & System Architect section at the end of this README.
-
Launch Stack:
docker compose up --build -d
-
Verify Health:
curl http://localhost:8080/v1/healthz
-
Explore Operations Dashboard: Open
http://localhost:3000to inspect live operations, conversation threads, and context versions.
cd backend
cp .env.example .env
# Edit backend/.env and configure python -m venv venvsource venv/bin/activate # Windows: venv\Scripts\activatepip install -r requirements.txt# Pre-seed the MongoDB database with expanded mock dataset
python3 ../dataset/generate_dataset.py --seed-dir ../dataset --out ../expanded# Start the development server
uvicorn main:app --host 0.0.0.0 --port 8080 --reloadcd frontend
cp .env.example .env.local
# Set NEXT_PUBLIC_BOT_URL=http://localhost:8080 in env.local
npm install
npm run dev| HTTP Verb | Path | Request Body | Success Code | Purpose |
|---|---|---|---|---|
GET |
/v1/healthz |
None | 200 |
Liveness check (DB connectivity & uptime). |
GET |
/v1/metadata |
None | 200 |
Team metadata and challenge approach. |
POST |
/v1/context |
ContextBody JSON |
200 |
Ingest new context versions. |
POST |
/v1/tick |
TickBody JSON |
200 |
Evaluate triggers and return actions. |
POST |
/v1/reply |
ReplyBody JSON |
200 |
Process conversational reply turns. |
POST |
/v1/teardown |
None | 200 |
Wipe all tables (called between test windows). |
POST |
/v1/demo/reset |
None | 200 |
Clear suppression, wait states, and conversations. |
GET |
/v1/action/{id}/explain |
None | 200 |
Audit decision path for a conversation. |
NEXORA exposes its full cognitive routing trace through the explain endpoint. This returns diagnostic details about why a specific trigger was prioritized and what factors were extracted during generation:
{
"conversation_id": "conv_m_001_trg_001",
"trigger_id": "trg_001",
"why_selected": "Trigger 'trg_001' of kind 'research_digest' with urgency 3 was selected and assigned a priority score of 75 (ranked #1).",
"priority_breakdown": {
"score": 75,
"rank": 1,
"reason": "score=75: [urgency=3/5 -> 15pts] + [expires_in=24.5h -> 20pts] + [kind=research_digest -> 8pts] + [source=external -> 10pts] + [scope=merchant -> 7pts] + [payload_keys=2 -> 4pts]"
},
"merchant_signals_used": ["low_ctr"],
"category_signals_used": ["Nov-Feb exam-stress bruxism spike"],
"customer_signals_used": [],
"compulsion_levers_used": ["specificity", "effort_externalization"],
"confidence_score": 0.92,
"suppression_status": {
"is_suppressed": false,
"suppression_key": "sup_research_m_001"
},
"wait_state_status": {
"is_waiting": false,
"wait_until": null
},
"rationale": "Anchored on recent clinical digest item. Proposing patient campaign workflow utilizing commitment lever."
}The API wraps validation and runtime errors in a standard error schema:
{
"success": false,
"accepted": false,
"reason": "error_reason_slug",
"error": {
"code": "ERROR_CODE_SLUG",
"message": "Detailed error description."
}
}Standard Codes:
INVALID_JSON(400): Malformed JSON syntax in request body.BAD_REQUEST(400): Invalid scope provided in context push.TRIGGER_NOT_FOUND(404): Specified trigger ID does not exist.MERCHANT_NOT_FOUND(404): Specified merchant ID does not exist.CUSTOMER_NOT_FOUND(404): Specified customer ID does not exist.PAYLOAD_TOO_LARGE(413): Request body exceeds2MBcap.VALIDATION_ERROR(422): Request parameters failed validation checks.RATE_LIMIT_EXCEEDED(429): Global or endpoint rate limits exceeded.INTERNAL_ERROR(500): Unexpected exception in backend code.
Triggers processed during /v1/tick are ranked using a deterministic 0-100 score:
-
Urgency (Max 25): Clamped urgency score (
$1 \text{ to } 5$ )$\times 5$ . -
Expiry Proximity (Max 25): Expiry window proximity scoring.
$\le 24$ hours left =$25\text{pts}$ .$\ge 168$ hours left =$0\text{pts}$ . No expiry =$12\text{pts}$ . - Kind Weight (Max 20): Business kind weight assigned to the trigger kind.
-
Source Weight (Max 10):
external=$10\text{pts}$ ,internal=$6\text{pts}$ . -
Scope Weight (Max 10):
customer(direct revenue) =$10\text{pts}$ ,merchant=$7\text{pts}$ . -
Payload Richness (Max 10): Number of payload dictionary keys
$\times 2$ (capped at 10).
Ties are broken lexicographically by trigger ID.
NEXORA supports 27 trigger configurations:
- Critical Events (20pts):
supply_alert,regulation_change. - High Commercial Value (18pts):
appointment_tomorrow,recall_due,chronic_refill_due. - Retention Nudges (16pts):
renewal_due. - Performance Signals (14-15pts):
perf_spike,perf_dip,seasonal_perf_dip,competitor_opened. - Warmup Tests & Loops (10-13pts):
customer_lapsed_hard,ipl_match_today,winback_eligible,bridal_followup,wedding_package_followup,festival_upcoming,trial_followup,customer_lapsed_soft,category_seasonal. - Relationship Celebrations (5-9pts):
milestone_reached,review_theme_emerged,gbp_unverified,cde_opportunity,research_digest,active_planning_intent,dormant_with_nexora,curious_ask_due.
GROQ_API_KEY(Required): API key for Llama model calls.LLM_MODEL(Default:llama-3.3-70b-versatile): Core composition model.LLM_FALLBACK_MODEL(Default:llama-3.1-8b-instant): Failover composition model.LLM_TIMEOUT_SECONDS(Default:22): Threshold before attempting failover.MONGO_URI(Default:mongodb://localhost:27017): MongoDB connection string.REDIS_URL(Default:redis://localhost:6379): Redis connection string.RATE_LIMIT_PER_MINUTE(Default:1200): Global request rate limit per minute.DEMO_MODE(Default:true): Bypasses suppression logic for demonstration purposes.ENABLE_AUTH(Default:false): Enables token authentication.API_AUTH_TOKEN(Default: None): Authorization Bearer token.
NEXORA includes an extensive test suite with 101 tests (100% passing):
cd backend
pytest tests/ -v- Unit Tests: Prompt formatting, lever matching, language switching, output validation.
- Integration Tests: Core API flows, versioning controls, wait-state timers, rate limit blocks.
- Warmup Tests: Warmup simulation matching Phase 1 of the testing brief (verifies that 255 base contexts load successfully).
- Validation Tests: Simulates all 30 canonical test cases against the live API, validating output schemas and formatting.
Nexora-Studio/
βββ backend/ # FastAPI Application Code
β βββ main.py # Lifespan coordination, middleware initialization, exception handlers
β βββ bot.py # Thin entrypoint alias for uvicorn launcher
β βββ config.py # Environment configurations
β βββ middleware.py # Global rate limiter, payload size verifier, logging middleware
β βββ models/ # Pydantic schemas (requests, responses, contexts)
β βββ storage/ # Database adapter singletons (Redis, MongoDB)
β βββ composer/ # Message composition pipeline modules
β βββ reply/ # Multi-turn conversational handler modules
β βββ routers/ # API controller route endpoints
β βββ dataset/ # Mock dataset loaders and seeding tools
β βββ tests/ # 101 automated test cases
β βββ Dockerfile # Container configuration (runs as non-root user)
βββ frontend/ # Next.js UI operations dashboard
βββ dataset/ # Challenge base JSON seeds
βββ expanded/ # Seeding dataset generated at build
βββ documents/ # Challenge documentation files
βββ docker-compose.yml # Orchestration file
βββ judge_simulator.py # Local testing grading simulator
βββ generate_submission.py # Submits 30 canonical tests to API -> submission.jsonl
To verify NEXORA against the Magicpin AI Challenge grading harness:
Tip
Testing Target URL: By default, the commands below target the local endpoint (http://localhost:8080). To test the live deployed server, replace http://localhost:8080 with the production API URL: https://nexora-studio-0aaz.onrender.com.
-
Launch Stack:
docker compose up --build
-
Verify Health & Load Status:
curl http://localhost:8080/v1/healthz # Ensure all contexts are preloaded (category: 5, merchant: 50, customer: 200, trigger: 100) -
Run Grading Simulator:
-
Local Backend:
python3 judge_simulator.py --bot-url http://localhost:8080 --groq-api-key $GROQ_API_KEY -
Live Deployed Production Backend:
python3 judge_simulator.py --bot-url https://nexora-studio-0aaz.onrender.com --groq-api-key $GROQ_API_KEY
-
Local Backend:
-
Inspect Score Diagnostic Log:
Examine the generated audit logs on the dashboard (
http://localhost:3000/scoresorhttps://nexorabot-ai.vercel.app/scores) to verify URL compliance, compulsion checks, and response latency.
The generate_submission.py script produces the official submission.jsonl file required by the magicpin AI Challenge. It drives the live running bot through its HTTP API (/v1/context and /v1/tick) using the 30 canonical test cases, validating response formatting and schemas dynamically. This ensures that the generated submission file matches exactly what the live bot would output during evaluation.
To generate the submission file from the backend/ directory:
-
Launch the Backend Server: Start your FastAPI backend in a PowerShell window:
uvicorn main:app --host 0.0.0.0 --port 8080
-
Run the Generator Script: Open a second PowerShell window, change directory to
backend/, configure theBOT_URLenvironment variable (either local or live deployed), and execute the generator:cd backend # For Local Dev: $env:BOT_URL="http://localhost:8080" # Or for Live Deployed Production: # $env:BOT_URL="https://nexora-studio-0aaz.onrender.com"
python ../generate_submission.py --expanded-dir ../expanded --out ../submission.jsonl
If using standard Windows Command Prompt (CMD), run:
cd backend
:: For Local Dev:
set BOT_URL=http://localhost:8080
:: Or for Live Deployed Production:
:: set BOT_URL=https://nexora-studio-0aaz.onrender.com
python ..\generate_submission.py --expanded-dir ..\expanded --out ..\submission.jsonlUpon successful execution, the script will output log traces indicating contexts are loaded and tick events are evaluated:
Loaded 30 canonical test pairs.
Verifying connection to http://localhost:8080/v1/healthz ... Connected!
[1/30] Processing trigger: trg_001_recall_due for merchant: m_001_drmeera_dentist_delhi
Pushed category, merchant, customer, and trigger contexts.
Executing tick event...
Generated action successfully (CTA: multi_choice_slot)
...
[30/30] Processing trigger: trg_030_curious_ask_due for merchant: m_010_nupurdental_dentist_delhi
Generated action successfully (CTA: binary_yes_no)
Successfully completed all 30 test pairs.
Submission file saved at: F:\_Code\Nexora-Studio\submission.jsonl
Overview Tab 1 |
Overview Tab 2 |
Overview Tab 3 |
Overview Tab 4 |
Overview Tab 5 |
Conversation Tab 1 |
Conversation Tab 2 |
Conversation Tab 3 |
Contexts Tab 1 |
Contexts Tab 2 |
Contexts Tab 3 |
Contexts Tab 4 |
Simulator Tab 1 |
Simulator Tab 2 |
Simulator Tab 3 |
Scores Tab 1 |
Scores Tab 2 |
Scores Tab 3 |
Architecture Tab 1 |
Architecture Tab 2 |
This project is licensed under the MIT License. See LICENSE for more details.
Ujjwal Saini Founder, Lead Engineer & System Architect
Passionate Full-Stack Engineer specializing in AI-powered systems, computer vision, real-time analytics, and scalable platform architecture. Focused on building production-grade solutions that transform raw operational data into actionable business intelligence. Hey, I'm Ujjwal β a creative full-stack developer with a deep love for design, motion, and digital storytelling. I bring bold ideas to life through stunning interfaces and seamless user experiences, always chasing clarity in every interaction.
My stack is MERN-focused, but my mindset is product-first. I thrive in fast-paced environments where innovation and precision matter, constantly pushing for smarter, cleaner, and faster solutions.
- Portfolio: ujjwalsaini.vercel.app
- GitHub: @UjjwalSaini07
- LinkedIn: @ujjwalsaini07
- Twitter/X: @UjjwalSx007
- Email: ujjwalsaini0007+nexora@gmail.com




















