ifixkart-backend/swarm/scenarios/workshop_surge.py

205 lines
8.9 KiB
Python

"""
@scenario WorkshopSurgeScenario (swarm/scenarios/workshop_surge.py)
@purpose Simulates repair ticket intake surges and spare parts lead-time delays
to forecast workshop turnaround bottlenecks and technician backlog.
"""
import asyncio
import time
import json
from typing import Dict, Any, Callable, Optional, List
from pydantic import BaseModel, Field
from swarm.core.persona_generator import generate_personas, AgentPersona
from swarm.core.calibration import (
fetch_historical_baseline,
compute_simulation_dispersion,
synthesize_calibrated_projection,
)
from swarm.core.synthesizer import generate_markdown_report
from swarm.providers import get_llm_provider
from swarm.scenarios.base_scenario import BaseScenario, ScenarioResult
class WorkshopReasoningSchema(BaseModel):
archetype_id: str
delay_tolerance: str
interview_quote: str
class WorkshopSurgeScenario(BaseScenario):
async def run(
self,
input_params: Dict[str, Any],
store_id: int = 1,
cancellation_check: Optional[Callable[[], bool]] = None,
heartbeat_callback: Optional[Callable[[], None]] = None
) -> ScenarioResult:
start_time = time.perf_counter()
# 1. Inputs
surge_multiplier = float(input_params.get("surge_multiplier", 1.5)) # +50% repair tickets
parts_delay_days = int(input_params.get("parts_delay_days", 3)) # 3 days shipment delay
active_technicians = int(input_params.get("active_technicians", 4)) # 4 techs on bench
# 2. Baseline
baseline = fetch_historical_baseline("workshop_surge", store_id)
if heartbeat_callback:
heartbeat_callback()
if cancellation_check and cancellation_check():
raise InterruptedError("Simulation cancelled by user.")
# 3. Personas
personas = generate_personas(count=50, seed=202)
agent_outcomes: List[float] = []
agent_logs: List[Dict[str, Any]] = []
# Turnaround modeling
# Base hours = 4.2h. Surge adds queuing delay inversely proportional to techs
capacity_ratio = (surge_multiplier * 50) / max(1, active_technicians * 10)
delay_hours = (baseline.empirical_mean * capacity_ratio) + (parts_delay_days * 8.0)
disgruntled_count = 0
for p in personas:
# Individual sensitivity to delays
max_tolerable_hours = 8.0 if p.urgency > 0.8 else 48.0
is_satisfied = delay_hours <= max_tolerable_hours
if not is_satisfied:
disgruntled_count += 1
agent_outcomes.append(delay_hours)
agent_logs.append({
"agent_id": p.agent_id,
"archetype": p.archetype_name,
"urgency": p.urgency,
"projected_tat_hours": round(delay_hours, 1),
"satisfaction": "SATISFIED" if is_satisfied else "ESCALATED_DISPUTE"
})
if heartbeat_callback:
heartbeat_callback()
# 4. Dispersion & Calibration
dispersion = compute_simulation_dispersion(agent_outcomes)
projection = synthesize_calibrated_projection(baseline, dispersion)
# 5. LLM Synthesis
provider = get_llm_provider()
archetype_breakdown = []
interview_samples = []
total_prompt_tokens = 0
total_completion_tokens = 0
total_cost = 0.0
arch_groups = {}
for p in personas:
arch_groups.setdefault(p.archetype_id, []).append(p)
async def _eval_workshop_archetype(arch_id: str, p_list: List[AgentPersona]):
prompt = (
f"You are simulating repair customers during a workshop backlog at iFixKart.\n"
f"Current turnaround delay: {delay_hours:.1f} hours ({parts_delay_days} days parts delay).\n"
f"Archetype: {p_list[0].archetype_name}.\n"
f"Provide a 1-sentence assessment of their tolerance and a customer quote about this turnaround delay."
)
try:
reasoning, usage = await provider.generate_structured(
prompt=prompt,
schema=WorkshopReasoningSchema,
system_prompt="You are a customer experience (CX) and workshop operations auditor."
)
return {
"breakdown": {
"name": p_list[0].archetype_name,
"share": f"{len(p_list)/len(personas):.0%}",
"rate": f"{delay_hours:.1f} hrs",
"friction": reasoning.delay_tolerance
},
"sample": {
"persona": f"{p_list[0].archetype_name} ({p_list[0].name})",
"quote": reasoning.interview_quote
},
"usage": usage
}
except Exception:
return {
"breakdown": {
"name": p_list[0].archetype_name,
"share": f"{len(p_list)/len(personas):.0%}",
"rate": f"{delay_hours:.1f} hrs",
"friction": "Urgent device users will request job cancellation if delay exceeds 24h."
},
"sample": {
"persona": f"{p_list[0].archetype_name} ({p_list[0].name})",
"quote": "I need my phone for office work every day. Waiting 3 days for a screen is unacceptable."
},
"usage": None
}
results = await asyncio.gather(*(_eval_workshop_archetype(a_id, p_l) for a_id, p_l in arch_groups.items()))
for r in results:
archetype_breakdown.append(r["breakdown"])
interview_samples.append(r["sample"])
if r["usage"]:
total_prompt_tokens += r["usage"].prompt_tokens
total_completion_tokens += r["usage"].completion_tokens
total_cost += r["usage"].estimated_cost_usd
summary_metrics = {
"surge_multiplier": surge_multiplier,
"parts_delay_days": parts_delay_days,
"active_technicians": active_technicians,
"baseline_tat_hours": baseline.empirical_mean,
"projected_tat_hours": round(projection.calibrated_projected_value, 1),
"projected_turnaround_hours": round(projection.calibrated_projected_value, 1),
"baseline_daily_intake": round(15.0, 1),
"projected_queue_tickets": round(15.0 * surge_multiplier, 1),
"sla_threshold_hours": 48.0,
"dispute_risk_rate_pct": round((disgruntled_count / max(1, len(personas))) * 100.0, 1),
"bottleneck_severity": "CRITICAL" if delay_hours > 36.0 else ("ELEVATED" if delay_hours > 12.0 else "NORMAL"),
"safety_verdict": "CRITICAL CAPACITY BOTTLENECK" if delay_hours > 36.0 else ("ELEVATED QUEUE RISK" if delay_hours > 12.0 else "CAPACITY STABLE")
}
# 6. Render Report
elapsed_ms = int((time.perf_counter() - start_time) * 1000)
telemetry = {
"formatted_inputs": json.dumps(input_params, indent=2),
"recommendation_summary": (
f"Turnaround time inflates to {delay_hours:.1f} hours. "
f"{'Add 2 temporary bench technicians or pre-notify customers of parts arrival delays.' if delay_hours > 24 else 'Workload is manageable within standard SLAs.'}"
),
"execution_time_ms": elapsed_ms,
"model_name": getattr(provider, "model", "mock"),
"total_tokens": total_prompt_tokens + total_completion_tokens,
"prompt_tokens": total_prompt_tokens,
"completion_tokens": total_completion_tokens,
"total_cost_usd": round(total_cost, 6)
}
report_md = generate_markdown_report(
scenario_type="workshop_surge",
scenario_title=f"Workshop SLA & Surge Forecast ({surge_multiplier}x Intake, {parts_delay_days}d Delay)",
input_params=input_params,
baseline=baseline,
dispersion=dispersion,
projection=projection,
archetype_breakdown=archetype_breakdown,
interview_samples=interview_samples,
telemetry=telemetry
)
return ScenarioResult(
scenario_type="workshop_surge",
scenario_title=f"Workshop Surge ({summary_metrics['bottleneck_severity']})",
baseline=baseline,
dispersion=dispersion,
projection=projection,
summary_metrics=summary_metrics,
archetype_breakdown=archetype_breakdown,
interview_samples=interview_samples,
agent_logs=agent_logs,
report_markdown=report_md,
execution_time_ms=elapsed_ms,
prompt_tokens=total_prompt_tokens,
completion_tokens=total_completion_tokens,
total_cost_usd=round(total_cost, 6)
)