Agents Package

All agent implementations and base classes. This documentation is auto-generated from Python docstrings.

Package Overview

HemoStat Agents Package

Provides all four agent implementations for the HemoStat autonomous container health monitoring system:

  • Monitor Agent: Continuously polls Docker containers for health issues

  • Analyzer Agent: Performs AI-powered root cause analysis

  • Responder Agent: Executes safe remediation actions with safety constraints

  • Alert Agent: Sends notifications and stores events for dashboard consumption

All agents inherit from HemoStatAgent base class and communicate via Redis pub/sub.

Base Agent Class

Foundation for all agents. Provides Redis pub/sub communication and shared state management.

HemoStat Base Agent Module

Provides the foundational HemoStatAgent base class that all specialized agents inherit from. Encapsulates Redis pub/sub communication patterns and shared state management.

class agents.agent_base.HemoStatAgent(agent_name, redis_host=None, redis_port=None, redis_db=0)[source]

Bases: object

Base class for all HemoStat agents.

Encapsulates Redis pub/sub communication and shared state management. All specialized agents (Monitor, Analyzer, Responder, Alert) inherit from this class.

__init__(agent_name, redis_host=None, redis_port=None, redis_db=0)[source]

Initialize the HemoStat agent.

Parameters:
  • agent_name (str) – Unique identifier for this agent (e.g., ‘monitor’, ‘analyzer’)

  • redis_host (str | None) – Redis server hostname (defaults to env REDIS_HOST or ‘redis’)

  • redis_port (int | None) – Redis server port (defaults to env REDIS_PORT or 6379)

  • redis_db (int) – Redis database number (default: 0)

Raises:

HemoStatConnectionError – If Redis connection fails after retries

classmethod from_env(agent_name)[source]

Create an agent instance from environment variables.

Reads REDIS_HOST, REDIS_PORT, and REDIS_DB from environment.

Parameters:

agent_name (str) – Name of the agent

Returns:

Initialized HemoStatAgent instance

Return type:

HemoStatAgent

get_shared_state(key)[source]

Retrieve shared state from Redis.

Parameters:

key (str) – State key (will be prefixed with ‘hemostat:state:’)

Returns:

Deserialized state dict, or None if key doesn’t exist or error occurs

Return type:

dict[str, Any] | None

property is_running: bool

Check if the agent is currently running.

Returns:

True if the agent is running, False otherwise

publish_event(channel, event_type, data)[source]

Publish a structured event to a Redis channel.

Parameters:
  • channel (str) – Redis channel name (e.g., ‘hemostat:events:health’)

  • event_type (str) – Type of event (e.g., ‘container_unhealthy’)

  • data (dict[str, Any]) – Event payload data

Returns:

True if publish succeeded, False otherwise

Return type:

bool

set_shared_state(key, value, ttl=None)[source]

Store shared state in Redis with optional TTL.

Parameters:
  • key (str) – State key (will be prefixed with ‘hemostat:state:’)

  • value (dict[str, Any]) – State data to store

  • ttl (int | None) – Time-to-live in seconds (optional)

Returns:

True if successful, False otherwise

Return type:

bool

start_listening()[source]

Start the pub/sub message listening loop.

Blocks until stop() is called. Handles messages and exceptions gracefully.

stop()[source]

Gracefully shut down the agent.

Stops the listening loop, unsubscribes from channels, and closes connections.

subscribe_to_channel(channel, callback)[source]

Subscribe to a Redis channel and register a message handler.

Parameters:
  • channel (str) – Redis channel name to subscribe to

  • callback (Callable[[dict[str, Any]], None]) – Callable that will be invoked for each message (receives deserialized message dict)

exception agents.agent_base.HemoStatConnectionError[source]

Bases: Exception

Custom exception for Redis connection failures.

Logger

Logging utilities for all agents.

HemoStat Custom Logger Module

Provides a centralized, comprehensive logging system for the HemoStat project. Supports multiple output formats (text, JSON), configurable log levels, and structured logging with contextual information.

class agents.logger.HemoStatLogger[source]

Bases: object

Centralized logger factory for HemoStat agents.

Provides consistent logging configuration across all agents with support for: - Multiple output formats (text, JSON) - Configurable log levels via environment variables - Structured logging with contextual information - Consistent formatting and naming conventions

classmethod configure_root_logger()[source]

Configure the root logger with basic settings.

Called once at application startup to set up root logger configuration.

classmethod get_logger(name)[source]

Get or create a logger with the given name.

Creates a new logger if it doesn’t exist, or returns the cached instance. All loggers are configured with consistent formatting and handlers.

Parameters:

name (str) – Logger name (typically agent name like ‘monitor’, ‘analyzer’, etc.)

Returns:

Configured logging.Logger instance

Return type:

Logger

classmethod reset()[source]

Reset all cached loggers and configuration.

Useful for testing or reconfiguration.

Platform Utilities

