BackDoorBuster/detection/GPTdetection.py
tritium0041 18454a0228
Some checks failed
Python application test / build (pull_request) Failing after 12m34s
feat:更改代码分布,实现模块化添加功能
2024-04-28 21:53:43 +08:00

40 lines
1.7 KiB
Python

import json
import os
from .utils import *
import openai
def detectGPT(content: str):
client = openai.OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
text = content
# client = openai.OpenAI(api_key="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") #测试用key
response = client.chat.completions.create(
messages=[
{
"role": "system",
"content": "You are a Python code reviewer.Read the code below and identify any potential security vulnerabilities. Classify them by risk level (high, medium, low, none). Only report the line number and the risk level.\nYou should output the result as json format in one line. For example: "
'[{"Line": {the line number}, "Risk": "{choose from (high,medium,low)}","Reason":"{how it is vulnable}"}] Each of these three field is required.\n'
"You are required to only output the json format. Do not output any other information.\n",
},
{
"role": "user",
"content": text,
},
],
model="gpt-3.5-turbo",
)
try:
message_content = response.choices[0].message.content
if message_content is None:
raise ValueError("API response content is None")
res_json = json.loads(message_content)
except json.JSONDecodeError:
raise ValueError("Error: Could not parse the response. Please try again.")
classified_results = {"high": [], "medium": [], "low": [], "none": []}
for res in res_json:
classified_results[res["Risk"]].append(
(res["Line"], text.split("\n")[res["Line"] - 1].strip())
)
return classified_results