Yaswanth-Bolla commited on
Commit
f041270
·
1 Parent(s): 4af0351

Business continuity endpoint

Browse files
Files changed (5) hide show
  1. API_DOCUMENTATION.md +182 -0
  2. app.py +2 -0
  3. business_continuity.py +216 -0
  4. enterprise_ra.py +36 -16
  5. threat_ra.py +36 -16
API_DOCUMENTATION.md CHANGED
@@ -589,3 +589,185 @@ curl -X POST "http://localhost:8000/api/enterprise-ra/generate-risks" \
589
  "number_of_risks": 5
590
  }'
591
  ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
589
  "number_of_risks": 5
590
  }'
591
  ```
592
+
593
+ ---
594
+
595
+ ## Business Continuity Recovery Strategies Endpoint
596
+
597
+ ### Generate Recovery Strategies
598
+
599
+ **Endpoint:** `POST /api/business-continuity/generate-recovery-strategies`
600
+
601
+ **Purpose:** Generate comprehensive business continuity recovery strategies for specific business processes, covering people, technology, site, and vendor unavailability scenarios.
602
+
603
+ **Use Cases:**
604
+ - Business continuity planning and strategy development
605
+ - Disaster recovery planning for critical business processes
606
+ - Resilience planning for operational dependencies
607
+ - Risk mitigation strategy development
608
+ - Compliance with business continuity standards (ISO 22301)
609
+
610
+ **Request Body:**
611
+ ```json
612
+ {
613
+ "business_process": {
614
+ "department": "Finance",
615
+ "sub_department": "Accounts Payable",
616
+ "process_name": "Invoice Processing",
617
+ "process_description": "Processing vendor invoices, approval workflows, and payment authorization for all company purchases"
618
+ },
619
+ "analysis_data": {
620
+ "impact_analysis": {
621
+ "rto": "4 hours",
622
+ "rpo": "1 hour",
623
+ "maximum_tolerable_downtime": "24 hours",
624
+ "annual_revenue_impact": "$2.5M",
625
+ "dependencies": ["ERP system", "banking systems", "approval workflows"]
626
+ },
627
+ "minimum_operating_requirements": {
628
+ "staff_minimum": "2 senior staff",
629
+ "technology_requirements": ["ERP access", "banking portal", "email system"],
630
+ "workspace_requirements": "Secure location with internet access",
631
+ "vendor_dependencies": ["primary bank", "ERP vendor", "internet provider"]
632
+ }
633
+ }
634
+ }
635
+ ```
636
+
637
+ **Response:**
638
+ ```json
639
+ {
640
+ "success": true,
641
+ "people_unavailability_strategy": "Establish cross-training programs for all invoice processing roles with documented procedures, maintain a rotation schedule to ensure multiple staff are familiar with critical functions, and create emergency contact lists for temporary qualified personnel from other departments. Implement role-based access controls and approval delegation workflows to ensure processing can continue with reduced staff.",
642
+ "people_reasoning": "Cross-training and documentation are essential for invoice processing continuity since financial processes require specific expertise and regulatory compliance knowledge that cannot be easily replaced.",
643
+
644
+ "technology_data_unavailability_strategy": "Implement automated daily backups of all invoice data with cloud-based storage, establish redundant ERP system access through secondary data centers, and maintain offline copies of critical vendor information and payment instructions. Deploy backup internet connections and mobile hotspots for emergency connectivity to banking systems.",
645
+ "technology_reasoning": "Financial processes like invoice processing require real-time access to accurate data and secure banking connections, making technology redundancy critical for meeting payment deadlines and avoiding vendor relationship damage.",
646
+
647
+ "site_unavailability_strategy": "Pre-configure secure remote access to all financial systems with VPN and multi-factor authentication, establish agreements for temporary workspace at alternate company locations, and ensure key personnel have secure home office setups with dedicated internet connections. Maintain physical copies of emergency vendor contact information and critical payment authorization documents.",
648
+ "site_reasoning": "Invoice processing can be performed remotely when proper security controls are in place, but requires secure access to sensitive financial systems and confidential vendor information.",
649
+
650
+ "third_party_vendors_unavailability_strategy": "Maintain relationships with backup banking partners for payment processing, establish secondary internet service providers with automatic failover, and negotiate service level agreements with ERP vendor for priority support during outages. Keep emergency contact information for all critical vendors and establish alternative communication channels.",
651
+ "vendor_reasoning": "Invoice processing depends heavily on external banking systems and ERP infrastructure, requiring vendor diversification to ensure payment capabilities remain operational during service disruptions.",
652
+
653
+ "message": "Successfully generated comprehensive recovery strategies"
654
+ }
655
+ ```
656
+
657
+ **Key Features:**
658
+ - **Process-Specific Strategies**: Tailored recommendations based on the specific business process and its dependencies
659
+ - **Industry Best Practices**: Strategies aligned with ISO 22301 business continuity standards and industry frameworks
660
+ - **Actionable Recommendations**: Detailed, implementable steps with specific technologies and procedures
661
+ - **Risk-Based Reasoning**: Clear explanations for why each strategy is appropriate for the specific process
662
+ - **Comprehensive Coverage**: Addresses all major disruption scenarios (people, technology, site, vendor)
663
+ - **Regulatory Awareness**: Considers compliance requirements and regulatory impacts in strategy development
664
+
665
+ **Response Fields:**
666
+
667
+ | Field | Description |
668
+ |-------|-------------|
669
+ | `people_unavailability_strategy` | Detailed strategy for maintaining operations when key personnel are unavailable |
670
+ | `people_reasoning` | Justification for the people strategy based on process requirements |
671
+ | `technology_data_unavailability_strategy` | Strategy for handling IT system failures, data loss, or technology disruptions |
672
+ | `technology_reasoning` | Explanation of why the technology strategy fits the process requirements |
673
+ | `site_unavailability_strategy` | Plans for continuing operations when primary work locations are inaccessible |
674
+ | `site_reasoning` | Justification for site strategy based on process location dependencies |
675
+ | `third_party_vendors_unavailability_strategy` | Contingency plans for vendor, supplier, or service provider disruptions |
676
+ | `vendor_reasoning` | Explanation of vendor strategy relevance to process dependencies |
677
+
678
+ **Error Handling:**
679
+ - Provides intelligent fallback strategies when AI service is unavailable
680
+ - Generates process-specific recommendations based on request parameters
681
+ - Includes comprehensive error messages for troubleshooting
682
+
683
+ ### cURL Example:
684
+ ```bash
685
+ curl -X POST "http://localhost:8000/api/business-continuity/generate-recovery-strategies" \
686
+ -H "Content-Type: application/json" \
687
+ -d '{
688
+ "business_process": {
689
+ "department": "Finance",
690
+ "sub_department": "Accounts Payable",
691
+ "process_name": "Invoice Processing",
692
+ "process_description": "Processing vendor invoices, approval workflows, and payment authorization"
693
+ },
694
+ "analysis_data": {
695
+ "impact_analysis": {
696
+ "rto": "4 hours",
697
+ "rpo": "1 hour",
698
+ "maximum_tolerable_downtime": "24 hours"
699
+ },
700
+ "minimum_operating_requirements": {
701
+ "staff_minimum": "2 senior staff",
702
+ "technology_requirements": ["ERP access", "banking portal"],
703
+ "workspace_requirements": "Secure location with internet access"
704
+ }
705
+ }
706
+ }'
707
+ ```
708
+
709
+ ### Postman Collection Setup:
710
+
711
+ **Request Configuration:**
712
+ - **Method**: POST
713
+ - **URL**: `{{base_url}}/business-continuity/api/business-continuity/generate-recovery-strategies`
714
+ - **Headers**: `Content-Type: application/json`
715
+
716
+ **Test Scenarios:**
717
+
718
+ *Financial Process Example:*
719
+ ```json
720
+ {
721
+ "business_process": {
722
+ "department": "Finance",
723
+ "sub_department": "Treasury",
724
+ "process_name": "Cash Management",
725
+ "process_description": "Daily cash flow monitoring, bank reconciliation, and liquidity management"
726
+ },
727
+ "analysis_data": {
728
+ "impact_analysis": {
729
+ "rto": "2 hours",
730
+ "maximum_tolerable_downtime": "8 hours",
731
+ "dependencies": ["banking systems", "treasury management system"]
732
+ }
733
+ }
734
+ }
735
+ ```
736
+
737
+ *IT Operations Example:*
738
+ ```json
739
+ {
740
+ "business_process": {
741
+ "department": "IT",
742
+ "sub_department": "Infrastructure",
743
+ "process_name": "Server Monitoring",
744
+ "process_description": "24/7 monitoring of critical IT infrastructure and incident response"
745
+ },
746
+ "analysis_data": {
747
+ "impact_analysis": {
748
+ "rto": "15 minutes",
749
+ "maximum_tolerable_downtime": "1 hour",
750
+ "dependencies": ["monitoring tools", "alerting systems", "ticketing system"]
751
+ }
752
+ }
753
+ }
754
+ ```
755
+
756
+ *HR Process Example:*
757
+ ```json
758
+ {
759
+ "business_process": {
760
+ "department": "Human Resources",
761
+ "sub_department": "Payroll",
762
+ "process_name": "Payroll Processing",
763
+ "process_description": "Bi-weekly payroll calculation, tax withholding, and direct deposit processing"
764
+ },
765
+ "analysis_data": {
766
+ "impact_analysis": {
767
+ "rto": "24 hours",
768
+ "maximum_tolerable_downtime": "72 hours",
769
+ "dependencies": ["HRIS system", "banking integration", "tax calculation system"]
770
+ }
771
+ }
772
+ }
773
+ ```
app.py CHANGED
@@ -10,6 +10,7 @@ import json
10
  from enterprise_ra import enterprise_ra_router
11
  from threat_ra import threat_ra_router
12
  from dashboard_analytics import dashboard_router
 
13
 
14
  app = FastAPI(title="EY Catalyst Risk Analysis API", version="1.0.0")
15
 
@@ -17,6 +18,7 @@ app = FastAPI(title="EY Catalyst Risk Analysis API", version="1.0.0")
17
  app.include_router(enterprise_ra_router, prefix="/enterprise")
18
  app.include_router(threat_ra_router, prefix="/threat")
19
  app.include_router(dashboard_router, prefix="/dashboard")
 
20
 
21
  # Environment Variables
22
  GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
 
10
  from enterprise_ra import enterprise_ra_router
11
  from threat_ra import threat_ra_router
12
  from dashboard_analytics import dashboard_router
13
+ from business_continuity import business_continuity_router
14
 
15
  app = FastAPI(title="EY Catalyst Risk Analysis API", version="1.0.0")
16
 
 
18
  app.include_router(enterprise_ra_router, prefix="/enterprise")
19
  app.include_router(threat_ra_router, prefix="/threat")
20
  app.include_router(dashboard_router, prefix="/dashboard")
21
+ app.include_router(business_continuity_router, prefix="/business-continuity")
22
 
23
  # Environment Variables
24
  GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
business_continuity.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # business_continuity.py
2
+ from fastapi import APIRouter, HTTPException
3
+ from pydantic import BaseModel
4
+ from typing import List, Optional, Dict, Any
5
+ import os
6
+ import openai
7
+ import json
8
+ import uuid
9
+
10
+ # Environment Variables
11
+ GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
12
+ if GROQ_API_KEY:
13
+ GROQ_API_KEY = GROQ_API_KEY.strip()
14
+
15
+ # Model Setup
16
+ def generate_response(system_prompt: str, user_message: str):
17
+ if not GROQ_API_KEY:
18
+ raise Exception("GROQ_API_KEY environment variable is not set")
19
+
20
+ client = openai.OpenAI(api_key=GROQ_API_KEY, base_url="https://api.groq.com/openai/v1")
21
+ try:
22
+ response = client.chat.completions.create(
23
+ model="llama3-8b-8192",
24
+ messages=[
25
+ {"role": "system", "content": system_prompt},
26
+ {"role": "user", "content": user_message}
27
+ ],
28
+ temperature=0.4
29
+ )
30
+ return response.choices[0].message.content
31
+ except Exception as e:
32
+ raise Exception(f"GROQ API connection failed: {str(e)}")
33
+
34
+ # Request Models
35
+ class BusinessProcess(BaseModel):
36
+ department: str
37
+ sub_department: Optional[str] = ""
38
+ process_name: str
39
+ process_description: str
40
+
41
+ class AnalysisData(BaseModel):
42
+ impact_analysis: Optional[Dict[str, Any]] = {}
43
+ minimum_operating_requirements: Optional[Dict[str, Any]] = {}
44
+
45
+ class BusinessContinuityRequest(BaseModel):
46
+ business_process: BusinessProcess
47
+ analysis_data: AnalysisData
48
+
49
+ # Response Models
50
+ class RecoveryStrategiesResponse(BaseModel):
51
+ success: bool
52
+ people_unavailability_strategy: str
53
+ people_reasoning: str
54
+ technology_data_unavailability_strategy: str
55
+ technology_reasoning: str
56
+ site_unavailability_strategy: str
57
+ site_reasoning: str
58
+ third_party_vendors_unavailability_strategy: str
59
+ vendor_reasoning: str
60
+ message: str
61
+
62
+ # Business Continuity Router
63
+ business_continuity_router = APIRouter()
64
+
65
+ @business_continuity_router.post("/api/business-continuity/generate-recovery-strategies", response_model=RecoveryStrategiesResponse)
66
+ def generate_recovery_strategies(request: BusinessContinuityRequest):
67
+ """
68
+ Generate comprehensive business continuity recovery strategies for a business process
69
+ """
70
+ system_prompt = """You are a business continuity expert with extensive experience in developing recovery strategies for various business processes. Your task is to generate comprehensive, actionable recovery strategies and their reasoning for specific business processes.
71
+
72
+ CRITICAL: You must respond with ONLY a valid JSON object. Do not include any markdown formatting, code blocks, or additional text.
73
+
74
+ For each recovery strategy, you need to:
75
+ 1. Provide detailed, actionable steps that can be immediately implemented
76
+ 2. Consider the specific nature of the business process and its dependencies
77
+ 3. Include realistic timelines and resource requirements
78
+ 4. Reference industry best practices and standards (ISO 22301, NIST, COOP guidelines)
79
+ 5. Provide clear reasoning that explains why each strategy is appropriate for the specific process
80
+
81
+ Consider these factors:
82
+ - Business process criticality and dependencies
83
+ - Resource requirements (human, technology, facilities)
84
+ - Regulatory and compliance considerations
85
+ - Cost-effectiveness and feasibility
86
+ - Recovery time objectives (RTO) and recovery point objectives (RPO)
87
+ - Industry-specific risks and challenges
88
+ - Stakeholder communication requirements
89
+ - Testing and maintenance needs
90
+
91
+ Provide specific justifications that reference:
92
+ - Industry standards and best practices
93
+ - Historical incident data and lessons learned
94
+ - Process-specific vulnerabilities and requirements
95
+ - Resource availability and constraints
96
+ - Regulatory requirements and compliance needs
97
+ - Business impact considerations
98
+ - Technology dependencies and alternatives
99
+
100
+ RESPOND WITH ONLY THIS EXACT JSON FORMAT (no markdown, no code blocks, no additional text):
101
+ {
102
+ "people_unavailability_strategy": "Detailed strategy for handling personnel unavailability with specific actionable steps",
103
+ "people_reasoning": "Clear explanation of why this strategy is appropriate for this specific business process",
104
+ "technology_data_unavailability_strategy": "Detailed strategy for handling technology and data unavailability with specific steps",
105
+ "technology_reasoning": "Clear explanation of why this technology strategy fits this process",
106
+ "site_unavailability_strategy": "Detailed strategy for handling site unavailability with actionable steps",
107
+ "site_reasoning": "Clear explanation of why this site strategy is suitable for this process",
108
+ "third_party_vendors_unavailability_strategy": "Detailed strategy for handling vendor/supplier disruptions with specific steps",
109
+ "vendor_reasoning": "Clear explanation of why this vendor strategy is appropriate for this process"
110
+ }"""
111
+
112
+ # Convert request to JSON for the prompt
113
+ input_json = {
114
+ "business_process": {
115
+ "department": request.business_process.department,
116
+ "sub_department": request.business_process.sub_department,
117
+ "process_name": request.business_process.process_name,
118
+ "process_description": request.business_process.process_description
119
+ },
120
+ "analysis_data": {
121
+ "impact_analysis": request.analysis_data.impact_analysis,
122
+ "minimum_operating_requirements": request.analysis_data.minimum_operating_requirements
123
+ }
124
+ }
125
+
126
+ user_message = f"""You are a business continuity expert. Generate comprehensive recovery strategies AND their reasoning for the business process described in the following JSON data:
127
+
128
+ {json.dumps(input_json, indent=2)}
129
+
130
+ Please analyze the provided business process information and provide specific, actionable recovery strategies for each of the following scenarios. Each strategy should be detailed, practical, and specific to this business process.
131
+
132
+ For EACH strategy, also provide a clear reasoning explanation of WHY this strategy was recommended for this specific process.
133
+
134
+ Strategy Categories Required:
135
+ 1. People Unavailability Strategy - What to do when key personnel are unavailable
136
+ 2. Technology/Data Unavailability Strategy - How to handle IT system failures or data loss
137
+ 3. Site Unavailability Strategy - Plans for when the primary work location is inaccessible
138
+ 4. Third Party Vendors Unavailability Strategy - Contingencies for vendor/supplier disruptions
139
+
140
+ Output Requirements:
141
+ - Format your response as a valid JSON object with these exact keys:
142
+ - people_unavailability_strategy
143
+ - people_reasoning
144
+ - technology_data_unavailability_strategy
145
+ - technology_reasoning
146
+ - site_unavailability_strategy
147
+ - site_reasoning
148
+ - third_party_vendors_unavailability_strategy
149
+ - vendor_reasoning
150
+
151
+ - Each strategy should be a detailed string (2-3 sentences minimum) with actionable steps
152
+ - Each reasoning should explain WHY this strategy was chosen for this specific process (1-2 sentences)
153
+ - Return ONLY the JSON object, no additional text or formatting"""
154
+
155
+ try:
156
+ result = generate_response(system_prompt, user_message)
157
+
158
+ # Clean the response - remove markdown code blocks if present
159
+ cleaned_result = result.strip()
160
+ if cleaned_result.startswith('```json'):
161
+ cleaned_result = cleaned_result[7:] # Remove ```json
162
+ elif cleaned_result.startswith('```'):
163
+ cleaned_result = cleaned_result[3:] # Remove ```
164
+ if cleaned_result.endswith('```'):
165
+ cleaned_result = cleaned_result[:-3] # Remove trailing ```
166
+ cleaned_result = cleaned_result.strip()
167
+
168
+ # Extract JSON from the response
169
+ json_start = cleaned_result.find('{')
170
+ json_end = cleaned_result.rfind('}') + 1
171
+
172
+ if json_start != -1 and json_end > json_start:
173
+ json_str = cleaned_result[json_start:json_end]
174
+ strategies_data = json.loads(json_str)
175
+
176
+ return RecoveryStrategiesResponse(
177
+ success=True,
178
+ people_unavailability_strategy=strategies_data.get("people_unavailability_strategy", ""),
179
+ people_reasoning=strategies_data.get("people_reasoning", ""),
180
+ technology_data_unavailability_strategy=strategies_data.get("technology_data_unavailability_strategy", ""),
181
+ technology_reasoning=strategies_data.get("technology_reasoning", ""),
182
+ site_unavailability_strategy=strategies_data.get("site_unavailability_strategy", ""),
183
+ site_reasoning=strategies_data.get("site_reasoning", ""),
184
+ third_party_vendors_unavailability_strategy=strategies_data.get("third_party_vendors_unavailability_strategy", ""),
185
+ vendor_reasoning=strategies_data.get("vendor_reasoning", ""),
186
+ message="Successfully generated comprehensive recovery strategies"
187
+ )
188
+ else:
189
+ raise ValueError("No valid JSON found in response")
190
+
191
+ except (json.JSONDecodeError, ValueError) as e:
192
+ # Fallback response with generic but relevant strategies
193
+ process_name = request.business_process.process_name
194
+ department = request.business_process.department
195
+
196
+ fallback_response = RecoveryStrategiesResponse(
197
+ success=True,
198
+ people_unavailability_strategy=f"Develop cross-training programs for key roles in {process_name}, maintain updated contact lists for temporary staff, and establish clear escalation procedures for critical decision-making. Document all critical processes to ensure knowledge transfer and implement a buddy system for essential personnel.",
199
+ people_reasoning=f"Cross-training and documentation are essential for {process_name} in {department} to reduce single points of failure and ensure continuity when key personnel are unavailable.",
200
+
201
+ technology_data_unavailability_strategy=f"Implement regular automated data backups for {process_name} systems, establish redundant systems and failover procedures, and maintain updated disaster recovery documentation. Test backup systems monthly and ensure all critical data is replicated to secure off-site locations.",
202
+ technology_reasoning=f"Data protection and system redundancy are critical for {process_name} operations to minimize downtime and ensure rapid recovery from technology failures.",
203
+
204
+ site_unavailability_strategy=f"Identify and pre-approve alternative work locations for {process_name} operations, enable remote work capabilities with necessary tools and secure access, and establish communication protocols for distributed teams. Maintain emergency supplies and equipment at alternate locations.",
205
+ site_reasoning=f"Alternative work arrangements ensure {process_name} operations can continue even when primary {department} facilities are inaccessible due to emergencies or disasters.",
206
+
207
+ third_party_vendors_unavailability_strategy=f"Maintain relationships with alternate vendors and suppliers critical to {process_name}, keep emergency contact information updated, and develop contingency contracts for essential services. Regularly assess vendor stability and maintain inventory buffers for critical supplies.",
208
+ vendor_reasoning=f"Vendor diversification and contingency planning reduce dependency risks for {process_name} and ensure continuity of critical external services and supplies.",
209
+
210
+ message="Generated fallback recovery strategies due to processing error"
211
+ )
212
+
213
+ return fallback_response
214
+
215
+ except Exception as e:
216
+ raise HTTPException(status_code=500, detail=f"Error generating recovery strategies: {str(e)}")
enterprise_ra.py CHANGED
@@ -83,8 +83,9 @@ def generate_enterprise_risks(request: RiskGenerationRequest):
83
  """
84
  Generate comprehensive enterprise risks based on category and department
85
  """