Platform detection and utilities.

HemoStat Platform Detection Utilities

Provides OS detection and platform-specific configuration for Docker socket handling. Supports Windows, Linux, and macOS with automatic detection of running environment.

agents.platform_utils.get_docker_host()[source]

Get the appropriate Docker daemon socket path for the current platform.

Logic:

  • If running in Docker container: always use unix:///var/run/docker.sock (Docker Desktop on Windows maps the named pipe to this path inside containers)

  • If running locally on Windows: use npipe:////./pipe/docker_engine

  • If running locally on Linux/macOS: use unix:///var/run/docker.sock

Returns:

Docker daemon socket path appropriate for the platform

Return type:

str

agents.platform_utils.get_platform()[source]

Get the current operating system name.

Returns:

‘Windows’, ‘Linux’, or ‘Darwin’ (macOS)

Return type:

str

agents.platform_utils.get_platform_display()[source]

Get a human-readable platform description for logging.

Returns:

Platform description string

Return type:

str

agents.platform_utils.is_in_docker()[source]

Detect if the current process is running inside a Docker container.

Returns:

True if running in Docker, False otherwise

Return type:

bool

Monitor Agent

Continuously monitors Docker container health and publishes alerts.

HemoStat Monitor Agent

Continuously polls Docker containers to detect health issues, resource anomalies, and failures. Publishes structured health alerts to Redis for consumption by the Analyzer Agent.

class agents.hemostat_monitor.monitor.ContainerMonitor[source]

Bases: HemoStatAgent

Monitor Agent for HemoStat.

Polls Docker containers at regular intervals, collects metrics (CPU, memory, network, disk I/O), detects anomalies against configurable thresholds, and publishes health alerts to Redis.

__init__()[source]

Initialize the Container Monitor agent.

Raises:
run()[source]

Main monitoring loop that runs continuously until stopped.

Polls containers at regular intervals and detects anomalies.

stop()[source]

Stop the monitor agent gracefully.

Analyzer Agent

Performs AI-powered root cause analysis on health alerts.

HemoStat Analyzer Agent - Core Implementation

Performs AI-powered root cause analysis of container health issues using LangChain with Claude/GPT-4, distinguishes real issues from false alarms, calculates confidence scores, and publishes remediation recommendations or false alarm notifications.

class agents.hemostat_analyzer.analyzer.HealthAnalyzer[source]

Bases: HemoStatAgent

AI-powered health analyzer for container health issues.

Inherits from HemoStatAgent and implements intelligent analysis of container health alerts using LangChain with Claude/GPT-4, with rule-based fallback for reliability.

__init__()[source]

Initialize the Health Analyzer.

Loads configuration from environment variables, initializes LangChain LLM, and subscribes to health alert channel.

Raises:

HemoStatConnectionError – If Redis connection fails

run()[source]

Start the analyzer listening loop.

Blocks until stop() is called. Handles exceptions gracefully.

Responder Agent

Executes safe remediation actions on containers.

HemoStat Responder Agent - Safe Container Remediation

Executes remediation actions recommended by the Analyzer Agent with comprehensive safety constraints including cooldown periods, circuit breakers, and audit logging.

class agents.hemostat_responder.responder.ContainerResponder[source]

Bases: HemoStatAgent

Executes safe container remediation with multi-layered safety mechanisms.

Subscribes to hemostat:remediation_needed channel and executes Docker operations (restart, scale, cleanup, exec) while enforcing cooldown periods, circuit breakers, and maintaining comprehensive audit logs.

__init__()[source]

Initialize the Responder Agent.

Connects to Docker daemon with retry logic, loads safety configuration from environment variables, and subscribes to remediation_needed channel.

Raises:

HemoStatConnectionError – If Redis connection fails

run()[source]

Start the message listening loop.

Blocks until stop() is called. Listens for remediation requests on hemostat:remediation_needed channel and processes them.

Alert Agent

Sends notifications and stores event history.

HemoStat Alert Agent - Event Storage and Notifications

Consumes remediation completion and false alarm events from the Responder and Analyzer agents. Sends formatted notifications to Slack webhooks, stores events in Redis for dashboard consumption, and implements event deduplication to prevent notification spam.

class agents.hemostat_alert.alert.AlertNotifier[source]

Bases: HemoStatAgent

Alert Agent for sending notifications and storing events.

Subscribes to remediation completion and false alarm events, sends Slack notifications, and stores events in Redis for dashboard consumption. Implements event deduplication using minute-level timestamps and event type hashing to prevent duplicate notifications within configurable TTL windows.

__init__()[source]

Initialize the Alert Agent.

Loads configuration from environment variables, subscribes to remediation completion and false alarm channels, and validates Slack webhook URL if provided.

Raises:

HemoStatConnectionError – If Redis connection fails

run()[source]

Start the message listening loop.

Blocks until stop() is called. Handles exceptions gracefully and logs errors.