duplicati_analysis_server_openai.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. from http.server import BaseHTTPRequestHandler, HTTPServer
  2. from urllib.parse import parse_qs
  3. import json
  4. import logging
  5. from datetime import datetime
  6. from openai import OpenAI # OpenAI Python client
  7. # Configure logging
  8. logging.basicConfig(
  9. filename="duplicati_logs.log",
  10. level=logging.INFO,
  11. format="%(asctime)s - %(message)s",
  12. )
  13. # OpenAI API configuration
  14. API_KEY = "sk-175159668af9430ea6208f5636b24198" # Replace with your OpenAI API key
  15. MODEL = "deepseek-chat"
  16. class DuplicatiLogHandler(BaseHTTPRequestHandler):
  17. def do_POST(self):
  18. # Get the length of the data
  19. content_length = int(self.headers["Content-Length"])
  20. # Read the POST data
  21. post_data = self.rfile.read(content_length).decode("utf-8")
  22. # Parse the form-urlencoded data
  23. data = parse_qs(post_data)
  24. # Log the data
  25. self.log_data(data)
  26. # Send the log message to OpenAI API for analysis
  27. analysis_result, diagnostic_message = self.send_to_openai(data)
  28. if analysis_result:
  29. logging.info(f"OpenAI Analysis Result: {analysis_result}")
  30. if diagnostic_message:
  31. logging.info(f"Diagnostic Message: {diagnostic_message}")
  32. # Send a response
  33. self.send_response(200)
  34. self.send_header("Content-type", "application/json")
  35. self.end_headers()
  36. response = {
  37. "status": "success",
  38. "message": "Log received",
  39. "analysis_result": analysis_result,
  40. "diagnostic_message": diagnostic_message,
  41. }
  42. self.wfile.write(json.dumps(response).encode("utf-8"))
  43. def log_data(self, data):
  44. """Log the received data to a file."""
  45. log_entry = {
  46. "timestamp": datetime.now().isoformat(),
  47. "data": data,
  48. }
  49. logging.info(json.dumps(log_entry))
  50. def send_to_openai(self, data):
  51. """Send the raw log data to OpenAI API for analysis."""
  52. try:
  53. # Prepare the messages for OpenAI API
  54. messages = [
  55. {
  56. "role": "system",
  57. "content": "You are an operator analyzing backup logs. "
  58. "Check the log message for abnormalities and respond with 'normal' or 'abnormal'. "
  59. "If the backup is abnormal, provide a detailed diagnostic message explaining the issue and suggesting possible fixes.",
  60. },
  61. {
  62. "role": "user",
  63. "content": json.dumps(data), # Pass the raw data as a JSON string
  64. },
  65. ]
  66. # Make a request to OpenAI API
  67. client = OpenAI(api_key=API_KEY, base_url="https://api.deepseek.com")
  68. response = client.chat.completions.create(
  69. model=MODEL,
  70. messages=messages,
  71. max_tokens=1024,
  72. temperature=0.7,
  73. stream=False
  74. )
  75. # Parse the response
  76. chat_response = response.choices[0].message.content
  77. # Extract analysis result and diagnostic message
  78. if "abnormal" in chat_response.lower():
  79. analysis_result = "abnormal"
  80. diagnostic_message = chat_response # Use the full response as the diagnostic message
  81. else:
  82. analysis_result = "normal"
  83. diagnostic_message = chat_response
  84. return analysis_result, diagnostic_message
  85. except Exception as e:
  86. logging.error(f"Failed to send data to OpenAI API: {e}")
  87. return None, None
  88. def run(server_class=HTTPServer, handler_class=DuplicatiLogHandler, port=8680):
  89. server_address = ("", port)
  90. httpd = server_class(server_address, handler_class)
  91. print(f"Starting Duplicati log server on port {port}...")
  92. httpd.serve_forever()
  93. if __name__ == "__main__":
  94. run()