86
- system_prompt = """
87
- You are an expert enterprise risk analyst. Your task is to generate comprehensive risks for organizations based on the provided category, department, and business context.
 
88
 
89
  For each risk, you need to:
90
  1. Create a clear, specific risk name
@@ -111,7 +112,7 @@ Provide specific justifications that reference:
111
  - Technology adoption patterns
112
  - Business model vulnerabilities
113
 
114
- Respond strictly in this JSON format:
115
  {
116
  "risks": [
117
  {
@@ -131,8 +132,7 @@ Respond strictly in this JSON format:
131
  ]
132
  }
133
  ]
134
- }
135
- """
136
 
137
  user_message = f"""
138
  Generate {request.number_of_risks} enterprise risks for the following context:
@@ -148,12 +148,22 @@ Please provide comprehensive risks that are relevant to this department and cate
148
  try:
149
  result = generate_response(system_prompt, user_message)
150
 
 
 
 
 
 
 
 
 
 
 
151
  # Extract JSON from the response
152
- json_start = result.find('{')
153
- json_end = result.rfind('}') + 1
154
 
155
  if json_start != -1 and json_end > json_start:
156
- json_str = result[json_start:json_end]
157
  risks_data = json.loads(json_str)
158
 
159
  # Convert to our response format
@@ -227,8 +237,9 @@ def generate_threats_for_risk(request: ThreatGenerationRequest):
227
  """
