Yaswanth-Bolla commited on
Commit
8202192
·
1 Parent(s): 1f51659
Files changed (1) hide show
  1. business_continuity.py +26 -54
business_continuity.py CHANGED
@@ -122,56 +122,26 @@ class RecoveryStrategiesResponse(BaseModel):
122
  def clean_json_response(response_text: str) -> str:
123
  """Clean and extract JSON from API response"""
124
  logger.info("Cleaning JSON response")
125
-
126
  if not response_text:
127
  logger.error("Empty response text provided")
128
  raise ValueError("Empty response text")
129
-
130
- # Remove common markdown formatting
131
  cleaned = response_text.strip()
132
-
133
- # Remove code blocks more aggressively
134
  patterns = [
135
- r'```json\s*', # Matches opening fence with optional spaces after ```json
136
- r'```', # Matches closing or generic triple backticks
137
  ]
138
  for pattern in patterns:
139
  cleaned = re.sub(pattern, '', cleaned, flags=re.MULTILINE | re.DOTALL)
140
-
141
  cleaned = cleaned.strip()
142
-
143
- # Try to find complete JSON by counting braces
144
- json_start = cleaned.find('{')
145
- if json_start == -1:
146
- logger.error(f"No opening brace found. Response preview: {cleaned[:300]}...")
147
- raise ValueError("No JSON opening brace found in response")
148
-
149
- # Count braces to find the matching closing brace
150
- brace_count = 0
151
- json_end = -1
152
-
153
- for i in range(json_start, len(cleaned)):
154
- if cleaned[i] == '{':
155
- brace_count += 1
156
- elif cleaned[i] == '}':
157
- brace_count -= 1
158
- if brace_count == 0:
159
- json_end = i
160
- break
161
-
162
- if json_end == -1:
163
- logger.error(f"No matching closing brace found. Response preview: {cleaned[:500]}...")
164
- # Try using the last closing brace as fallback
165
- json_end = cleaned.rfind('}')
166
- if json_end == -1 or json_end <= json_start:
167
- raise ValueError("No valid JSON structure found in response")
168
-
169
- json_str = cleaned[json_start:json_end + 1]
170
  logger.info(f"Extracted JSON length: {len(json_str)}")
171
  logger.info(f"JSON preview: {json_str[:150]}...")
172
  logger.info(f"JSON ending: ...{json_str[-50:]}")
173
-
174
- # Validate that it's at least syntactically correct JSON
175
  try:
176
  json.loads(json_str)
177
  logger.info("JSON syntax validation passed")
@@ -179,7 +149,6 @@ def clean_json_response(response_text: str) -> str:
179
  logger.error(f"JSON syntax validation failed: {str(e)}")
180
  logger.error(f"Problematic JSON: {json_str}")
181
  raise ValueError(f"Invalid JSON syntax: {str(e)}")
182
-
183
  return json_str
184
 
185
 
@@ -262,23 +231,26 @@ def generate_recovery_strategies(request: BusinessContinuityRequest):
262
 
263
  system_prompt = """You are an expert business continuity consultant. Your task is to generate specific, actionable recovery strategies for business processes.
264
 
265
- CRITICAL INSTRUCTIONS:
266
- 1. Respond with ONLY a valid JSON object
267
- 2. Do not include any markdown formatting, code blocks, or additional text
268
- 3. Each strategy must be 2-3 detailed sentences with specific actionable steps
269
- 4. Each reasoning must be 1-2 sentences explaining why the strategy fits the specific process
 
270
 
271
- Required JSON format (no deviations allowed):
 
272
  {
273
- "people_unavailability_strategy": "Detailed strategy for handling personnel unavailability with specific steps",
274
- "people_reasoning": "Clear explanation of why this strategy suits this specific process",
275
- "technology_data_unavailability_strategy": "Comprehensive strategy for technology and data failures with actionable steps",
276
- "technology_reasoning": "Explanation of why this technology strategy is appropriate for this process",
277
- "site_unavailability_strategy": "Detailed strategy for site/facility unavailability with specific actions",
278
- "site_reasoning": "Why this site strategy is suitable for this specific process",
279
- "third_party_vendors_unavailability_strategy": "Comprehensive strategy for vendor/supplier disruptions",
280
- "vendor_reasoning": "Why this vendor strategy is appropriate for this process"
281
- }"""
 
282
 
283
  user_message = f"""Generate business continuity recovery strategies for this specific process:
284
 
 
122
  def clean_json_response(response_text: str) -> str:
123
  """Clean and extract JSON from API response"""
124
  logger.info("Cleaning JSON response")
 
125
  if not response_text:
126
  logger.error("Empty response text provided")
127
  raise ValueError("Empty response text")
 
 
128
  cleaned = response_text.strip()
 
 
129
  patterns = [
130
+ r'```json\s*',
131
+ r'```',
132
  ]
133
  for pattern in patterns:
134
  cleaned = re.sub(pattern, '', cleaned, flags=re.MULTILINE | re.DOTALL)
 
135
  cleaned = cleaned.strip()
136
+ # Use regex to extract the first valid JSON object
137
+ match = re.search(r'\{[\s\S]*\}', cleaned)
138
+ if not match:
139
+ logger.error(f"No JSON object found. Response preview: {cleaned[:300]}...")
140
+ raise ValueError("No JSON object found in response")
141
+ json_str = match.group(0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
  logger.info(f"Extracted JSON length: {len(json_str)}")
143
  logger.info(f"JSON preview: {json_str[:150]}...")
144
  logger.info(f"JSON ending: ...{json_str[-50:]}")
 
 
145
  try:
146
  json.loads(json_str)
147
  logger.info("JSON syntax validation passed")
 
149
  logger.error(f"JSON syntax validation failed: {str(e)}")
150
  logger.error(f"Problematic JSON: {json_str}")
151
  raise ValueError(f"Invalid JSON syntax: {str(e)}")
 
152
  return json_str
153
 
154
 
 
231
 
232
  system_prompt = """You are an expert business continuity consultant. Your task is to generate specific, actionable recovery strategies for business processes.
233
 
234
+ **CRITICAL INSTRUCTIONS:**
235
+ 1. **MUST** respond with a single, valid JSON object and nothing else.
236
+ 2. The JSON object must be the only content in your response. Do not include any text, explanations, or markdown formatting (like ```json) before or after the JSON object.
237
+ 3. Ensure the JSON is perfectly formed with correct syntax, including matching curly braces, quoted keys, and properly escaped string values.
238
+ 4. Each strategy must be 2-3 detailed sentences with specific, actionable steps.
239
+ 5. Each reasoning must be 1-2 sentences explaining why the strategy fits the specific process.
240
 
241
+ **Required JSON format (no deviations allowed):**
242
+ ```json
243
  {
244
+ "people_unavailability_strategy": "Detailed strategy for handling personnel unavailability with specific steps.",
245
+ "people_reasoning": "Clear explanation of why this strategy suits this specific process.",
246
+ "technology_data_unavailability_strategy": "Comprehensive strategy for technology and data failures with actionable steps.",
247
+ "technology_reasoning": "Explanation of why this technology strategy is appropriate for this process.",
248
+ "site_unavailability_strategy": "Detailed strategy for site/facility unavailability with specific actions.",
249
+ "site_reasoning": "Why this site strategy is suitable for this specific process.",
250
+ "third_party_vendors_unavailability_strategy": "Comprehensive strategy for vendor/supplier disruptions.",
251
+ "vendor_reasoning": "Why this vendor strategy is appropriate for this process."
252
+ }
253
+ ```"""
254
 
255
  user_message = f"""Generate business continuity recovery strategies for this specific process:
256