Yaswanth-Bolla commited on
Commit
e118e76
·
1 Parent(s): 17ed4d3

Updated teh format to meet requirements

Browse files
Files changed (2) hide show
  1. README.md +384 -39
  2. app.py +260 -140
README.md CHANGED
@@ -138,33 +138,60 @@ Provides mitigation strategies and revised risk assessments for identified threa
138
 
139
  **Request Body**:
140
  ```json
141
- [
142
- {
143
- "enablerType": "Technology",
144
- "enablerDomain": "Hardware",
145
- "majorCategory": "Fire",
146
- "mappedThreat": "Fire at HQ",
147
- "existingControls": "Data centre equipped with handheld fire extinguishers",
148
- "complianceStatus": "Yes, inspected monthly and tagged",
149
- "impact": "4",
150
- "likelihood": "3",
151
- "riskValue": "12"
152
- }
153
- ]
 
154
  ```
155
 
156
  **Response**:
157
  ```json
158
  {
159
- "mitigatedRisks": [
160
- {
161
- "revisedImpact": 2,
162
- "revisedLikelihood": 2,
163
- "revisedRiskValue": 4,
164
- "mitigationPlan": " Install fire suppression systems • Conduct quarterly training • Implement monitoring alerts",
165
- "ownership": "Facilities Management Team"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  }
167
- ]
168
  }
169
  ```
170
 
@@ -327,36 +354,354 @@ curl -X POST "http://localhost:8000/api/generate-threats" \
327
  ```bash
328
  curl -X POST "http://localhost:8000/api/risk-mitigation" \
329
  -H "Content-Type: application/json" \
330
- -d '[
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
331
  {
332
- "enablerType": "Process",
333
- "enablerDomain": "Information Security",
334
- "majorCategory": "Cyber Security",
335
- "mappedThreat": "Ransomware Attack",
336
- "existingControls": "Antivirus software and email filtering",
337
- "complianceStatus": "Partially compliant - needs updates",
338
- "impact": "5",
339
- "likelihood": "4",
340
- "riskValue": "20"
341
  }
342
- ]'
 
343
  ```
344
 
345
- **Response**:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
346
  ```json
347
  {
348
- "mitigatedRisks": [
349
  {
350
- "revisedImpact": 3,
351
- "revisedLikelihood": 2,
352
- "revisedRiskValue": 6,
353
- "mitigationPlan": "• Deploy endpoint detection response systems • Implement network segmentation controls • Conduct regular penetration testing",
354
- "ownership": "Information Security Team"
355
  }
356
  ]
357
  }
358
  ```
359
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
360
  ## 🚨 Error Handling
361
 
362
  ### Common Error Responses
 
138
 
139
  **Request Body**:
140
  ```json
141
+ {
142
+ "responses": [
143
+ {
144
+ "category": "Fire",
145
+ "question": "Is the data centre equipped with an appropriate fire suppression system?",
146
+ "user_answer": "We only have a few handheld fire extinguishers, and there's no automated system."
147
+ },
148
+ {
149
+ "category": "Cybercrime",
150
+ "question": "Is there a well-documented and tested incident response plan?",
151
+ "user_answer": "There is a response plan but it hasn't been tested in the last 2 years."
152
+ }
153
+ ]
154
+ }
155
  ```
156
 
157
  **Response**:
158
  ```json
159
  {
160
+ "risk_analysis": {
161
+ "risk_id": "RISK-001",
162
+ "category": "Fire",
163
+ "question": "Is the data centre equipped with an appropriate fire suppression system?",
164
+ "user_answer": "We only have a few handheld fire extinguishers, and there's no automated system.",
165
+ "risk_name": "Absence of automated fire suppression system",
166
+ "identified_threat": "Increased risk of fire damage and personnel danger due to lack of automatic suppression systems.",
167
+ "likelihood": "High",
168
+ "impact": "Severe",
169
+ "risk_value": 9,
170
+ "residual_risk": "Critical",
171
+ "current_control_description": "Only basic handheld extinguishers are available; no active fire suppression in place.",
172
+ "current_control_rating": "Poor",
173
+ "business_unit": "Facilities",
174
+ "risk_owner": "Fire Safety Officer",
175
+ "timeline": "Immediate",
176
+ "mitigation_plan": "Install automated suppression systems like FM200 or Inergen and integrate with fire alarms.",
177
+ "summary": {
178
+ "risk_classification_summary": "This is a critical fire safety risk with a high likelihood and severe impact. It requires immediate action.",
179
+ "mitigation_suggestions": [
180
+ "Deploy automated gas-based fire suppression systems.",
181
+ "Conduct fire safety training and drills.",
182
+ "Regularly inspect and maintain suppression systems."
183
+ ],
184
+ "risk_trends": {
185
+ "top_category": "Fire",
186
+ "risk_severity": "Critical",
187
+ "observations": [
188
+ "Many facilities lack automated fire suppression.",
189
+ "High fire risks stem from outdated or manual systems.",
190
+ "Immediate remediation is crucial to prevent major incidents."
191
+ ]
192
+ }
193
  }
194
+ }
195
  }
196
  ```