228
  Generate specific threats for a given risk
229
  """
230
- system_prompt = """
231
- You are an expert threat analyst. Your task is to generate specific threats that could lead to or contribute to a given risk.
 
232
 
233
  For each threat, provide:
234
  1. A clear, specific threat name
@@ -255,7 +266,7 @@ Provide specific justifications that reference:
255
  - Supply chain and third-party risks
256
  - Insider threat patterns specific to the department
257
 
258
- Respond strictly in this JSON format:
259
  {
260
  "threats": [
261
  {
@@ -264,8 +275,7 @@ Respond strictly in this JSON format:
264
  "justification": "Industry-specific reasoning for why this threat is particularly relevant, including statistics, trends, regulatory factors, or common occurrences in this sector and department"
265
  }
266
  ]
267
- }
268
- """
269
 
270
  user_message = f"""
271
  Generate {request.number_of_threats} specific threats for the following risk:
@@ -280,12 +290,22 @@ Please provide threats that are directly relevant to this risk and could realist
280
  try:
281
  result = generate_response(system_prompt, user_message)
282
 
 
 
 
 
 
 
 
 
 
 
283
  # Extract JSON from the response
284
- json_start = result.find('{')
285
- json_end = result.rfind('}') + 1
286
 
287
  if json_start != -1 and json_end > json_start:
