#9 AI bira kontrole,i dinamicki se updejtuje document

This commit is contained in:
2025-02-14 17:52:51 +01:00
parent f917f0acff
commit 595b7a2a17
6 changed files with 156 additions and 30 deletions

View File

@@ -1,6 +1,7 @@
from openai import OpenAI
from django.conf import settings
from .models import Risk
from .models import Risk, Control, Document, DocumentRiskControl
from django.shortcuts import get_object_or_404
def extract_risk_factors(organization):
excluded_fields={"name","email"}
@@ -50,3 +51,52 @@ def get_top_risk(organization):
risk_ids = response.choices[0].message.content.strip().split(",")
return [int(risk_id) for risk_id in risk_ids if risk_id.isdigit()]
def get_controls_for_risk(risk):
client = OpenAI(api_key=settings.OPENAI_API_KEY)
all_controls = Control.objects.all()
control_list = []
for control in all_controls:
control_list.append(f"Control ID: {control.id}, Control Name: {control.name}")
prompt = f"""
You are a cyber security expert. For the risk '{risk.risk_name}', select 10 relevant controls
from the following list and assign a weight (1-10) based on how much they reduce risks.
Available Controls (only respond with control IDs and weights):
{control_list}
Respond only with control IDs (numbers) and their corresponding weights (1-10).
Format:
ID: <control_id> Weight: <weight>
Example:
1: 9
2: 6
3: 4
"""
response = client.chat.completions.create(
model="gpt-4",
messages=[{"role": "system", "content": prompt}]
)
result = response.choices[0].message.content.strip()
selected_controls = []
for line in result.split("\n"):
line = line.strip()
parts = line.split("Weight:")
if len(parts) == 2:
control_id_str = parts[0].replace("ID:", "").replace("id:", "").replace("Id:", "").strip()
weight_str = parts[1].strip().replace("Weight:", "").replace("weight:","").strip()
control_id_str = ''.join(filter(str.isdigit, control_id_str))
weight_str = ''.join(filter(str.isdigit, weight_str))
control_id = int(control_id_str)
weight = int(weight_str)
print(f"ID: {control_id}, Weight: {weight}")
control = Control.objects.filter(id=control_id).first()
if control:
selected_controls.append((control_id, weight))
return selected_controls[:10]