Spaces:
Sleeping
Sleeping
File size: 29,546 Bytes
f844095 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 |
"""
Policy Impact Simulator Chat Integration
Provides natural language interface for policy impact simulation
"""
import re
import json
import logging
from typing import Dict, Any, Optional, List
from datetime import datetime, timedelta
from dataclasses import dataclass
from policy_impact_simulator import (
PolicyImpactSimulator,
PolicyScenario,
PolicyParameter
)
from policy_chart_generator import PolicyChartGenerator
logger = logging.getLogger(__name__)
@dataclass
class PolicyQuery:
"""Parsed policy query from natural language"""
intent: str
parameter: Optional[PolicyParameter]
current_value: Optional[float]
proposed_value: Optional[float]
years: int = 5
raw_query: str = ""
class PolicySimulatorChatInterface:
"""Chat interface for policy impact simulation"""
def __init__(self):
self.simulator = PolicyImpactSimulator()
self.chart_generator = PolicyChartGenerator()
self.conversation_context = {}
# Enhanced pattern matching for natural language queries
self.patterns = {
"simulate_dr": [
r"simulate.*dearness.*relief.*(\d+).*to.*(\d+)",
r"dr.*increase.*from.*(\d+).*to.*(\d+)",
r"what.*if.*dr.*changes.*(\d+).*(\d+)",
r"impact.*dearness.*(\d+).*percent.*(\d+).*percent",
r"dr.*analysis.*(\d+).*(\d+)",
r"dearness.*relief.*(\d+).*(\d+)",
r"impact.*increasing.*dr.*by.*(\d+)",
r"show.*impact.*dr.*by.*(\d+)",
r"dr.*increase.*by.*(\d+).*percent",
r"increase.*dr.*by.*(\d+)"
],
"simulate_pension": [
r"simulate.*basic.*pension.*(\d+).*to.*(\d+)",
r"pension.*increase.*from.*(\d+).*to.*(\d+)",
r"what.*if.*pension.*changes.*(\d+).*(\d+)",
r"impact.*basic.*pension.*(\d+).*(\d+)",
r"pension.*boost.*(\d+).*(\d+)",
r"basic.*pension.*(\d+).*(\d+)",
r"analyze.*minimum.*pension.*changes",
r"analyze.*basic.*pension",
r"minimum.*pension.*analysis",
r"basic.*pension.*impact"
],
"simulate_medical": [
r"simulate.*medical.*allowance.*(\d+).*to.*(\d+)",
r"medical.*increase.*from.*(\d+).*to.*(\d+)",
r"what.*if.*medical.*changes.*(\d+).*(\d+)",
r"medical.*allowance.*(\d+).*(\d+)"
],
"scenario_analysis": [
r"scenario.*analysis.*pension",
r"do.*scenario.*analysis",
r"pension.*scenario.*analysis",
r"analyze.*pension.*scenarios",
r"scenario.*analysis.*dr",
r"pension.*rules.*scenario",
r"government.*policy.*scenario",
r"policy.*scenario.*analysis"
],
"interactive_form": [
r"start.*scenario.*analysis",
r"interactive.*scenario",
r"step.*by.*step.*analysis",
r"guided.*analysis",
r"scenario.*form"
],
"general_policy": [
r"policy.*impact.*simulation",
r"simulate.*policy.*change",
r"what.*if.*we.*change",
r"impact.*analysis.*policy",
r"policy.*analysis",
r"government.*policy.*impact"
],
"compare_scenarios": [
r"compare.*scenarios",
r"which.*is.*better.*policy",
r"cost.*comparison.*policies",
r"scenario.*comparison",
r"best.*case.*worst.*case"
]
}
def process_policy_query(self, query: str, user_id: str = "default") -> Dict[str, Any]:
"""
Process natural language policy query and return simulation results
"""
try:
# Parse the query
parsed_query = self._parse_policy_query(query)
if not parsed_query:
return self._get_help_response()
# Handle different intents
if parsed_query.intent == "simulate":
return self._handle_simulation_request(parsed_query, user_id)
elif parsed_query.intent == "compare":
return self._handle_comparison_request(parsed_query, user_id)
elif parsed_query.intent == "help":
return self._get_help_response()
elif parsed_query.intent == "scenario_analysis":
return self._handle_scenario_analysis_request(parsed_query, user_id)
elif parsed_query.intent == "interactive_form":
return self._start_interactive_form(user_id)
else:
return self._get_clarification_response(query)
except Exception as e:
logger.error(f"Policy query processing error: {e}")
return {
"type": "error",
"message": f"Sorry, I encountered an error processing your policy query: {str(e)}",
"suggestions": ["Try rephrasing your question", "Use specific numbers and policy parameters"]
}
def _parse_policy_query(self, query: str) -> Optional[PolicyQuery]:
"""Parse natural language query into structured policy query"""
query_lower = query.lower()
# Check for explicit help requests (more specific to avoid false positives)
help_patterns = [r"^help", r"how.*do.*i", r"what.*can.*you", r"guide.*me", r"need.*help"]
if any(re.search(pattern, query_lower) for pattern in help_patterns):
return PolicyQuery(intent="help", parameter=None, current_value=None, proposed_value=None, raw_query=query)
# Check for comparison requests
if any(word in query_lower for word in ["compare", "vs", "versus", "which is better"]):
return PolicyQuery(intent="compare", parameter=None, current_value=None, proposed_value=None, raw_query=query)
# Try to match simulation patterns
for intent, patterns in self.patterns.items():
for pattern in patterns:
match = re.search(pattern, query_lower)
if match:
return self._extract_simulation_params(intent, match, query)
# Check for general policy simulation intent
if any(word in query_lower for word in ["simulate", "impact", "policy", "change", "effect"]):
return PolicyQuery(intent="simulate", parameter=None, current_value=None, proposed_value=None, raw_query=query)
return None
def _extract_simulation_params(self, intent: str, match, raw_query: str) -> PolicyQuery:
"""Extract simulation parameters from regex match"""
try:
# Handle new intent types that don't need parameter extraction
if intent in ["scenario_analysis", "interactive_form"]:
return PolicyQuery(
intent=intent,
parameter=None,
current_value=None,
proposed_value=None,
raw_query=raw_query
)
groups = match.groups()
# Map intent to parameter for simulation intents
parameter_mapping = {
"simulate_dr": PolicyParameter.DEARNESS_RELIEF,
"simulate_pension": PolicyParameter.BASIC_PENSION,
"simulate_medical": PolicyParameter.MEDICAL_ALLOWANCE
}
parameter = parameter_mapping.get(intent, PolicyParameter.DEARNESS_RELIEF)
# Handle different pattern types
if len(groups) == 0:
# No numbers - provide default analysis scenario
if parameter == PolicyParameter.DEARNESS_RELIEF:
current_value = 12.0 # Current DR is 12%
proposed_value = 18.0 # Standard 6% increase
elif parameter == PolicyParameter.BASIC_PENSION:
current_value = 6000.0 # Current basic pension is βΉ6,000
proposed_value = 8000.0 # Standard βΉ2,000 increase
elif parameter == PolicyParameter.MEDICAL_ALLOWANCE:
current_value = 1000.0 # Current medical allowance is βΉ1,000
proposed_value = 1500.0 # Standard βΉ500 increase
else:
current_value = 0.0
proposed_value = 1.0
elif len(groups) == 1:
# Single number - treat as percentage increase
increase_amount = float(groups[0])
# Set current values based on parameter type
if parameter == PolicyParameter.DEARNESS_RELIEF:
current_value = 12.0 # Current DR is 12%
proposed_value = current_value + increase_amount
elif parameter == PolicyParameter.BASIC_PENSION:
current_value = 6000.0 # Current basic pension is βΉ6,000
proposed_value = current_value + increase_amount
elif parameter == PolicyParameter.MEDICAL_ALLOWANCE:
current_value = 1000.0 # Current medical allowance is βΉ1,000
proposed_value = current_value + increase_amount
else:
current_value = increase_amount
proposed_value = increase_amount * 1.5 # Default 50% increase
else:
# Two numbers - from X to Y
current_value = float(groups[0]) if len(groups) > 0 else None
proposed_value = float(groups[1]) if len(groups) > 1 else None
# Extract years if mentioned
years_match = re.search(r"(\d+).*years?", raw_query.lower())
years = int(years_match.group(1)) if years_match else 5
return PolicyQuery(
intent="simulate",
parameter=parameter,
current_value=current_value,
proposed_value=proposed_value,
years=min(years, 10), # Cap at 10 years
raw_query=raw_query
)
except Exception as e:
logger.error(f"Parameter extraction error: {e}")
return PolicyQuery(intent="simulate", parameter=None, current_value=None, proposed_value=None, raw_query=raw_query)
def _handle_simulation_request(self, parsed_query: PolicyQuery, user_id: str) -> Dict[str, Any]:
"""Handle policy simulation request"""
try:
# If missing parameters, provide clarification with specific guidance
if not all([parsed_query.parameter, parsed_query.current_value, parsed_query.proposed_value]):
return self._get_clarification_response(parsed_query.raw_query)
# Create scenario
scenario = PolicyScenario(
parameter=parsed_query.parameter,
current_value=parsed_query.current_value,
proposed_value=parsed_query.proposed_value,
effective_date=datetime.now() + timedelta(days=90), # 3 months from now
affected_population=self._estimate_affected_population(parsed_query.parameter),
annual_growth_rate=0.03,
inflation_rate=0.06
)
# Run simulation
result = self.simulator.simulate_policy_impact(scenario, parsed_query.years, True)
# Format for chat response
return self._format_simulation_response(result, parsed_query)
except Exception as e:
logger.error(f"Simulation request error: {e}")
return {
"type": "error",
"message": f"Simulation failed: {str(e)}",
"raw_query": parsed_query.raw_query
}
def _estimate_affected_population(self, parameter: PolicyParameter) -> int:
"""Estimate affected population based on parameter type"""
population_estimates = {
PolicyParameter.DEARNESS_RELIEF: 510000, # All pensioners
PolicyParameter.BASIC_PENSION: 450000, # Basic pension recipients
PolicyParameter.MEDICAL_ALLOWANCE: 510000, # All pensioners
PolicyParameter.PENSION_FACTOR: 510000,
PolicyParameter.MINIMUM_PENSION: 200000 # Lower income pensioners
}
return population_estimates.get(parameter, 400000)
def _format_simulation_response(self, result: Dict[str, Any], query: PolicyQuery) -> Dict[str, Any]:
"""Format simulation results for chat display"""
if "error" in result:
return {
"type": "error",
"message": f"Simulation error: {result['error']}"
}
total_impact = result.get("total_impact", {})
projections = result.get("scenario_projections", [])
clause_analysis = result.get("clause_analysis", {})
# Create summary message
summary = f"""
π― **Policy Impact Simulation Results**
**Parameter**: {result.get('parameter_name', 'Unknown')}
**Change**: {result.get('current_value')} β {result.get('proposed_value')}
**Effective Date**: {result.get('effective_date', '').split('T')[0]}
π **Financial Impact Over {result.get('projection_years')} Years**:
β’ **Total Additional Cost**: βΉ{total_impact.get('total_additional_cost_crores', 0):.1f} crores
β’ **Percentage Increase**: {total_impact.get('percentage_increase', 0):.1f}%
β’ **Annual Average**: βΉ{total_impact.get('annual_average_impact_crores', 0):.1f} crores
β’ **Cost per Beneficiary**: βΉ{total_impact.get('cost_per_beneficiary_annual', 0):,.0f} per year
π **Year-by-Year Breakdown**:
"""
# Add yearly breakdown
for i, proj in enumerate(projections[:3]): # Show first 3 years
summary += f"Year {proj.year}: βΉ{proj.impact/10000000:.1f} crores impact ({proj.affected_beneficiaries:,} beneficiaries)\n"
if len(projections) > 3:
summary += f"... and {len(projections)-3} more years\n"
# Add clause information
if clause_analysis:
clause_diff = clause_analysis.get("clause_diff", {})
summary += f"""
βοΈ **Policy Changes**:
β’ **Change Type**: {clause_diff.get('change_type', 'Unknown').title()}
β’ **Magnitude**: {clause_diff.get('change_percentage', 0):.1f}% change
β’ **Affected Clauses**: {len(clause_analysis.get('affected_clauses', []))} clauses modified
"""
# Add scenario variants
variants = result.get("variants", {})
charts = []
if variants:
best_case = sum(p.impact for p in variants.get("best_case", [])) / 10000000
worst_case = sum(p.impact for p in variants.get("worst_case", [])) / 10000000
base_case = total_impact.get('total_additional_cost_crores', 0)
summary += f"""
π **Scenario Analysis**:
β’ **Best Case**: βΉ{best_case:.1f} crores
β’ **Base Case**: βΉ{base_case:.1f} crores
β’ **Worst Case**: βΉ{worst_case:.1f} crores
"""
# Generate charts
try:
# Scenario comparison chart
scenario_data = {
'best_case': {'total_cost': best_case},
'base_case': {'total_cost': base_case},
'worst_case': {'total_cost': worst_case}
}
chart_title = f"{result.get('parameter_name', 'Policy')} Impact Analysis"
scenario_chart = self.chart_generator.generate_scenario_comparison_chart(
scenario_data, chart_title
)
if scenario_chart:
charts.append({
"type": "scenario_comparison",
"title": chart_title,
"data": scenario_chart
})
# Year-by-year breakdown chart
if projections:
# Convert projections to the format expected by chart generator
yearly_data = []
for proj in projections:
yearly_data.append({
'year': proj.year,
'impact': proj.impact / 10000000, # Convert to crores
'beneficiaries': proj.affected_beneficiaries
})
trend_chart = self.chart_generator.generate_yearly_breakdown_chart(
yearly_data, f"{result.get('parameter_name', 'Policy')} 5-Year Impact"
)
if trend_chart:
charts.append({
"type": "yearly_trend",
"title": "5-Year Financial Impact Trend",
"data": trend_chart
})
except Exception as e:
logger.error(f"Chart generation error: {e}")
return {
"type": "policy_simulation",
"message": summary,
"simulation_id": result.get("scenario_id"),
"detailed_results": result,
"charts": charts,
"export_options": ["CSV", "PDF", "JSON"],
"follow_up_suggestions": [
"Compare with other policy scenarios",
"Analyze implementation timeline",
"Export detailed evidence pack",
"Simulate different effective dates"
]
}
def _get_interactive_form(self, parsed_query: PolicyQuery) -> Dict[str, Any]:
"""Provide interactive form for missing parameters"""
available_parameters = [
{"id": "dearness_relief", "name": "Dearness Relief (%)", "current": 12.0, "unit": "%"},
{"id": "basic_pension", "name": "Basic Pension (βΉ)", "current": 6000, "unit": "βΉ"},
{"id": "medical_allowance", "name": "Medical Allowance (βΉ)", "current": 1000, "unit": "βΉ"},
{"id": "pension_factor", "name": "Pension Factor", "current": 1.0, "unit": "multiplier"},
{"id": "minimum_pension", "name": "Minimum Pension (βΉ)", "current": 3500, "unit": "βΉ"}
]
return {
"type": "interactive_form",
"message": "I'd be happy to help you simulate policy impact! Please provide the following details:",
"form_fields": [
{
"name": "parameter",
"label": "Policy Parameter",
"type": "select",
"options": available_parameters,
"required": True
},
{
"name": "current_value",
"label": "Current Value",
"type": "number",
"required": True
},
{
"name": "proposed_value",
"label": "Proposed Value",
"type": "number",
"required": True
},
{
"name": "years",
"label": "Projection Years",
"type": "number",
"default": 5,
"min": 1,
"max": 10
}
],
"examples": [
"Simulate DR increase from 12% to 18% over 5 years",
"What if basic pension changes from βΉ6000 to βΉ8000?",
"Impact of medical allowance increase to βΉ2000"
]
}
def _handle_comparison_request(self, parsed_query: PolicyQuery, user_id: str) -> Dict[str, Any]:
"""Handle policy comparison request"""
sample_comparisons = [
{
"name": "DR vs Basic Pension Increase",
"scenarios": [
{"parameter": "DR", "change": "12% β 18%", "impact": "βΉ85.2 crores"},
{"parameter": "Basic Pension", "change": "βΉ6000 β βΉ8000", "impact": "βΉ108.0 crores"}
],
"recommendation": "DR increase is more cost-effective"
},
{
"name": "Short vs Long Term Impact",
"scenarios": [
{"period": "3 years", "total_impact": "βΉ150.5 crores"},
{"period": "10 years", "total_impact": "βΉ628.3 crores"}
],
"recommendation": "Long-term planning essential"
}
]
return {
"type": "policy_comparison",
"message": "Here are some policy comparison examples. Would you like to compare specific scenarios?",
"comparisons": sample_comparisons,
"custom_comparison": {
"description": "I can help you compare up to 5 different policy scenarios",
"example": "Compare DR increase vs pension boost vs medical allowance increase"
}
}
def _get_help_response(self) -> Dict[str, Any]:
"""Provide help information"""
return {
"type": "help",
"message": """
π― **Policy Impact Simulator Help**
I can help you simulate the financial impact of government policy changes. Here's what I can do:
**π Simulation Capabilities**:
β’ Dearness Relief (DR) changes
β’ Basic pension adjustments
β’ Medical allowance modifications
β’ Pension factor changes
β’ Minimum pension guarantees
**π¬ How to Ask**:
β’ "Simulate DR increase from 12% to 18%"
β’ "What if basic pension changes from βΉ6000 to βΉ8000?"
β’ "Impact of medical allowance increase to βΉ2000 over 5 years"
β’ "Compare DR increase vs pension boost"
**π What You Get**:
β’ Total financial impact over 3-10 years
β’ Year-by-year breakdown
β’ Best/base/worst case scenarios
β’ Affected population estimates
β’ Policy clause analysis
β’ Implementation timeline
β’ Exportable evidence pack
**π Quick Examples**:
Try asking: "Show me the impact of increasing DR by 6%"
""",
"quick_actions": [
{"label": "Sample DR Simulation", "query": "simulate DR from 12 to 18 percent"},
{"label": "Basic Pension Impact", "query": "what if basic pension increases to 8000"},
{"label": "Compare Scenarios", "query": "compare policy scenarios"},
{"label": "View Parameters", "query": "show available policy parameters"}
]
}
def _get_clarification_response(self, query: str) -> Dict[str, Any]:
"""Request clarification for unclear queries"""
# Provide specific guidance based on the query content
query_lower = query.lower()
if "da" in query_lower or "dearness allowance" in query_lower or "dr" in query_lower:
specific_message = """π― **DA/DR Impact Analysis**
I can help you analyze the Dearness Allowance (DA) impact! To provide accurate calculations, please specify:
π **Required Details:**
β’ **Current DA Rate**: What's the existing DA percentage? (e.g., 12%)
β’ **Proposed DA Rate**: What should the new DA be? (e.g., 18% for a 6% increase)
β’ **Base Pension Amount**: What's the basic pension amount? (e.g., βΉ6,000)
β’ **Analysis Period**: How many years to analyze? (default: 5 years)
π‘ **Quick Examples:**
β’ "Show DA impact from 12% to 18% for pension βΉ6000"
β’ "Analyze 6% DA increase from current 12% to 18%"
β’ "DA simulation: current 12%, increase to 18%, basic pension βΉ6000"
π **What You'll Get:**
β’ Financial impact over 5 years with charts
β’ Cost per beneficiary calculations
β’ Best/Base/Worst case scenarios
β’ Implementation timeline and evidence pack"""
elif "pension" in query_lower and ("basic" in query_lower or "minimum" in query_lower):
specific_message = """π― **Basic Pension Impact Analysis**
I can help analyze basic pension changes! Please provide:
π **Required Details:**
β’ **Current Basic Pension**: What's the existing amount? (e.g., βΉ6,000)
β’ **Proposed Basic Pension**: What should the new amount be? (e.g., βΉ8,000)
β’ **Analysis Period**: How many years to analyze? (default: 5 years)
π‘ **Quick Examples:**
β’ "Show basic pension impact from βΉ6000 to βΉ8000"
β’ "Analyze pension increase to βΉ8000 over 5 years"
β’ "Basic pension simulation: current βΉ6000, increase to βΉ8000"
π **What You'll Get:**
β’ Financial impact projections with charts
β’ Affected population estimates
β’ Cost analysis and implementation timeline"""
else:
specific_message = """π― **Policy Impact Simulation Help**
I understand you want to analyze policy impact! To provide accurate calculations, please specify:
π **Choose Your Analysis:**
β’ **DA/DR Changes**: Dearness Allowance adjustments (e.g., "DA from 12% to 18%")
β’ **Basic Pension**: Minimum pension amount changes (e.g., "Pension from βΉ6000 to βΉ8000")
β’ **Medical Allowance**: Healthcare support changes (e.g., "Medical allowance to βΉ1500")
π‘ **Format Your Request:**
Include: Current value β Proposed value β Base amount (if applicable)
π **Quick Examples:**
β’ "Show DA impact from 12% to 18% for pension βΉ6000"
β’ "Analyze basic pension increase from βΉ6000 to βΉ8000"
β’ "Medical allowance impact from βΉ1000 to βΉ1500" """
return {
"type": "clarification",
"message": specific_message,
"original_query": query,
"suggestions": [
"π Use the format: 'Show [policy] impact from [current] to [proposed]'",
"π Include specific numbers and amounts",
"β±οΈ Specify time period if different from 5 years"
],
"quick_actions": [
{"text": "π DA Analysis Example", "query": "Show DA impact from 12% to 18% for pension βΉ6000"},
{"text": "π° Pension Analysis Example", "query": "Show basic pension impact from βΉ6000 to βΉ8000"},
{"text": "π Start Interactive Form", "query": "start scenario analysis"}
]
}
def _handle_scenario_analysis_request(self, parsed_query: PolicyQuery, user_id: str) -> Dict[str, Any]:
"""Handle general scenario analysis requests"""
return {
"type": "scenario_analysis_help",
"message": """π― **Scenario Analysis for Rajasthan Pension Policies**
I can help you analyze different scenarios for pension policy changes. Here are the most common analyses:
π **Available Scenario Analyses:**
β’ **Dearness Relief (DR)**: Analyze inflation adjustments (current: 12%)
β’ **Basic Pension**: Analyze minimum pension changes (current: βΉ6,000)
β’ **Medical Allowance**: Analyze healthcare support changes (current: βΉ1,000)
β’ **Pension Factor**: Analyze salary multiplier changes (current: 1.0x)
π¬ **How to Request Analysis:**
β’ "Simulate DR increase from 12% to 18% over 5 years"
β’ "What if basic pension increases to βΉ8,000?"
β’ "Compare best and worst case scenarios for medical allowance"
π **What You'll Get:**
β’ Financial impact projections (3-10 years)
β’ Best/Base/Worst case scenarios
β’ Affected population estimates
β’ Implementation timeline and complexity
β’ Exportable evidence packs
π **Try These Examples:**""",
"quick_actions": [
{"text": "π Analyze DR Scenarios", "query": "Show DR scenario analysis from 12% to 18%"},
{"text": "π° Analyze Pension Scenarios", "query": "Show basic pension scenarios from 6000 to 8000"},
{"text": "π₯ Analyze Medical Allowance", "query": "Show medical allowance scenarios"},
{"text": "π Start Interactive Form", "query": "start scenario analysis"}
]
}
def _start_interactive_form(self, user_id: str) -> Dict[str, Any]:
"""Start interactive scenario analysis form"""
try:
from scenario_chat_form import start_scenario_analysis_form
return start_scenario_analysis_form(user_id)
except Exception as e:
logger.error(f"Interactive form start failed: {e}")
return {
"type": "error",
"message": "Sorry, I couldn't start the interactive form. Let me help you with a quick simulation instead.",
"fallback_form": self._get_clarification_response("")
}
# Usage integration function
def process_policy_chat_query(query: str, user_id: str = "default") -> Dict[str, Any]:
"""
Main function to process policy-related chat queries
Use this in your main chat system
"""
interface = PolicySimulatorChatInterface()
return interface.process_policy_query(query, user_id)
|