288
- json_str = result[json_start:json_end]
289
  threats_data = json.loads(json_str)
290
 
291
  threats = [Threat(**threat) for threat in threats_data.get("threats", [])]
 
83
  """
84
  Generate comprehensive enterprise risks based on category and department
85
  """
86
+ system_prompt = """You are an expert enterprise risk analyst. Your task is to generate comprehensive risks for organizations based on the provided category, department, and business context.
87
+
88
+ CRITICAL: You must respond with ONLY a valid JSON object. Do not include any markdown formatting, code blocks, or additional text.
89
 
90
  For each risk, you need to:
91
  1. Create a clear, specific risk name
 
112
  - Technology adoption patterns
113
  - Business model vulnerabilities
114
 
115
+ RESPOND WITH ONLY THIS EXACT JSON FORMAT (no markdown, no code blocks, no additional text):
116
  {
117
  "risks": [
118
  {
 
132
  ]
133
  }
134
  ]
135
+ }"""
 
136
 
137
  user_message = f"""
138
  Generate {request.number_of_risks} enterprise risks for the following context:
 
148
  try:
149
  result = generate_response(system_prompt, user_message)
150
 
151
+ # Clean the response - remove markdown code blocks if present
152
+ cleaned_result = result.strip()
153
+ if cleaned_result.startswith('```json'):
154
+ cleaned_result = cleaned_result[7:] # Remove ```json
155
+ elif cleaned_result.startswith('```'):
156
+ cleaned_result = cleaned_result[3:] # Remove ```
157
+ if cleaned_result.endswith('```'):
158
+ cleaned_result = cleaned_result[:-3] # Remove trailing ```
159
+ cleaned_result = cleaned_result.strip()
160
+
161
  # Extract JSON from the response
162
+ json_start = cleaned_result.find('{')
163
+ json_end = cleaned_result.rfind('}') + 1
164
 
165
  if json_start != -1 and json_end > json_start:
166
+ json_str = cleaned_result[json_start:json_end]
167
  risks_data = json.loads(json_str)
168
 
169
  # Convert to our response format
 
237
  """
