Skip to content

Commit 6280637

Browse files
authored
Create threat_intel_agent.py
1 parent 456d222 commit 6280637

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

ai_agents/threat_intel_agent.py

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import os
2+
import time
3+
import json
4+
from web3 import Web3
5+
from openai import OpenAI
6+
from dotenv import load_dotenv
7+
8+
# Load environment variables
9+
load_dotenv()
10+
INFURA_URL = os.getenv("INFURA_URL")
11+
PRIVATE_KEY = os.getenv("PRIVATE_KEY")
12+
THREAT_INTEL_CONTRACT_ADDRESS = os.getenv("THREAT_INTEL_CONTRACT_ADDRESS")
13+
THREAT_INTEL_ABI_PATH = os.getenv("THREAT_INTEL_ABI_PATH")
14+
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
15+
16+
# Load contract ABI
17+
with open(THREAT_INTEL_ABI_PATH) as f:
18+
THREAT_INTEL_ABI = json.load(f)
19+
20+
web3 = Web3(Web3.HTTPProvider(INFURA_URL))
21+
threat_intel = web3.eth.contract(address=THREAT_INTEL_CONTRACT_ADDRESS, abi=THREAT_INTEL_ABI)
22+
account = web3.eth.account.from_key(PRIVATE_KEY)
23+
openai = OpenAI(api_key=OPENAI_API_KEY)
24+
25+
def fetch_unvalidated_threats():
26+
total = threat_intel.functions.totalThreats().call()
27+
pending = []
28+
for i in range(1, total + 1):
29+
threat = threat_intel.functions.threats(i).call()
30+
if not threat[6]: # aiValidated == False
31+
pending.append((i, threat))
32+
return pending
33+
34+
def ai_assess_threat(target, description):
35+
prompt = (
36+
"You are an AI threat intelligence analyst. Assess the following threat, provide a concise risk assessment, "
37+
"and rate severity from 1 (Critical) to 5 (Low). Output JSON: {'assessment': ..., 'severity': ...}.\n"
38+
f"Target: {target}\nDescription: {description}"
39+
)
40+
response = openai.chat.completions.create(
41+
model="gpt-4o",
42+
messages=[{"role": "user", "content": prompt}],
43+
temperature=0.05,
44+
)
45+
return response.choices[0].message.content.strip()
46+
47+
def post_assessment(report_id, result_json):
48+
result = json.loads(result_json)
49+
severity = int(result["severity"])
50+
tx = threat_intel.functions.aiAssessThreat(
51+
report_id, result["assessment"], severity
52+
).build_transaction({
53+
'from': account.address,
54+
'nonce': web3.eth.get_transaction_count(account.address),
55+
'gas': 200_000,
56+
'gasPrice': web3.to_wei('30', 'gwei')
57+
})
58+
signed = web3.eth.account.sign_transaction(tx, private_key=account.key)
59+
tx_hash = web3.eth.send_raw_transaction(signed.rawTransaction)
60+
print(f"AI assessed threat {report_id}: {web3.to_hex(tx_hash)}")
61+
62+
def main():
63+
while True:
64+
for report_id, threat in fetch_unvalidated_threats():
65+
result_json = ai_assess_threat(threat[1], threat[2])
66+
post_assessment(report_id, result_json)
67+
time.sleep(300)
68+
69+
if __name__ == "__main__":
70+
main()

0 commit comments

Comments
 (0)