debug_helpers.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. """Shared per-tool debug session: records tool calls to a JSON log when a
  2. tool-specific env var (e.g. WEB_TOOLS_DEBUG=true) is set; no-ops otherwise."""
  3. import datetime
  4. import json
  5. import logging
  6. import os
  7. import uuid
  8. from typing import Any, Dict
  9. from hermes_constants import get_hermes_home
  10. logger = logging.getLogger(__name__)
  11. def _now() -> str:
  12. return datetime.datetime.now().isoformat()
  13. class DebugSession:
  14. """Per-tool debug session that records tool calls to a JSON log file."""
  15. def __init__(self, tool_name: str, *, env_var: str) -> None:
  16. self.tool_name = tool_name
  17. self.enabled = os.getenv(env_var, "false").lower() == "true"
  18. self.session_id = str(uuid.uuid4()) if self.enabled else ""
  19. self.log_dir = get_hermes_home() / "logs"
  20. self._calls: list[dict[str, Any]] = []
  21. self._start_time = _now() if self.enabled else ""
  22. if self.enabled:
  23. self.log_dir.mkdir(parents=True, exist_ok=True)
  24. logger.debug("%s debug mode enabled - Session ID: %s", tool_name, self.session_id)
  25. @property
  26. def active(self) -> bool:
  27. return self.enabled
  28. def log_call(self, call_name: str, call_data: dict[str, Any]) -> None:
  29. """Append a tool-call entry to the in-memory log."""
  30. if self.enabled:
  31. self._calls.append({"timestamp": _now(), "tool_name": call_name, **call_data})
  32. def save(self) -> None:
  33. """Flush the in-memory log to a JSON file in the logs directory."""
  34. if not self.enabled:
  35. return
  36. try:
  37. filepath = self.log_dir / f"{self.tool_name}_debug_{self.session_id}.json"
  38. payload = {
  39. "session_id": self.session_id, "start_time": self._start_time, "end_time": _now(),
  40. "debug_enabled": True, "total_calls": len(self._calls), "tool_calls": self._calls}
  41. with open(filepath, "w", encoding="utf-8") as f:
  42. json.dump(payload, f, indent=2, ensure_ascii=False)
  43. logger.debug("%s debug log saved: %s", self.tool_name, filepath)
  44. except Exception as e:
  45. logger.error("Error saving %s debug log: %s", self.tool_name, e)