238
  Generate specific threats for a given risk
239
  """
240
+ system_prompt = """You are an expert threat analyst. Your task is to generate specific threats that could lead to or contribute to a given risk.
241
+
242
+ CRITICAL: You must respond with ONLY a valid JSON object. Do not include any markdown formatting, code blocks, or additional text.
243
 
244
  For each threat, provide:
245
  1. A clear, specific threat name
 
266
  - Supply chain and third-party risks
267
  - Insider threat patterns specific to the department
268
 
269
+ RESPOND WITH ONLY THIS EXACT JSON FORMAT (no markdown, no code blocks, no additional text):
270
  {
271
  "threats": [
272
  {
 
275
  "justification": "Industry-specific reasoning for why this threat is particularly relevant, including statistics, trends, regulatory factors, or common occurrences in this sector and department"
276
  }
277
  ]
278
+ }"""
 
279
 
280
  user_message = f"""
281
  Generate {request.number_of_threats} specific threats for the following risk:
 
290
  try:
291
  result = generate_response(system_prompt, user_message)
292
 
293
+ # Clean the response - remove markdown code blocks if present
294
+ cleaned_result = result.strip()
295
+ if cleaned_result.startswith('```json'):
296
+ cleaned_result = cleaned_result[7:] # Remove ```json
297
+ elif cleaned_result.startswith('```'):
298
+ cleaned_result = cleaned_result[3:] # Remove ```
299
+ if cleaned_result.endswith('```'):
300
+ cleaned_result = cleaned_result[:-3] # Remove trailing ```
301
+ cleaned_result = cleaned_result.strip()
302
+
303
  # Extract JSON from the response