197
 
 
354
  ```bash
355
  curl -X POST "http://localhost:8000/api/risk-mitigation" \
356
  -H "Content-Type: application/json" \
357
+ -d '{
358
+ "responses": [
359
+ {
360
+ "category": "Cybercrime",
361
+ "question": "Is there a well-documented and tested incident response plan?",
362
+ "user_answer": "There is a response plan but it hasn't been tested in the last 2 years."
363
+ }
364
+ ]
365
+ }'
366
+ ```
367
+
368
+ **Response**:
369
+ ```json
370
+ {
371
+ "risk_analysis": {
372
+ "risk_id": "RISK-002",
373
+ "category": "Cybercrime",
374
+ "question": "Is there a well-documented and tested incident response plan?",
375
+ "user_answer": "There is a response plan but it hasn't been tested in the last 2 years.",
376
+ "risk_name": "Outdated incident response planning",
377
+ "identified_threat": "Delayed or ineffective response to cyber incidents due to outdated procedures",
378
+ "likelihood": "High",
379
+ "impact": "Severe",
380
+ "risk_value": 8,
381
+ "residual_risk": "High",
382
+ "current_control_description": "Outdated incident response plan without recent testing",
383
+ "current_control_rating": "Poor",
384
+ "business_unit": "Information Technology",
385
+ "risk_owner": "CISO",
386
+ "timeline": "Immediate",
387
+ "mitigation_plan": "Update incident response plan, conduct regular testing, and implement automated threat detection",
388
+ "summary": {
389
+ "risk_classification_summary": "High-risk cybersecurity vulnerability requiring prompt remediation",
390
+ "mitigation_suggestions": [
391
+ "Update and test incident response plan quarterly",
392
+ "Implement automated threat detection systems",
393
+ "Conduct regular cybersecurity training"
394
+ ],
395
+ "risk_trends": {
396
+ "top_category": "Cybercrime",
397
+ "risk_severity": "High",
398
+ "observations": [
399
+ "Incident response plans are outdated across organization",
400
+ "Limited testing reduces effectiveness of responses",
401
+ "Regular plan updates and testing are essential"
402
+ ]
403
+ }
404
+ }
405
+ }
406
+ }
407
+ ```
408
+
409
+ ## 📮 Postman Setup Guide
410
+
411
+ ### Prerequisites
412
+ - Postman installed (download from [postman.com](https://www.postman.com/downloads/))
413
+ - API server running locally on `http://localhost:8000`
414
+
415
+ ### 1. Process Threat Generation Endpoint
416
+
417
+ **Create New Request:**
418
+ - **Method**: `POST`
419
+ - **URL**: `http://localhost:8000/api/generate-threats`
420
+ - **Name**: "Generate Process Threats"
421
+
422
+ **Headers:**
423
+ - **Key**: `Content-Type`
424
+ - **Value**: `application/json`
425
+
426
+ **Request Body (raw JSON):**
427
+ ```json
428
+ {
429
+ "processName": "Financial Transaction Processing",
430
+ "department": "Finance",
431
+ "description": "Handles all daily banking transactions and payment processing",
432
+ "owner": "John Smith",
433
+ "businessContext": "Critical for daily operations and customer payments",
434
+ "rto": "1hour",
435
+ "mtpd": "24hours",
436
+ "minTolerableDowntime": "15minutes"
437
+ }
438
+ ```
439
+
440
+ **Alternative Test Cases:**
441
+
442
+ *IT Infrastructure Process:*
443
+ ```json
444
+ {
445
+ "processName": "Email Server Management",
446
+ "department": "IT Operations",
447
+ "description": "Manages corporate email infrastructure and communications",
448
+ "owner": "IT Manager",
449
+ "businessContext": "Essential for internal and external communications",
450
+ "rto": "4hours",
451
+ "mtpd": "48hours",
452
+ "minTolerableDowntime": "1hour"
453
+ }
454
+ ```
455
+
456
+ *HR Process:*
457
+ ```json
458
+ {
459
+ "processName": "Payroll Processing",
460
+ "department": "Human Resources",
461
+ "description": "Monthly salary and benefits processing for all employees",
462
+ "owner": "Payroll Manager",
463
+ "businessContext": "Critical for employee satisfaction and legal compliance",
464
+ "rto": "8hours",
465
+ "mtpd": "72hours",
466
+ "minTolerableDowntime": "24hours"
467
+ }
468
+ ```
469
+
470
+ ### 2. Risk Mitigation Analysis Endpoint
471
+
472
+ **Create New Request:**
473
+ - **Method**: `POST`
474
+ - **URL**: `http://localhost:8000/api/risk-mitigation`
475
+ - **Name**: "Risk Mitigation Analysis"
476
+
477
+ **Headers:**
478
+ - **Key**: `Content-Type`
479
+ - **Value**: `application/json`
480
+
481
+ **Request Body (raw JSON):**
482
+ ```json
483
+ {
484
+ "responses": [
485
  {
486
+ "category": "Fire",
487
+ "question": "Is the data centre equipped with an appropriate fire suppression system?",
488
+ "user_answer": "We only have a few handheld fire extinguishers, and there's no automated system."
 
 
 
 
 
 
489
  }
490
+ ]
491
+ }
492
  ```
493
 
494
+ **Multiple Risk Questions Example:**
495
+ ```json
496
+ {
497
+ "responses": [
498
+ {
499
+ "category": "Fire",
500
+ "question": "Is the data centre equipped with an appropriate fire suppression system?",
501
+ "user_answer": "We only have a few handheld fire extinguishers, and there's no automated system."
502
+ },
503
+ {
504
+ "category": "Cybercrime",
505
+ "question": "Is there a well-documented and tested incident response plan?",
506
+ "user_answer": "There is a response plan but it hasn't been tested in the last 2 years."
507
+ }
508
+ ]
509
+ }
510
+ ```
511
+
512
+ **Additional Risk Categories Examples:**
513
  ```json
514
  {
515
+ "responses": [
516
  {
517
+ "category": "Physical Security",
518
+ "question": "Are there adequate access controls for all critical facilities?",
519
+ "user_answer": "We have basic card access but no multifactor authentication or visitor management."
 
 
520
  }
521
  ]
522
  }
523
  ```
524
 
525
+ ```json
526
+ {
527
+ "responses": [
528
+ {
529
+ "category": "Business Continuity",
530
+ "question": "Do you have tested backup systems for critical operations?",
531
+ "user_answer": "We have backups but testing is irregular and there's no formal recovery procedure documented."
532
+ }
533
+ ]
534
+ }
535
+ ```
536
+
537
+ ### 3. Geographic Threat Assessment Endpoint
538
+
539
+ **Create New Request:**
540
+ - **Method**: `POST`
541
+ - **URL**: `http://localhost:8000/bia/threat-assessment`
542
+ - **Name**: "Geographic Threat Assessment"
543
+
544
+ **Headers:**
545
+ - **Key**: `Content-Type`
546
+ - **Value**: `application/json`
547
+
548
+ **Request Body (raw JSON):**
549
+ ```json
550
+ {
551
+ "message": "Our company is planning to establish operations in Southeast Asia, specifically in Singapore and Bangkok."
552
+ }
553
+ ```
554
+
555
+ **Alternative Geographic Scenarios:**
556
+
557
+ *European Expansion:*
558
+ ```json
559
+ {
560
+ "message": "We are considering opening offices in Eastern Europe, particularly in Poland, Czech Republic, and Hungary for our manufacturing operations."
561
+ }
562
+ ```
563
+
564
+ *Middle East Assessment:*
565
+ ```json
566
+ {
567
+ "message": "Risk assessment needed for expanding our financial services into the Middle East, focusing on UAE, Saudi Arabia, and Qatar."
568
+ }
569
+ ```
570
+
571
+ *Latin America Supply Chain:*
572
+ ```json
573
+ {
574
+ "message": "Evaluating supply chain risks across Latin America including Mexico, Brazil, Argentina, and Colombia for our automotive parts business."
575
+ }
576
+ ```
577
+
578
+ *African Market Entry:*
579
+ ```json
580
+ {
581
+ "message": "Planning to enter African markets for telecommunications infrastructure, targeting South Africa, Nigeria, and Kenya."
582
+ }
583
+ ```
584
+
585
+ ### 4. Postman Collection Setup
586
+
587
+ **Create a Collection:**
588
+ 1. Click "New" → "Collection"
589
+ 2. Name: "EY Catalyst Risk Management API"
590
+ 3. Add all three requests to this collection
591
+
592
+ **Environment Variables:**
593
+ 1. Create environment: "EY Catalyst Local"
594
+ 2. Add variable:
595
+ - **Variable**: `base_url`
596
+ - **Initial Value**: `http://localhost:8000`
597
+ - **Current Value**: `http://localhost:8000`
598
+
599
+ **Update URLs to use environment:**
600
+ - Change URLs to: `{{base_url}}/api/generate-threats`
601
+ - Change URLs to: `{{base_url}}/api/risk-mitigation`
602
+ - Change URLs to: `{{base_url}}/bia/threat-assessment`
603
+
604
+ ### 5. Testing Workflow
605
+
606
+ **Recommended Testing Sequence:**
607
+
608
+ 1. **Start with Threat Generation:**
609
+ - Test with different business processes
610
+ - Verify threat categories and severity levels
611
+ - Note generated threat IDs for follow-up
612
+
613
+ 2. **Follow with Risk Mitigation:**
614
+ - Use threats from step 1 or create new risk scenarios
615
+ - Test single and multiple risk items
616
+ - Verify mitigation plans are actionable
617
+
618
+ 3. **Conclude with Geographic Assessment:**
619
+ - Test various global regions
620
+ - Compare risk profiles across locations
621
+ - Validate threat ratings and categories
622
+
623
+ ### 6. Expected Response Validation
624
+
625
+ **Threat Generation Response Structure:**
626
+ ```json
627
+ {
628
+ "threats": [
629
+ {
630
+ "id": 1,
631
+ "name": "string",
632
+ "description": "string",
633
+ "likelihood": 1-5,
634
+ "impact": 1-5,
635
+ "category": "string",
636
+ "mitigation": "string"
637
+ }
638
+ ]
639
+ }
640
+ ```
641
+
642
+ **Risk Mitigation Response Structure:**
643
+ ```json
644
+ {
645
+ "risk_analysis": {
646
+ "risk_id": "RISK-XXX",
647
+ "category": "string",
648
+ "question": "string",
649
+ "user_answer": "string",
650
+ "risk_name": "string",
651
+ "identified_threat": "string",
652
+ "likelihood": "string",
653
+ "impact": "string",
654
+ "risk_value": 1-10,
655
+ "residual_risk": "string",
656
+ "current_control_description": "string",
657
+ "current_control_rating": "string",
658
+ "business_unit": "string",
659
+ "risk_owner": "string",
660
+ "timeline": "string",
661
+ "mitigation_plan": "string",
662
+ "summary": {
663
+ "risk_classification_summary": "string",
664
+ "mitigation_suggestions": ["string", "string", "string"],
665
+ "risk_trends": {
666
+ "top_category": "string",
667
+ "risk_severity": "string",
668
+ "observations": ["string", "string", "string"]
669
+ }
670
+ }
671
+ }
672
+ }
673
+ ```
674
+
675
+ **Geographic Assessment Response Structure:**
676
+ ```json
677
+ {
678
+ "place": "string",
679
+ "threats": [
680
+ {
681
+ "name": "string",
682
+ "likelihood": 1-5,
683
+ "severity": 1-5,
684
+ "impact": "string",
685
+ "threat_rating": 1-25
686
+ }
687
+ ]
688
+ }
689
+ ```
690
+
691
+ ### 7. Troubleshooting
692
+
693
+ **Common Issues:**
694
+ - **Server not running**: Ensure `uvicorn app:app --reload` is active
695
+ - **Port conflicts**: Check if port 8000 is available
696
+ - **JSON validation errors**: Verify request body format
697
+ - **Missing headers**: Confirm `Content-Type: application/json`
698
+
699
+ **Success Indicators:**
700
+ - Status Code: `200 OK`
701
+ - Response contains expected JSON structure
702
+ - AI-generated content in responses
703
+ - Fallback responses when AI is unavailable
704
+
705
  ## 🚨 Error Handling
706
 
707
  ### Common Error Responses
app.py CHANGED
@@ -198,109 +198,122 @@ Respond strictly in this JSON format:
198
  result = generate_response(prompt, req.message)
199
  return result
200
 
201
- @app.post("/bia/impact-analysis")
202
- def bia_impact_analysis(req: Message):
203
- return {
204
- "status": "placeholder",
205
- "note": "This endpoint is reserved for BIA impact analysis logic."
206
- }
207
 
208
- class RiskItem(BaseModel):
209
- enablerType: str
210
- enablerDomain: str
211
- majorCategory: str
212
- mappedThreat: str
213
- existingControls: str
214
- complianceStatus: str
215
- impact: str
216
- likelihood: str
217
- riskValue: str
218
 
219
- class MitigationResponse(BaseModel):
220
- revisedImpact: int
221
- revisedLikelihood: int
222
- revisedRiskValue: int
223
- mitigationPlan: str
224
- ownership: str
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225
 
226
  class RiskMitigationResponse(BaseModel):
227
- mitigatedRisks: List[MitigationResponse]
228
 
229
  @app.post("/api/risk-mitigation", response_model=RiskMitigationResponse)
230
- def generate_risk_mitigation(risk_items: List[RiskItem]):
231
  """
232
- Generate mitigation plans and revised risk assessments for identified threats
233
  """
234
  system_prompt = """
235
- You are an expert risk management and business continuity analyst. Your task is to analyze existing risk items and provide comprehensive mitigation strategies that will reduce the overall risk.
236
-
237
- For each risk item provided, you need to:
238
- 1. Analyze the current risk assessment (impact, likelihood, risk value)
239
- 2. Evaluate existing controls and compliance status
240
- 3. Recommend additional mitigation measures
241
- 4. Provide revised risk ratings after implementing the mitigation plan
242
- 5. Assign appropriate ownership for the mitigation activities
243
-
244
- Consider:
245
- - Current controls effectiveness and compliance status
246
- - Industry best practices for the specific threat type
247
- - Cost-effective mitigation strategies
248
- - Realistic timeline for implementation
249
- - Appropriate ownership based on enabler type and domain
250
-
251
- For revised ratings:
252
- - Impact (1-5): Consider how mitigation reduces potential damage
253
- - Likelihood (1-5): Consider how mitigation reduces probability of occurrence
254
- - Risk Value: Calculate as revised impact × revised likelihood
255
-
256
- For mitigation plans:
257
- - Maximum 3 bullet points
258
- - Each point maximum 10 words
259
- - Be concise and actionable
260
-
261
- Respond strictly in this JSON format (no newlines within strings):
262
  {
263
- "mitigatedRisks": [
264
- {
265
- "revisedImpact": 2,
266
- "revisedLikelihood": 2,
267
- "revisedRiskValue": 4,
268
- "mitigationPlan": " Install fire suppression systems • Conduct quarterly training • Implement monitoring alerts",
269
- "ownership": "Responsible party/department"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270
  }
271
- ]
272
  }
273
  """
274
 
275
- # Format the risk items for the AI
276
- risk_data = []
277
- for i, item in enumerate(risk_items, 1):
278
- risk_data.append(f"""
279
- Risk Item {i}:
280
- - Enabler Type: {item.enablerType}
281
- - Enabler Domain: {item.enablerDomain}
282
- - Major Category: {item.majorCategory}
283
- - Mapped Threat: {item.mappedThreat}
284
- - Existing Controls: {item.existingControls}
285
- - Compliance Status: {item.complianceStatus}
286
- - Current Impact: {item.impact}
287
- - Current Likelihood: {item.likelihood}
288
- - Current Risk Value: {item.riskValue}
289
- """)
290
-
291
  user_message = f"""
292
- Please analyze the following risk items and provide mitigation strategies:
293
 
294
- {''.join(risk_data)}
 
 
295
 
296
- For each risk item, provide:
297
- 1. Revised impact rating (1-5) after implementing mitigation
298
- 2. Revised likelihood rating (1-5) after implementing mitigation
299
- 3. Revised risk value (impact × likelihood)
300
- 4. Concise mitigation plan (max 3 points, 10 words each)
301
- 5. Appropriate ownership assignment (department/role responsible)
302
-
303
- Consider the existing controls and compliance status when developing mitigation plans.
304
  """
305
 
306
  try:
@@ -314,8 +327,8 @@ Consider the existing controls and compliance status when developing mitigation
314
  json_str = result[json_start:json_end]
315
  # The AI returns properly formatted JSON with newlines, just parse it directly
316
  try:
317
- mitigation_data = json.loads(json_str)
318
- return RiskMitigationResponse(**mitigation_data)
319
  except json.JSONDecodeError as e:
320
  # If direct parsing fails, try cleaning the JSON
321
  import re
@@ -323,64 +336,171 @@ Consider the existing controls and compliance status when developing mitigation
323
  json_str = re.sub(r'\r\s*', ' ', json_str)
324
  json_str = re.sub(r'\t+', ' ', json_str)
325
  json_str = re.sub(r'\s+', ' ', json_str)
326
- mitigation_data = json.loads(json_str)
327
- return RiskMitigationResponse(**mitigation_data)
328
  else:
329
  raise ValueError("No valid JSON found in response")
330
 
331
  except (json.JSONDecodeError, ValueError) as e:
332
- # Fallback response if JSON parsing fails - provide intelligent mitigation
333
- fallback_risks = []
334
- for i, item in enumerate(risk_items):
335
- # Intelligent fallback logic based on threat category and existing controls
336
- current_impact = int(item.impact)
337
- current_likelihood = int(item.likelihood)
338
-
339
- # Risk reduction logic based on category
340
- impact_reduction = 1
341
- likelihood_reduction = 1
342
-
343
- if item.majorCategory.lower() in ['fire', 'natural disaster']:
344
- impact_reduction = 2
345
- likelihood_reduction = 2
346
- elif item.majorCategory.lower() in ['cyber security', 'security']:
347
- impact_reduction = 1
348
- likelihood_reduction = 2
349
-
350
- revised_impact = max(1, current_impact - impact_reduction)
351
- revised_likelihood = max(1, current_likelihood - likelihood_reduction)
352
-
353
- # Generate category-specific mitigation plans
354
- if item.majorCategory.lower() == 'fire':
355
- mitigation_plan = "• Install automatic fire suppression systems • Conduct quarterly safety training • Implement 24/7 monitoring alerts"
356
- ownership = "Facilities Management Team"
357
- elif item.majorCategory.lower() in ['cyber security', 'security']:
358
- mitigation_plan = "• Deploy endpoint detection response systems • Implement network segmentation controls • Conduct regular penetration testing"
359
- ownership = "Information Security Team"
360
- else:
361
- mitigation_plan = f"• Enhance existing {item.majorCategory.lower()} controls • Implement continuous monitoring systems • Establish incident response procedures"
362
- ownership = f"{item.enablerDomain} Team"
363
-
364
- fallback_risks.append(MitigationResponse(
365
- revisedImpact=revised_impact,
366
- revisedLikelihood=revised_likelihood,
367
- revisedRiskValue=revised_impact * revised_likelihood,
368
- mitigationPlan=mitigation_plan,
369
- ownership=ownership
370
- ))
371
 
372
- return RiskMitigationResponse(mitigatedRisks=fallback_risks)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
373
 
374
  except Exception as e:
375
  # General fallback for any other errors
376
- fallback_risks = []
377
- for i, item in enumerate(risk_items):
378
- fallback_risks.append(MitigationResponse(
379
- revisedImpact=2,
380
- revisedLikelihood=2,
381
- revisedRiskValue=4,
382
- mitigationPlan="• Implement enhanced risk controls • Establish monitoring procedures • Conduct regular assessments",
383
- ownership="Risk Management Team"
384
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
385
 
386
- return RiskMitigationResponse(mitigatedRisks=fallback_risks)
 
198
  result = generate_response(prompt, req.message)
199
  return result
200
 
201
+ class RiskQuestion(BaseModel):
202
+ category: str
203
+ question: str
204
+ user_answer: str
 
 
205
 
206
+ class RiskRequestModel(BaseModel):
207
+ responses: List[RiskQuestion]
 
 
 
 
 
 
 
 
208
 
209
+ class RiskTrends(BaseModel):
210
+ top_category: str
211
+ risk_severity: str
212
+ observations: List[str]
213
+
214
+ class RiskSummary(BaseModel):
215
+ risk_classification_summary: str
216
+ mitigation_suggestions: List[str]
217
+ risk_trends: RiskTrends
218
+
219
+ class RiskAnalysis(BaseModel):
220
+ risk_id: str
221
+ category: str
222
+ question: str
223
+ user_answer: str
224
+ risk_name: str
225
+ identified_threat: str
226
+ likelihood: str
227
+ impact: str
228
+ risk_value: int
229
+ residual_risk: str
230
+ current_control_description: str
231
+ current_control_rating: str
232
+ business_unit: str
233
+ risk_owner: str
234
+ timeline: str
235
+ mitigation_plan: str
236
+ summary: RiskSummary
237
 
238
  class RiskMitigationResponse(BaseModel):
239
+ risk_analysis: RiskAnalysis
240
 
241
  @app.post("/api/risk-mitigation", response_model=RiskMitigationResponse)
242
+ def generate_risk_mitigation(request: RiskRequestModel):
243
  """
244
+ Generate comprehensive risk analysis and mitigation plan based on user responses
245
  """
246
  system_prompt = """
247
+ You are an expert risk management and business continuity analyst. Your task is to analyze user responses to risk assessment questions and provide detailed risk analysis with mitigation strategies.
248
+
249
+ For the risk question provided, you need to:
250
+ 1. Create a unique risk identifier (RISK-XXX format)
251
+ 2. Identify the specific risk from the user's answer
252
+ 3. Assess likelihood (Low, Medium, High, Very High) and impact (Minor, Moderate, Significant, Severe)
253
+ 4. Calculate a risk value (1-10 scale)
254
+ 5. Determine residual risk (Low, Moderate, High, Critical)
255
+ 6. Evaluate current controls based on the user's answer
256
+ 7. Assign appropriate business unit and risk owner
257
+ 8. Provide a mitigation plan with timeline
258
+ 9. Create a comprehensive risk summary with classification, mitigation suggestions, and trends
259
+
260
+ Use your expertise to make reasonable assumptions about the business context when details are limited.
261
+
262
+ Respond strictly in this JSON format:
 
 
 
 
 
 
 
 
 
 
 
263
  {
264
+ "risk_analysis": {
265
+ "risk_id": "RISK-XXX",
266
+ "category": "The risk category from input",
267
+ "question": "The original question",
268
+ "user_answer": "The user's response",
269
+ "risk_name": "Concise name of the identified risk",
270
+ "identified_threat": "Detailed description of the threat identified",
271
+ "likelihood": "High/Medium/Low/Very High",
272
+ "impact": "Severe/Significant/Moderate/Minor",
273
+ "risk_value": 1-10,
274
+ "residual_risk": "Critical/High/Moderate/Low",
275
+ "current_control_description": "Description of current controls based on user answer",
276
+ "current_control_rating": "Good/Fair/Poor",
277
+ "business_unit": "Relevant department responsible",
278
+ "risk_owner": "Specific role responsible for the risk",
279
+ "timeline": "Immediate/Short-term/Medium-term/Long-term",
280
+ "mitigation_plan": "Detailed plan to address the risk",
281
+ "summary": {
282
+ "risk_classification_summary": "Brief summary of the risk classification",
283
+ "mitigation_suggestions": [
284
+ "Suggestion 1",
285
+ "Suggestion 2",
286
+ "Suggestion 3"
287
+ ],
288
+ "risk_trends": {
289
+ "top_category": "Most critical risk category",
290
+ "risk_severity": "Overall severity assessment",
291
+ "observations": [
292
+ "Observation 1",
293
+ "Observation 2",
294
+ "Observation 3"
295
+ ]
296
+ }
297
  }
298
+ }
299
  }
300
  """
301
 
302
+ # For simplicity, we'll just analyze the first question in the list
303
+ # In a real implementation, you might want to handle multiple questions differently
304
+ if not request.responses:
305
+ raise ValueError("No risk questions provided")
306
+
307
+ item = request.responses[0] # Take the first response for analysis
308
+
 
 
 
 
 
 
 
 
 
309
  user_message = f"""
310
+ Please analyze the following risk assessment response:
311
 
312
+ Category: {item.category}
313
+ Question: {item.question}
314
+ User Answer: {item.user_answer}
315
 
316
+ Provide a comprehensive risk analysis with mitigation plan based on this response.
 
 
 
 
 
 
 
317
  """
318
 
319
  try:
 
327
  json_str = result[json_start:json_end]
328
  # The AI returns properly formatted JSON with newlines, just parse it directly
329
  try:
330
+ risk_data = json.loads(json_str)
331
+ return RiskMitigationResponse(**risk_data)
332
  except json.JSONDecodeError as e:
333
  # If direct parsing fails, try cleaning the JSON
334
  import re
 
336
  json_str = re.sub(r'\r\s*', ' ', json_str)
337
  json_str = re.sub(r'\t+', ' ', json_str)
338
  json_str = re.sub(r'\s+', ' ', json_str)
339
+ risk_data = json.loads(json_str)
340
+ return RiskMitigationResponse(**risk_data)
341
  else:
342
  raise ValueError("No valid JSON found in response")
343
 
344
  except (json.JSONDecodeError, ValueError) as e:
345
+ # Fallback response if JSON parsing fails - provide intelligent risk analysis
346
+ item = request.responses[0] # Take the first response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
347
 
348
+ # Create a fallback risk analysis based on the category
349
+ if item.category.lower() == 'fire':
350
+ risk_analysis = RiskAnalysis(
351
+ risk_id="RISK-001",
352
+ category=item.category,
353
+ question=item.question,
354
+ user_answer=item.user_answer,
355
+ risk_name="Fire safety control deficiency",
356
+ identified_threat="Potential for uncontrolled fire damage due to inadequate fire suppression systems",
357
+ likelihood="High",
358
+ impact="Severe",
359
+ risk_value=9,
360
+ residual_risk="Critical",
361
+ current_control_description="Basic manual fire control measures without automated systems",
362
+ current_control_rating="Poor",
363
+ business_unit="Facilities",
364
+ risk_owner="Fire Safety Officer",
365
+ timeline="Immediate",
366
+ mitigation_plan="Install automated fire suppression systems, implement 24/7 monitoring, and conduct regular fire drills",
367
+ summary=RiskSummary(
368
+ risk_classification_summary="Critical fire safety risk requiring immediate mitigation",
369
+ mitigation_suggestions=[
370
+ "Deploy automated fire suppression systems",
371
+ "Install early detection monitoring",
372
+ "Conduct regular fire drills"
373
+ ],
374
+ risk_trends=RiskTrends(
375
+ top_category="Fire",
376
+ risk_severity="Critical",
377
+ observations=[
378
+ "Fire safety systems are outdated or insufficient",
379
+ "Manual responses may be inadequate for rapid fire spread",
380
+ "Immediate automated solution implementation is recommended"
381
+ ]
382
+ )
383
+ )
384
+ )
385
+ elif item.category.lower() == 'cybercrime':
386
+ risk_analysis = RiskAnalysis(
387
+ risk_id="RISK-002",
388
+ category=item.category,
389
+ question=item.question,
390
+ user_answer=item.user_answer,
391
+ risk_name="Outdated incident response planning",
392
+ identified_threat="Delayed or ineffective response to cyber incidents due to outdated procedures",
393
+ likelihood="High",
394
+ impact="Severe",
395
+ risk_value=8,
396
+ residual_risk="High",
397
+ current_control_description="Outdated incident response plan without recent testing",
398
+ current_control_rating="Poor",
399
+ business_unit="Information Technology",
400
+ risk_owner="CISO",
401
+ timeline="Immediate",
402
+ mitigation_plan="Update incident response plan, conduct regular testing, and implement automated threat detection",
403
+ summary=RiskSummary(
404
+ risk_classification_summary="High-risk cybersecurity vulnerability requiring prompt remediation",
405
+ mitigation_suggestions=[
406
+ "Update and test incident response plan quarterly",
407
+ "Implement automated threat detection systems",
408
+ "Conduct regular cybersecurity training"
409
+ ],
410
+ risk_trends=RiskTrends(
411
+ top_category="Cybercrime",
412
+ risk_severity="High",
413
+ observations=[
414
+ "Incident response plans are outdated across organization",
415
+ "Limited testing reduces effectiveness of responses",
416
+ "Regular plan updates and testing are essential"
417
+ ]
418
+ )
419
+ )
420
+ )
421
+ else:
422
+ # Generic risk analysis for other categories
423
+ risk_analysis = RiskAnalysis(
424
+ risk_id="RISK-003",
425
+ category=item.category,
426
+ question=item.question,
427
+ user_answer=item.user_answer,
428
+ risk_name=f"Inadequate {item.category} controls",
429
+ identified_threat=f"Increased vulnerability to {item.category}-related incidents",
430
+ likelihood="Medium",
431
+ impact="Moderate",
432
+ risk_value=6,
433
+ residual_risk="Moderate",
434
+ current_control_description=f"Basic {item.category} controls with improvement opportunities",
435
+ current_control_rating="Fair",
436
+ business_unit="Operations",
437
+ risk_owner="Risk Manager",
438
+ timeline="Short-term",
439
+ mitigation_plan=f"Enhance {item.category} controls, implement monitoring systems, and establish regular review procedures",
440
+ summary=RiskSummary(
441
+ risk_classification_summary=f"Moderate {item.category} risk requiring planned mitigation",
442
+ mitigation_suggestions=[
443
+ f"Enhance existing {item.category} controls",
444
+ "Implement monitoring systems",
445
+ "Conduct regular control reviews"
446
+ ],
447
+ risk_trends=RiskTrends(
448
+ top_category=item.category,
449
+ risk_severity="Moderate",
450
+ observations=[
451
+ f"{item.category} controls need enhancement",
452
+ "Regular monitoring would improve risk posture",
453
+ "Structured improvement plan recommended"
454
+ ]
455
+ )
456
+ )
457
+ )
458
+
459
+ return RiskMitigationResponse(risk_analysis=risk_analysis)
460
 
461
  except Exception as e:
462
  # General fallback for any other errors
463
+ item = request.responses[0] if request.responses else RiskQuestion(
464
+ category="General",
465
+ question="Risk assessment question",
466
+ user_answer="Insufficient information provided"
467
+ )
468
+
469
+ # Generic fallback risk analysis
470
+ risk_analysis = RiskAnalysis(
471
+ risk_id="RISK-000",
472
+ category=item.category,
473
+ question=item.question,
474
+ user_answer=item.user_answer,
475
+ risk_name="Undefined risk",
476
+ identified_threat="Potential business impact from unassessed risk",
477
+ likelihood="Medium",
478
+ impact="Moderate",
479
+ risk_value=4,
480
+ residual_risk="Moderate",
481
+ current_control_description="Unknown or unassessed controls",
482
+ current_control_rating="Fair",
483
+ business_unit="Risk Management",
484
+ risk_owner="Risk Officer",
485
+ timeline="Short-term",
486
+ mitigation_plan="Conduct comprehensive risk assessment and implement appropriate controls",
487
+ summary=RiskSummary(
488
+ risk_classification_summary="General risk requiring assessment and control implementation",
489
+ mitigation_suggestions=[
490
+ "Conduct detailed risk assessment",
491
+ "Implement appropriate controls",
492
+ "Establish regular monitoring"
493
+ ],
494
+ risk_trends=RiskTrends(
495
+ top_category="General",
496
+ risk_severity="Moderate",
497
+ observations=[
498
+ "Risk assessment needs improvement",
499
+ "Control effectiveness should be evaluated",
500
+ "Regular risk monitoring recommended"
501
+ ]
502
+ )
503
+ )
504
+ )
505
 
506
+ return RiskMitigationResponse(risk_analysis=risk_analysis)