ifixkart-backend/swarm/scenarios/workshop_surge.py

186 lines
7.8 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 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)
for arch_id, p_list in arch_groups.items():
if cancellation_check and cancellation_check():
raise InterruptedError("Simulation cancelled by user.")
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."
)
total_prompt_tokens += usage.prompt_tokens
total_completion_tokens += usage.completion_tokens
total_cost += usage.estimated_cost_usd
delay_tolerance = reasoning.delay_tolerance
quote = reasoning.interview_quote
except Exception:
delay_tolerance = "Urgent device users will request job cancellation if delay exceeds 24h."
quote = "I need my phone for office work every day. Waiting 3 days for a screen is unacceptable."
archetype_breakdown.append({
"name": p_list[0].archetype_name,
"share": f"{len(p_list)/len(personas):.0%}",
"rate": f"{delay_hours:.1f} hrs",
"friction": delay_tolerance
})
interview_samples.append({
"persona": f"{p_list[0].archetype_name} ({p_list[0].name})",
"quote": quote
})
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),
"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")
}
# 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)
)