304
+ json_start = cleaned_result.find('{')
305
+ json_end = cleaned_result.rfind('}') + 1
306
 
307
  if json_start != -1 and json_end > json_start:
308
+ json_str = cleaned_result[json_start:json_end]
309
  threats_data = json.loads(json_str)
310
 
311
  threats = [Threat(**threat) for threat in threats_data.get("threats", [])]
threat_ra.py CHANGED
@@ -81,8 +81,9 @@ def generate_threat_risks(request: ThreatRiskGenerationRequest):
81
  """
82
  Generate comprehensive threat risk records for threat risk assessment
83
  """
84
- system_prompt = """
85
- You are an expert threat risk analyst. Your task is to generate comprehensive threat risk records that include domain-specific risks, threats, vulnerabilities, and their assessments.
 
86
 
87
  For each threat risk record, you need to:
88
  1. Create a specific risk name relevant to the domain
@@ -111,7 +112,7 @@ Provide specific justifications that reference:
111
  - Technology adoption risks
112
  - Operational and process weaknesses
113
 
114
- Respond strictly in this JSON format:
115
  {
116
  "threatRisks": [
117
  {
@@ -126,8 +127,7 @@ Respond strictly in this JSON format:
126
  "impact_justification": "Specific reasons for this impact score based on business dependencies and potential consequences"
127
  }
128
  ]
129
- }
130
- """
131
 
