""" @scenario PricingElasticityScenario (swarm/scenarios/pricing_elasticity.py) @purpose Simulates customer price sensitivity, sales volume change, and margin cannibalization. """ 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 ArchetypeReasoningSchema(BaseModel): archetype_id: str conversion_rate: float = Field(..., ge=0.0, le=1.0) primary_friction: str interview_quote: str class PricingElasticityScenario(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. Parse & validate inputs discount_pct = float(input_params.get("discount_pct", 15.0)) current_price = float(input_params.get("current_price", 3500.0)) cost_price = float(input_params.get("cost_price", 2100.0)) target_category = str(input_params.get("target_category", "Display & Touch Screens")) discounted_price = current_price * (1.0 - discount_pct / 100.0) # 2. Historical Baseline baseline = fetch_historical_baseline("pricing_elasticity", store_id) if heartbeat_callback: heartbeat_callback() # Check cancellation if cancellation_check and cancellation_check(): raise InterruptedError("Simulation cancelled by user.") # 3. Spawn 50 Personas personas = generate_personas(count=50, seed=42) agent_outcomes: List[float] = [] agent_logs: List[Dict[str, Any]] = [] # 4. Multi-agent evaluation loop arch_groups: Dict[str, List[AgentPersona]] = {} for p in personas: arch_groups.setdefault(p.archetype_id, []).append(p) # Mathematical decision heuristic per agent # Price drop increases willingness to buy proportional to price sensitivity price_attractiveness = (discount_pct / 100.0) * p.price_sensitivity * 1.8 # Excessive discounts trigger quality suspicion if quality priority is high quality_penalty = 0.0 if discount_pct > 30.0 and p.quality_priority > 0.7: quality_penalty = (discount_pct - 30.0) / 100.0 * p.quality_priority base_prob = baseline.empirical_mean agent_prob = max(0.01, min(0.95, base_prob + price_attractiveness - quality_penalty)) agent_outcomes.append(agent_prob) agent_logs.append({ "agent_id": p.agent_id, "archetype": p.archetype_name, "device": p.device_model, "price_sensitivity": p.price_sensitivity, "simulated_purchase_prob": round(agent_prob, 3), "decision": "PURCHASE" if agent_prob > 0.40 else "ABANDON" }) if heartbeat_callback: heartbeat_callback() # 5. Measure model dispersion and calibrated projection dispersion = compute_simulation_dispersion(agent_outcomes) projection = synthesize_calibrated_projection(baseline, dispersion) # 6. LLM Provider for qualitative archetype synthesis provider = get_llm_provider() archetype_breakdown = [] interview_samples = [] total_prompt_tokens = 0 total_completion_tokens = 0 total_cost = 0.0 async def _eval_archetype(arch_id: str, p_list: List[AgentPersona]): avg_prob = sum( next(log["simulated_purchase_prob"] for log in agent_logs if log["agent_id"] == p.agent_id) for p in p_list ) / max(1, len(p_list)) prompt = ( f"You are evaluating customer behavior for archetype '{p_list[0].archetype_name}' in iFixKart.\n" f"Scenario: A {discount_pct}% discount on {target_category} (Original: Rs {current_price}, Discounted: Rs {discounted_price}).\n" f"Simulated average purchase rate: {avg_prob:.2%}.\n" f"Generate the primary friction point and a realistic 1-sentence quote explaining why this persona bought or abandoned." ) try: reasoning, usage = await provider.generate_structured( prompt=prompt, schema=ArchetypeReasoningSchema, system_prompt="You are a behavioral economics analyst specializing in electronics repair commerce." ) return { "breakdown": { "name": p_list[0].archetype_name, "share": f"{len(p_list)/len(personas):.0%}", "rate": f"{avg_prob:.1%}", "friction": reasoning.primary_friction }, "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"{avg_prob:.1%}", "friction": "Balancing cost savings against OEM screen durability." }, "sample": { "persona": f"{p_list[0].archetype_name} ({p_list[0].name})", "quote": f"At Rs {discounted_price:.0f}, the deal is tempting, but I want to be sure it has a 6-month warranty." }, "usage": None } results = await asyncio.gather(*(_eval_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 # 7. Financial Elasticity Metrics baseline_margin_per_unit = current_price - cost_price discounted_margin_per_unit = discounted_price - cost_price # Volume multiplier based on projection delta volume_multiplier = 1.0 + (projection.simulated_directional_delta_pct / 100.0) baseline_profit = 100 * baseline_margin_per_unit projected_profit = 100 * volume_multiplier * discounted_margin_per_unit profit_delta_pct = ((projected_profit - baseline_profit) / baseline_profit) * 100.0 if baseline_profit > 0 else 0.0 # Elasticity coefficient = % change in quantity / % change in price price_change_pct = discount_pct quantity_change_pct = projection.simulated_directional_delta_pct elasticity_coef = abs(quantity_change_pct / price_change_pct) if price_change_pct > 0 else 1.0 summary_metrics = { "discount_pct": discount_pct, "original_price": current_price, "discounted_price": discounted_price, "cost_price": cost_price, "baseline_conversion_pct": round(baseline.empirical_mean * 100.0, 2), "projected_conversion_pct": round(projection.calibrated_projected_value * 100.0, 2), "projected_volume_multiplier": round(volume_multiplier, 3), "unit_margin_reduction_pct": round((1.0 - discounted_margin_per_unit / baseline_margin_per_unit) * 100.0, 2), "net_gross_profit_delta_pct": round(profit_delta_pct, 2), "price_elasticity_coefficient": round(elasticity_coef, 2), "elasticity_verdict": "ELASTIC (Volume offsets margin)" if elasticity_coef > 1.0 else "INELASTIC (Margin cannibalization)" } # 8. Render Markdown Report elapsed_ms = int((time.perf_counter() - start_time) * 1000) telemetry = { "formatted_inputs": json.dumps(input_params, indent=2), "recommendation_summary": ( f"Elasticity coefficient is {elasticity_coef:.2f}. " f"{'Volume expansion exceeds unit margin decline.' if elasticity_coef > 1.0 else 'Warning: Gross profit will drop by ' + f'{abs(profit_delta_pct):.1f}% despite higher volume. Consider bundling free tempered glass instead of cash discounts.'}" ), "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="pricing_elasticity", scenario_title=f"Discount Elasticity Analysis ({discount_pct}% on {target_category})", input_params=input_params, baseline=baseline, dispersion=dispersion, projection=projection, archetype_breakdown=archetype_breakdown, interview_samples=interview_samples, telemetry=telemetry ) return ScenarioResult( scenario_type="pricing_elasticity", scenario_title=f"Discount Elasticity ({discount_pct}%)", 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) )