ifixkart-backend/swarm/scenarios/fleet_quote.py

187 lines
8.7 KiB
Python

"""
@scenario FleetQuoteScenario (swarm/scenarios/fleet_quote.py)
@purpose Simulates corporate B2B procurement committee deliberations (CFO, IT Admin, Security)
to predict bulk fleet quote win probability and optimize bid terms.
"""
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 ProcurementDeliberationSchema(BaseModel):
cfo_vote: bool
it_ops_vote: bool
compliance_vote: bool
primary_objection: str
recommended_adjustment: str
class FleetQuoteScenario(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
device_count = int(input_params.get("device_count", 50))
quoted_price_per_unit = float(input_params.get("quoted_price_per_unit", 4200.0))
warranty_months = int(input_params.get("warranty_months", 6))
turnaround_days = int(input_params.get("turnaround_days", 3))
# 2. Baseline
baseline = fetch_historical_baseline("fleet_quote", store_id)
if heartbeat_callback:
heartbeat_callback()
if cancellation_check and cancellation_check():
raise InterruptedError("Simulation cancelled by user.")
# 3. Simulate multi-member procurement personas (CFO, IT Ops, Security) across 15 enterprise profiles
personas = [p for p in generate_personas(count=50, seed=303) if p.b2b_focus]
if len(personas) < 15:
personas = generate_personas(count=50, seed=303)[:15]
agent_outcomes: List[float] = []
agent_logs: List[Dict[str, Any]] = []
# Pricing benchmark threshold (industry average for fleet laptop/screen service ~ Rs 3800)
target_benchmark = 3800.0
price_competitiveness = max(0.0, 1.0 - (quoted_price_per_unit - target_benchmark) / target_benchmark)
warranty_bonus = min(0.30, warranty_months * 0.05)
sla_penalty = max(0.0, (turnaround_days - 2) * 0.08)
accepted_deals = 0
for p in personas:
win_score = (price_competitiveness * 0.50) + warranty_bonus - sla_penalty
win_prob = min(0.95, max(0.05, baseline.empirical_mean + (win_score * 0.40)))
agent_outcomes.append(win_prob)
is_accepted = win_prob >= 0.50
if is_accepted:
accepted_deals += 1
agent_logs.append({
"agent_id": p.agent_id,
"enterprise_name": p.name,
"budget_cap": p.budget_inr,
"win_probability": round(win_prob, 3),
"decision": "ACCEPT_QUOTE" if is_accepted else "REJECT_OR_COUNTER"
})
if heartbeat_callback:
heartbeat_callback()
# 4. Dispersion & Calibration
dispersion = compute_simulation_dispersion(agent_outcomes)
projection = synthesize_calibrated_projection(baseline, dispersion)
# 5. LLM Procurement Deliberation
provider = get_llm_provider()
prompt = (
f"You are simulating a corporate B2B procurement committee for {device_count} enterprise devices at iFixKart.\n"
f"Quote Terms: Rs {quoted_price_per_unit}/unit, {warranty_months} months warranty, {turnaround_days} days turnaround.\n"
f"Simulated acceptance rate: {accepted_deals / max(1, len(personas)):.1%}.\n"
f"Provide the votes for CFO, IT Operations, and Compliance, with the primary objection and recommended counter-offer adjustment."
)
total_prompt_tokens = 0
total_completion_tokens = 0
total_cost = 0.0
try:
deliberation, usage = await provider.generate_structured(
prompt=prompt,
schema=ProcurementDeliberationSchema,
system_prompt="You are an enterprise B2B sales negotiation and procurement strategist."
)
total_prompt_tokens += usage.prompt_tokens
total_completion_tokens += usage.completion_tokens
total_cost += usage.estimated_cost_usd
cfo_vote = "Approved" if deliberation.cfo_vote else "Vetoed (Price too high)"
it_vote = "Approved" if deliberation.it_ops_vote else "Concerns (Turnaround time)"
comp_vote = "Approved" if deliberation.compliance_vote else "Concerns (Warranty terms)"
primary_objection = deliberation.primary_objection
recommended_adjustment = deliberation.recommended_adjustment
except Exception:
cfo_vote = "Approved" if quoted_price_per_unit <= 4000 else "Vetoed"
it_vote = "Approved" if turnaround_days <= 3 else "Needs 48h turnaround"
comp_vote = "Approved" if warranty_months >= 6 else "Demands 12-month warranty"
primary_objection = "Quoted price is 10% above standard bulk fleet maintenance benchmarks."
recommended_adjustment = "Offer Rs 3,950/unit if batch size increases to 75 units."
archetype_breakdown = [
{"name": "CFO / Finance Committee", "share": "40%", "rate": cfo_vote, "friction": primary_objection},
{"name": "IT Infrastructure Lead", "share": "35%", "rate": it_vote, "friction": f"Demands {turnaround_days}d maximum SLA"},
{"name": "Corporate Compliance / Legal", "share": "25%", "rate": comp_vote, "friction": f"{warranty_months}m warranty validation"}
]
interview_samples = [
{"persona": "Corporate IT Director", "quote": "We value the 6-month warranty, but we need guaranteed 48-hour swap capability for executive laptops."},
{"persona": "Enterprise Procurement Officer", "quote": f"At Rs {quoted_price_per_unit}, we need a volume rebate tier if quarterly volume crosses 100 devices."}
]
summary_metrics = {
"device_count": device_count,
"quoted_price_per_unit": quoted_price_per_unit,
"total_deal_value_inr": device_count * quoted_price_per_unit,
"baseline_win_rate_pct": round(baseline.empirical_mean * 100.0, 1),
"projected_win_rate_pct": round(projection.calibrated_projected_value * 100.0, 1),
"win_probability_category": "STRONG WIN (>= 60%)" if projection.calibrated_projected_value >= 0.60 else ("COMPETITIVE (40-59%)" if projection.calibrated_projected_value >= 0.40 else "AT RISK (< 40%)"),
"recommended_bid_adjustment": recommended_adjustment
}
# 6. Render Report
elapsed_ms = int((time.perf_counter() - start_time) * 1000)
telemetry = {
"formatted_inputs": json.dumps(input_params, indent=2),
"recommendation_summary": recommended_adjustment,
"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="fleet_quote",
scenario_title=f"B2B Corporate Fleet Quote Negotiation ({device_count} Units @ Rs {quoted_price_per_unit})",
input_params=input_params,
baseline=baseline,
dispersion=dispersion,
projection=projection,
archetype_breakdown=archetype_breakdown,
interview_samples=interview_samples,
telemetry=telemetry
)
return ScenarioResult(
scenario_type="fleet_quote",
scenario_title=f"Fleet Quote Simulation ({summary_metrics['win_probability_category']})",
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)
)