132
  user_message = f"""
133
  Generate {request.number_of_records} threat risk records for the following context:
@@ -143,12 +143,22 @@ Please provide comprehensive threat risk records that include specific risks, th
143
  try:
144
  result = generate_response(system_prompt, user_message)
145
 
 
 
 
 
 
 
 
 
 
 
146
  # Extract JSON from the response
147
- json_start = result.find('{')
148
- json_end = result.rfind('}') + 1
149
 
150
  if json_start != -1 and json_end > json_start:
151
- json_str = result[json_start:json_end]
152
  risks_data = json.loads(json_str)
153
 
154
  # Convert to our response format
@@ -222,8 +232,9 @@ def analyze_threat_risk(request: ThreatRiskAnalysisRequest):
222
  """
223
  Provide detailed analysis and recommendations for a specific threat risk scenario
224
  """
225
- system_prompt = """
226
- You are an expert threat risk analyst. Your task is to provide detailed analysis and recommendations for a specific threat risk scenario.
 
227
 
228
  Analyze the provided threat risk scenario and provide:
229
  1. Likelihood assessment (1-5 scale) with detailed justification
@@ -252,7 +263,7 @@ Provide specific justifications that reference:
252
  - Technology-specific risk factors
253
  - Geographic and sector-specific considerations
254
 
255
- Respond strictly in this JSON format:
256
  {
257
  "analysis": {
258
  "likelihood": 3,
@@ -265,8 +276,7 @@ Respond strictly in this JSON format:
265
  "Specific recommendation 2 with regulatory reference",
266
  "Specific recommendation 3 with cost-benefit analysis"
267
  ]
268
- }
269
- """
270
 
271
  user_message = f"""
