Rivalcoder commited on
Commit
6ce5004
·
verified ·
1 Parent(s): 6e3073a

Update app/services/risk_analyzer.py

Browse files
Files changed (1) hide show
  1. app/services/risk_analyzer.py +19 -28
app/services/risk_analyzer.py CHANGED
@@ -3,30 +3,27 @@ from app.config import settings
3
  from app.services.risk_scorer import RISK_DEFINITIONS
4
  import json
5
  import re
6
- from typing import Dict, List
7
 
8
 
9
- # Configure the Gemini API
10
  genai.configure(api_key=settings.GEMINI_API_KEY)
11
 
12
 
13
  def analyze_clause_with_gemini(clause_text: str) -> Dict:
14
  """
15
- Analyze a contract clause using Google Gemini AI for risk identification.
16
-
17
  Args:
18
- clause_text: The text of the clause to analyze
19
-
20
  Returns:
21
  Dictionary containing identified risk IDs and suggestions
22
  """
23
 
24
- # Create the detailed prompt for Gemini
25
  prompt = f"""
26
  You are an expert Indian legal consultant specializing in contract analysis and risk assessment.
27
- Analyze the following contract clause and identify any legal risks based on the predefined risk categories.
28
 
29
- CONTRACT CLAUSE TO ANALYZE:
30
  {clause_text}
31
 
32
  RISK CATEGORIES TO CHECK FOR:
@@ -36,64 +33,59 @@ RISK CATEGORIES TO CHECK FOR:
36
  4. DPDP_NON_COMPLIANCE: Data protection clause may not comply with the DPDP Act 2023
37
 
38
  INSTRUCTIONS:
39
- 1. Carefully read the clause text
40
- 2. Identify which of the above risk categories apply to this clause
41
- 3. For each identified risk, provide a brief explanation
42
- 4. Suggest a compliant alternative or modification for any identified risks
43
  5. If no risks are found, respond with "No risks identified"
44
 
45
- RESPONSE FORMAT (JSON):
46
  {{
47
  "risks": [
48
  {{
49
  "risk_id": "RISK_CATEGORY_ID",
50
- "explanation": "Brief explanation of why this risk applies"
51
  }}
52
  ],
53
- "suggestion": "Compliant alternative or modification suggestion"
54
  }}
55
 
56
  If no risks are identified, return:
57
  {{
58
  "risks": [],
59
- "suggestion": "No risks identified - clause appears compliant"
60
  }}
61
  """
62
 
63
  try:
64
- # Initialize the Gemini model
65
- model = genai.GenerativeModel('gemini-2.5-flash-lite')
66
 
67
  # Generate response
68
  response = model.generate_content(prompt)
69
-
70
- # Extract the text response
71
  response_text = response.text.strip()
72
 
73
  # Try to parse JSON from the response
74
  try:
75
- # Look for JSON in the response (sometimes Gemini includes extra text)
76
- json_match = re.search(r'\{.*\}', response_text, re.DOTALL)
77
  if json_match:
78
  json_str = json_match.group()
79
  result = json.loads(json_str)
80
  else:
81
- # Fallback: try to parse the entire response as JSON
82
  result = json.loads(response_text)
83
  except json.JSONDecodeError:
84
- # If JSON parsing fails, create a fallback response
85
  result = {
86
  "risks": [],
87
  "suggestion": "Unable to parse AI response - manual review recommended"
88
  }
89
 
90
- # Validate and clean the response
91
  if "risks" not in result:
92
  result["risks"] = []
93
  if "suggestion" not in result:
94
  result["suggestion"] = "No suggestion provided"
95
 
96
- # Validate risk IDs
97
  valid_risks = []
98
  for risk in result["risks"]:
99
  if isinstance(risk, dict) and "risk_id" in risk:
@@ -102,7 +94,6 @@ If no risks are identified, return:
102
  valid_risks.append(risk)
103
 
104
  result["risks"] = valid_risks
105
-
106
  return result
107
 
108
  except Exception as e:
 
3
  from app.services.risk_scorer import RISK_DEFINITIONS
4
  import json
5
  import re
6
+ from typing import Dict
7
 
8
 
9
+ # Configure Gemini API
10
  genai.configure(api_key=settings.GEMINI_API_KEY)
11
 
12
 
13
  def analyze_clause_with_gemini(clause_text: str) -> Dict:
14
  """
15
+ Analyze a contract (clause or full text) using Google Gemini AI for risk identification.
 
16
  Args:
17
+ clause_text: The text of the clause or contract to analyze
 
18
  Returns:
19
  Dictionary containing identified risk IDs and suggestions
20
  """
21
 
 
22
  prompt = f"""
23
  You are an expert Indian legal consultant specializing in contract analysis and risk assessment.
24
+ Analyze the following contract text and identify any legal risks based on the predefined categories.
25
 
26
+ CONTRACT TEXT TO ANALYZE:
27
  {clause_text}
28
 
29
  RISK CATEGORIES TO CHECK FOR:
 
33
  4. DPDP_NON_COMPLIANCE: Data protection clause may not comply with the DPDP Act 2023
34
 
35
  INSTRUCTIONS:
36
+ 1. Carefully read the contract text
37
+ 2. Identify which of the above risk categories apply
38
+ 3. For each identified risk, provide a **short explanation (max 1–2 lines, no long paragraphs)**
39
+ 4. Suggest a **brief compliant alternative (1–2 lines)**
40
  5. If no risks are found, respond with "No risks identified"
41
 
42
+ RESPONSE FORMAT (strict JSON only):
43
  {{
44
  "risks": [
45
  {{
46
  "risk_id": "RISK_CATEGORY_ID",
47
+ "explanation": "1–2 line explanation of why this risk applies"
48
  }}
49
  ],
50
+ "suggestion": "1–2 line compliant alternative or modification suggestion"
51
  }}
52
 
53
  If no risks are identified, return:
54
  {{
55
  "risks": [],
56
+ "suggestion": "No risks identified - contract appears compliant"
57
  }}
58
  """
59
 
60
  try:
61
+ # Initialize Gemini model
62
+ model = genai.GenerativeModel("gemini-2.5-flash-lite")
63
 
64
  # Generate response
65
  response = model.generate_content(prompt)
 
 
66
  response_text = response.text.strip()
67
 
68
  # Try to parse JSON from the response
69
  try:
70
+ json_match = re.search(r"\{.*\}", response_text, re.DOTALL)
 
71
  if json_match:
72
  json_str = json_match.group()
73
  result = json.loads(json_str)
74
  else:
 
75
  result = json.loads(response_text)
76
  except json.JSONDecodeError:
 
77
  result = {
78
  "risks": [],
79
  "suggestion": "Unable to parse AI response - manual review recommended"
80
  }
81
 
82
+ # Ensure required keys exist
83
  if "risks" not in result:
84
  result["risks"] = []
85
  if "suggestion" not in result:
86
  result["suggestion"] = "No suggestion provided"
87
 
88
+ # Validate risk IDs against known definitions
89
  valid_risks = []
90
  for risk in result["risks"]:
91
  if isinstance(risk, dict) and "risk_id" in risk:
 
94
  valid_risks.append(risk)
95
 
96
  result["risks"] = valid_risks
 
97
  return result
98
 
99
  except Exception as e: