331 lines
12 KiB
Python
331 lines
12 KiB
Python
"""
|
||
@router SimulationRouter (Backend/app/api/v1/routers/SimulationRouter.py)
|
||
@purpose REST API endpoints for Swarm Intelligence & Predictive Digital Twin simulations.
|
||
"""
|
||
import asyncio
|
||
from datetime import datetime
|
||
from typing import List, Optional, Dict, Any
|
||
from fastapi import APIRouter, Depends, HTTPException, Query, status, Request
|
||
from pydantic import BaseModel, Field
|
||
from sqlalchemy.orm import Session
|
||
from sqlalchemy import desc
|
||
|
||
from app.core.database.db_session import get_db
|
||
from app.core.permissions.RoleChecker import RoleChecker, get_current_user
|
||
from app.core.limiter import limiter
|
||
from app.models.UserModel import User
|
||
|
||
# Swarm Package Imports
|
||
from swarm.models.simulation_job import SimulationJob
|
||
from swarm.scenarios import SCENARIO_REGISTRY
|
||
from swarm.queue import execute_simulation_job, request_job_cancellation
|
||
from swarm.providers import get_llm_provider
|
||
from swarm.config import swarm_settings
|
||
|
||
router = APIRouter(
|
||
prefix="/api/v1/simulation",
|
||
tags=["Swarm Intelligence & Predictive Simulation"],
|
||
dependencies=[Depends(RoleChecker(["Super Admin", "Admin", "Store Manager", "Manager"]))]
|
||
)
|
||
|
||
|
||
# --- SCHEMAS ---
|
||
class ScenarioRunRequest(BaseModel):
|
||
scenario_type: str = Field(..., description="One of: pricing_elasticity, whatsapp_preflight, workshop_surge, fleet_quote")
|
||
input_params: Dict[str, Any] = Field(default_factory=dict)
|
||
store_id: int = Field(default=1)
|
||
|
||
|
||
class JobSummaryResponse(BaseModel):
|
||
job_id: str
|
||
scenario_type: str
|
||
status: str
|
||
store_id: int
|
||
created_at: datetime
|
||
execution_time_ms: Optional[int] = None
|
||
total_cost_usd: Optional[float] = None
|
||
|
||
|
||
class JobDetailResponse(BaseModel):
|
||
id: str
|
||
store_id: int
|
||
user_id: int
|
||
scenario_type: str
|
||
status: str
|
||
input_params: Dict[str, Any]
|
||
historical_baseline: Optional[Dict[str, Any]] = None
|
||
simulation_dispersion: Optional[Dict[str, Any]] = None
|
||
calibrated_projection: Optional[Dict[str, Any]] = None
|
||
summary_metrics: Optional[Dict[str, Any]] = None
|
||
report_markdown: Optional[str] = None
|
||
agent_logs: Optional[List[Dict[str, Any]]] = None
|
||
error_message: Optional[str] = None
|
||
execution_time_ms: Optional[int] = None
|
||
prompt_tokens: Optional[int] = None
|
||
completion_tokens: Optional[int] = None
|
||
total_cost_usd: Optional[float] = None
|
||
last_heartbeat_at: Optional[datetime] = None
|
||
created_at: datetime
|
||
started_at: Optional[datetime] = None
|
||
completed_at: Optional[datetime] = None
|
||
|
||
|
||
class PersonaInterviewRequest(BaseModel):
|
||
agent_id: str
|
||
question: str
|
||
|
||
|
||
class PersonaInterviewResponse(BaseModel):
|
||
agent_id: str
|
||
question: str
|
||
response: str
|
||
latency_ms: int
|
||
|
||
|
||
# --- ENDPOINTS ---
|
||
@router.get("/scenarios")
|
||
def list_available_scenarios():
|
||
"""Lists all registered simulation scenarios and sample parameters."""
|
||
scenarios_meta = {
|
||
"pricing_elasticity": {
|
||
"title": "Dynamic Pricing & Discount Elasticity Predictor",
|
||
"description": "Simulates customer price sensitivity, sales volume change, and margin cannibalization.",
|
||
"default_params": {
|
||
"discount_pct": 15.0,
|
||
"current_price": 3500.0,
|
||
"cost_price": 2100.0,
|
||
"target_category": "Display & Touch Screens"
|
||
}
|
||
},
|
||
"whatsapp_preflight": {
|
||
"title": "WhatsApp Campaign Pre-Flight & Deliverability Risk",
|
||
"description": "Simulates customer reception, click-through rates, and phone number block/spam hazard.",
|
||
"default_params": {
|
||
"message_template": "Exclusive 20% off all display repairs this weekend at iFixKart!",
|
||
"offer_type": "20% Discount",
|
||
"frequency_per_month": 2,
|
||
"target_segment": "Past Customers"
|
||
}
|
||
},
|
||
"workshop_surge": {
|
||
"title": "Workshop SLA & Repair Volume Surge",
|
||
"description": "Simulates repair ticket intake surges and parts lead-time delays to forecast bottlenecks.",
|
||
"default_params": {
|
||
"surge_multiplier": 1.5,
|
||
"parts_delay_days": 3,
|
||
"active_technicians": 4
|
||
}
|
||
},
|
||
"fleet_quote": {
|
||
"title": "B2B Corporate Fleet Quote Negotiation",
|
||
"description": "Simulates corporate procurement committee (CFO, IT Admin, Legal) deliberation.",
|
||
"default_params": {
|
||
"device_count": 50,
|
||
"quoted_price_per_unit": 4200.0,
|
||
"warranty_months": 6,
|
||
"turnaround_days": 3
|
||
}
|
||
}
|
||
}
|
||
return {
|
||
"available_scenarios": list(SCENARIO_REGISTRY.keys()),
|
||
"scenarios": scenarios_meta,
|
||
"max_concurrent_simulations": swarm_settings.MAX_CONCURRENT_SIMULATIONS,
|
||
"job_timeout_seconds": swarm_settings.JOB_TIMEOUT_SECONDS
|
||
}
|
||
|
||
|
||
@router.post("/scenarios/run", status_code=status.HTTP_202_ACCEPTED)
|
||
@limiter.limit("5/minute")
|
||
async def launch_simulation(
|
||
request: Request,
|
||
payload: ScenarioRunRequest,
|
||
db: Session = Depends(get_db),
|
||
current_user: User = Depends(get_current_user)
|
||
):
|
||
"""
|
||
Validates parameters, enforces concurrency bounds, enqueues the simulation job,
|
||
and returns HTTP 202 Accepted.
|
||
"""
|
||
if payload.scenario_type not in SCENARIO_REGISTRY:
|
||
raise HTTPException(
|
||
status_code=status.HTTP_400_BAD_REQUEST,
|
||
detail=f"Invalid scenario '{payload.scenario_type}'. Supported: {list(SCENARIO_REGISTRY.keys())}"
|
||
)
|
||
|
||
# Check store active running jobs
|
||
active_count = (
|
||
db.query(SimulationJob)
|
||
.filter(
|
||
SimulationJob.store_id == payload.store_id,
|
||
SimulationJob.status.in_(["QUEUED", "CLAIMED", "RUNNING"])
|
||
)
|
||
.count()
|
||
)
|
||
if active_count >= swarm_settings.MAX_CONCURRENT_SIMULATIONS:
|
||
raise HTTPException(
|
||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||
detail=f"Store concurrency limit reached ({swarm_settings.MAX_CONCURRENT_SIMULATIONS} concurrent runs). Please wait for ongoing jobs to complete."
|
||
)
|
||
|
||
# Persist QUEUED state
|
||
import ulid
|
||
job_id = str(ulid.ULID())
|
||
job = SimulationJob(
|
||
id=job_id,
|
||
store_id=payload.store_id,
|
||
user_id=current_user.id if hasattr(current_user, "id") else 1,
|
||
scenario_type=payload.scenario_type,
|
||
status="QUEUED",
|
||
input_params=payload.input_params
|
||
)
|
||
db.add(job)
|
||
db.commit()
|
||
|
||
# Dispatch execution cleanly in background thread running independent event loop
|
||
import threading
|
||
threading.Thread(
|
||
target=lambda: asyncio.run(execute_simulation_job(job_id)),
|
||
daemon=True,
|
||
name=f"sim-worker-{job_id[:8]}"
|
||
).start()
|
||
|
||
return {
|
||
"message": "Simulation job enqueued successfully.",
|
||
"job_id": job_id,
|
||
"status": "QUEUED",
|
||
"poll_url": f"/api/v1/simulation/jobs/{job_id}"
|
||
}
|
||
|
||
|
||
@router.get("/jobs/{job_id}", response_model=JobDetailResponse)
|
||
def get_simulation_job_detail(
|
||
job_id: str,
|
||
db: Session = Depends(get_db),
|
||
current_user: User = Depends(get_current_user)
|
||
):
|
||
"""Retrieves complete details, status, and prediction report for a simulation job."""
|
||
job = db.query(SimulationJob).filter(SimulationJob.id == job_id).first()
|
||
if not job:
|
||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Simulation job '{job_id}' not found.")
|
||
|
||
return JobDetailResponse(
|
||
id=job.id,
|
||
store_id=job.store_id,
|
||
user_id=job.user_id,
|
||
scenario_type=job.scenario_type,
|
||
status=job.status,
|
||
input_params=job.input_params or {},
|
||
historical_baseline=job.historical_baseline,
|
||
simulation_dispersion=job.simulation_dispersion,
|
||
calibrated_projection=job.calibrated_projection,
|
||
summary_metrics=job.summary_metrics,
|
||
report_markdown=job.report_markdown,
|
||
agent_logs=job.agent_logs,
|
||
error_message=job.error_message,
|
||
execution_time_ms=job.execution_time_ms,
|
||
prompt_tokens=job.prompt_tokens,
|
||
completion_tokens=job.completion_tokens,
|
||
total_cost_usd=float(job.total_cost_usd) if job.total_cost_usd is not None else None,
|
||
last_heartbeat_at=job.last_heartbeat_at,
|
||
created_at=job.created_at,
|
||
started_at=job.started_at,
|
||
completed_at=job.completed_at
|
||
)
|
||
|
||
|
||
@router.get("/jobs", response_model=List[JobSummaryResponse])
|
||
def list_simulation_jobs(
|
||
store_id: int = Query(default=1),
|
||
skip: int = Query(default=0, ge=0),
|
||
limit: int = Query(default=20, ge=1, le=100),
|
||
db: Session = Depends(get_db),
|
||
current_user: User = Depends(get_current_user)
|
||
):
|
||
"""Lists historical simulation runs for a store."""
|
||
jobs = (
|
||
db.query(SimulationJob)
|
||
.filter(SimulationJob.store_id == store_id)
|
||
.order_by(desc(SimulationJob.created_at))
|
||
.offset(skip)
|
||
.limit(limit)
|
||
.all()
|
||
)
|
||
return [
|
||
JobSummaryResponse(
|
||
job_id=j.id,
|
||
scenario_type=j.scenario_type,
|
||
status=j.status,
|
||
store_id=j.store_id,
|
||
created_at=j.created_at,
|
||
execution_time_ms=j.execution_time_ms,
|
||
total_cost_usd=float(j.total_cost_usd) if j.total_cost_usd is not None else None
|
||
)
|
||
for j in jobs
|
||
]
|
||
|
||
|
||
@router.post("/jobs/{job_id}/cancel")
|
||
def cancel_simulation_job(
|
||
job_id: str,
|
||
db: Session = Depends(get_db),
|
||
current_user: User = Depends(get_current_user)
|
||
):
|
||
"""Requests immediate cancellation of a running or queued simulation."""
|
||
job = db.query(SimulationJob).filter(SimulationJob.id == job_id).first()
|
||
if not job:
|
||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Simulation job '{job_id}' not found.")
|
||
|
||
if job.status in ["COMPLETED", "FAILED", "TIMED_OUT", "CANCELLED"]:
|
||
return {"message": f"Job is already in final state '{job.status}'.", "status": job.status}
|
||
|
||
success = request_job_cancellation(job_id)
|
||
return {"message": "Cancellation requested successfully.", "job_id": job_id, "cancelled": success}
|
||
|
||
|
||
@router.post("/jobs/{job_id}/interview", response_model=PersonaInterviewResponse)
|
||
async def interview_simulated_persona(
|
||
job_id: str,
|
||
payload: PersonaInterviewRequest,
|
||
db: Session = Depends(get_db),
|
||
current_user: User = Depends(get_current_user)
|
||
):
|
||
"""
|
||
Directly asks questions to a simulated persona from a completed simulation run.
|
||
Uses multi-turn chat adhering to the persona's persona profile.
|
||
"""
|
||
job = db.query(SimulationJob).filter(SimulationJob.id == job_id).first()
|
||
if not job:
|
||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Simulation job '{job_id}' not found.")
|
||
|
||
if job.status != "COMPLETED":
|
||
raise HTTPException(
|
||
status_code=status.HTTP_400_BAD_REQUEST,
|
||
detail=f"Cannot interview persona: Job is in state '{job.status}'. Job must be 'COMPLETED'."
|
||
)
|
||
|
||
# Locate persona in agent logs
|
||
agent_logs = job.agent_logs or []
|
||
target_log = next((log for log in agent_logs if log.get("agent_id") == payload.agent_id), None)
|
||
if not target_log:
|
||
raise HTTPException(
|
||
status_code=status.HTTP_404_NOT_FOUND,
|
||
detail=f"Agent '{payload.agent_id}' was not part of simulation run '{job_id}'."
|
||
)
|
||
|
||
provider = get_llm_provider()
|
||
system_prompt = (
|
||
f"You are simulated customer '{payload.agent_id}' belonging to archetype '{target_log.get('archetype', 'Customer')}'. "
|
||
f"In a simulated scenario involving '{job.scenario_type}', your recorded decision was '{target_log.get('decision', 'N/A')}'. "
|
||
f"Answer the store manager's question in 1–2 authentic sentences strictly from your persona's perspective."
|
||
)
|
||
|
||
messages = [{"role": "user", "content": payload.question}]
|
||
reply, usage = await provider.chat(messages, system_prompt=system_prompt)
|
||
|
||
return PersonaInterviewResponse(
|
||
agent_id=payload.agent_id,
|
||
question=payload.question,
|
||
response=reply,
|
||
latency_ms=usage.latency_ms
|
||
)
|