272
  Analyze the following threat risk scenario:
@@ -283,12 +293,22 @@ Please provide a comprehensive analysis including likelihood and impact assessme
283
  try:
284
  result = generate_response(system_prompt, user_message)
285
 
 
 
 
 
 
 
 
 
 
 
286
  # Extract JSON from the response
287
- json_start = result.find('{')
288
- json_end = result.rfind('}') + 1
289
 
290
  if json_start != -1 and json_end > json_start:
291
- json_str = result[json_start:json_end]
292
  analysis_data = json.loads(json_str)
293
 
294
  # Extract analysis data
 
81
  """
82
  Generate comprehensive threat risk records for threat risk assessment
83
  """
84
+ system_prompt = """You are an expert threat risk analyst. Your task is to generate comprehensive threat risk records that include domain-specific risks, threats, vulnerabilities, and their assessments.
85
+
86
+ CRITICAL: You must respond with ONLY a valid JSON object. Do not include any markdown formatting, code blocks, or additional text.
87
 
88
  For each threat risk record, you need to:
89
  1. Create a specific risk name relevant to the domain
 
112
  - Technology adoption risks
113
  - Operational and process weaknesses
114
 
115
+ RESPOND WITH ONLY THIS EXACT JSON FORMAT (no markdown, no code blocks, no additional text):
116
  {
117
  "threatRisks": [
118
  {
 
127
  "impact_justification": "Specific reasons for this impact score based on business dependencies and potential consequences"
128
  }
129
  ]
130
+ }"""
 
131
 
132
  user_message = f"""
133
  Generate {request.number_of_records} threat risk records for the following context:
 
143
  try:
144
  result = generate_response(system_prompt, user_message)
145
 
146
+ # Clean the response - remove markdown code blocks if present
147
+ cleaned_result = result.strip()
148
+ if cleaned_result.startswith('```json'):
149
+ cleaned_result = cleaned_result[7:] # Remove ```json
150
+ elif cleaned_result.startswith('```'):
151
+ cleaned_result = cleaned_result[3:] # Remove ```
152
+ if cleaned_result.endswith('```'):
153
+ cleaned_result = cleaned_result[:-3] # Remove trailing ```
154
+ cleaned_result = cleaned_result.strip()
155
+
156
  # Extract JSON from the response
157
+ json_start = cleaned_result.find('{')
158
+ json_end = cleaned_result.rfind('}') + 1
159
 
160
  if json_start != -1 and json_end > json_start:
161
+ json_str = cleaned_result[json_start:json_end]
162
  risks_data = json.loads(json_str)
163
 
164
  # Convert to our response format
 
232
  """
233
  Provide detailed analysis and recommendations for a specific threat risk scenario
234
  """
235
+ system_prompt = """You are an expert threat risk analyst. Your task is to provide detailed analysis and recommendations for a specific threat risk scenario.
236
+
237
+ CRITICAL: You must respond with ONLY a valid JSON object. Do not include any markdown formatting, code blocks, or additional text.
238
 
239
  Analyze the provided threat risk scenario and provide:
240
  1. Likelihood assessment (1-5 scale) with detailed justification
 
263
  - Technology-specific risk factors
264
  - Geographic and sector-specific considerations
265
 
266
+ RESPOND WITH ONLY THIS EXACT JSON FORMAT (no markdown, no code blocks, no additional text):
267
  {
268
  "analysis": {
269
  "likelihood": 3,
 
276
  "Specific recommendation 2 with regulatory reference",
277
  "Specific recommendation 3 with cost-benefit analysis"
278
  ]
279
+ }"""
 
280
 
281
  user_message = f"""
282
  Analyze the following threat risk scenario:
 
293
  try:
294
  result = generate_response(system_prompt, user_message)
295
 
296
+ # Clean the response - remove markdown code blocks if present
297
+ cleaned_result = result.strip()
298
+ if cleaned_result.startswith('```json'):
299
+ cleaned_result = cleaned_result[7:] # Remove ```json
300
+ elif cleaned_result.startswith('```'):
301
+ cleaned_result = cleaned_result[3:] # Remove ```
302
+ if cleaned_result.endswith('```'):
303
+ cleaned_result = cleaned_result[:-3] # Remove trailing ```
304
+ cleaned_result = cleaned_result.strip()
305
+
306
  # Extract JSON from the response
307
+ json_start = cleaned_result.find('{')
308
+ json_end = cleaned_result.rfind('}') + 1
309
 
310
  if json_start != -1 and json_end > json_start:
311
+ json_str = cleaned_result[json_start:json_end]
312
  analysis_data = json.loads(json_str)
313
 
314
  # Extract analysis data