Files
agentic-soc-platform/Lib/baseapi.py
T

135 lines
5.3 KiB
Python
Raw Permalink Normal View History

2025-09-28 09:40:31 +08:00
import os
import sys
from abc import ABC
from langchain_core.prompts import SystemMessagePromptTemplate, HumanMessagePromptTemplate
from Lib.configs import DATA_DIR
from Lib.log import logger
class BaseAPI(ABC):
def __init__(self):
self.logger = logger
class _TemplateWrapper:
2025-12-18 20:26:28 +08:00
""" A template wrapper class hidden internally that does only one thing: provide .format()."""
2025-09-28 09:40:31 +08:00
def __init__(self, content: str):
self._content = content
def format(self, **kwargs) -> str:
2025-12-18 20:26:28 +08:00
""" Implement the .format() method you want. """
2025-09-28 09:40:31 +08:00
return self._content.format(**kwargs)
@staticmethod
def _get_main_script_name():
"""
2025-12-18 20:26:28 +08:00
Get the filename of the main execution script (without the extension).
sys.argv[0] always points to the script that was originally started, regardless of which module the current code is running in.
2025-09-28 09:40:31 +08:00
"""
try:
2025-12-18 20:26:28 +08:00
# 1. Get the full path of the main execution script
2025-09-28 09:40:31 +08:00
script_path = sys.argv[0]
2025-12-18 20:26:28 +08:00
# 2. Extract the file name from the full path
2025-09-28 09:40:31 +08:00
script_filename = os.path.basename(script_path)
2025-12-18 20:26:28 +08:00
# 3. Separate the file name and extension
2025-09-28 09:40:31 +08:00
script_name, _ = os.path.splitext(script_filename)
return script_name
except IndexError as e:
2025-12-18 20:26:28 +08:00
raise RuntimeError("Unable to get the name of the main execution script, sys.argv[0] does not exist.") from e
2025-09-28 09:40:31 +08:00
except Exception as e:
2025-12-18 20:26:28 +08:00
raise RuntimeError(f"An error occurred while getting the name of the main execution script: {e}") from e
2025-09-28 09:40:31 +08:00
@property
def module_name(self):
2025-12-18 20:26:28 +08:00
"""Get the module loading path"""
2025-09-28 09:40:31 +08:00
module_name = self.__module__.split(".")[-1]
if module_name == "__main__":
return self._get_main_script_name()
else:
return module_name
2025-12-02 14:08:09 +08:00
def _get_md_file_path(self, filename: str, lang=None) -> str:
2025-09-28 09:40:31 +08:00
"""
2025-12-18 20:26:28 +08:00
Get the file path based on the workbook name.
2025-09-28 09:40:31 +08:00
"""
if os.path.isfile(filename): # "/root/asf/ES-Rule-21-Phishing_user_report_mail/senior_phishing_expert.md"
template_path = filename
else:
if filename.endswith('.md'): # "senior_phishing_expert.md"
fname = filename
else:
2025-12-02 14:08:09 +08:00
if lang is not None:
fname = f"{filename}_{lang}.md" # "senior_phishing_expert_en"
else:
fname = f"{filename}.md" # "senior_phishing_expert"
2025-09-28 09:40:31 +08:00
if os.path.isfile(os.path.join(DATA_DIR, fname)): # "ES-Rule-21-Phishing_user_report_mail/senior_phishing_expert.md"
template_path = os.path.join(DATA_DIR, fname)
else:
template_path = os.path.join(DATA_DIR, self.module_name, fname)
return template_path
2025-12-12 04:30:20 +08:00
def _get_file_path(self, filename: str):
"""
2025-12-18 20:26:28 +08:00
Get the file path based on the workbook name.
2025-12-12 04:30:20 +08:00
"""
if os.path.isfile(filename): # "/root/asf/ES-Rule-21-Phishing_user_report_mail/senior_phishing_expert.md"
return filename
else:
if os.path.join(DATA_DIR, self.module_name, filename): # "ES-Rule-21-Phishing_user_report_mail/senior_phishing_expert.md"
template_path = os.path.join(DATA_DIR, self.module_name, filename)
return template_path
else:
raise Exception("File not exist")
2025-09-28 09:40:31 +08:00
def load_markdown_template(self, filename: str) -> _TemplateWrapper:
"""
2025-12-18 20:26:28 +08:00
Read the content according to the workbook name and return an object that supports .format().
2025-09-28 09:40:31 +08:00
"""
template_path = self._get_md_file_path(filename)
try:
with open(template_path, 'r', encoding='utf-8') as f:
content = f.read()
2025-12-18 20:26:28 +08:00
# Return an instance of an inner nested class
2025-09-28 09:40:31 +08:00
return self._TemplateWrapper(content)
except Exception as e:
logger.warning(f"Failed to load prompt template {template_path}: {str(e)}")
raise e
2025-12-02 14:08:09 +08:00
def load_system_prompt_template(self, filename, lang=None):
2025-12-18 20:26:28 +08:00
"""Load system prompt template"""
2025-12-02 14:08:09 +08:00
template_path = self._get_md_file_path(filename, lang=lang)
2025-09-28 09:40:31 +08:00
try:
with open(template_path, 'r', encoding='utf-8') as f:
system_prompt_template: SystemMessagePromptTemplate = SystemMessagePromptTemplate.from_template(f.read())
logger.debug(f"Loaded system prompt template from: {template_path}")
return system_prompt_template
except Exception as e:
logger.warning(f"Failed to load prompt template {template_path}: {str(e)}")
raise e
2025-12-02 14:08:09 +08:00
def load_human_prompt_template(self, filename, lang=None):
template_path = self._get_md_file_path(filename, lang=lang)
2025-09-28 09:40:31 +08:00
try:
with open(template_path, 'r', encoding='utf-8') as f:
human_prompt_template: HumanMessagePromptTemplate = HumanMessagePromptTemplate.from_template(f.read())
logger.debug(f"Loaded human prompt template from: {template_path}")
return human_prompt_template
except Exception as e:
logger.warning(f"Failed to load prompt template {template_path}: {str(e)}")
raise e
def run(self):
raise NotImplementedError