"""Simple random-action agent compatible with the Kinitro evaluator. This implementation keeps the contract defined by ``AgentInterface`` but intentionally avoids any expert policy logic. It produces uniformly random actions inside the environment's action space bounds while gracefully handling observation payloads that may include images or other auxiliary data. """ from __future__ import annotations import logging from typing import Any import gymnasium as gym import numpy as np import torch from agent_interface import AgentInterface class RLAgent(AgentInterface): """Example agent that emits random actions within the configured action space.""" def __init__( self, observation_space: gym.Space | None = None, action_space: gym.Space | None = None, seed: int | None = None, **kwargs: Any, ) -> None: super().__init__(observation_space, action_space, seed, **kwargs) self.logger = logging.getLogger(__name__) self.logger.info("Initialising RLAgent with seed %s", self.seed) if not isinstance(self.action_space, gym.spaces.Box): raise ValueError("RLAgent requires a Box action space") # Cache bounds and create a dedicated RNG so the agent is deterministic # when provided with a seed from the evaluator. self._low = np.asarray(self.action_space.low, dtype=np.float32) self._high = np.asarray(self.action_space.high, dtype=np.float32) self._rng = np.random.default_rng(self.seed) # Replace infinities with sane defaults to avoid invalid samples. self._low = np.where(np.isfinite(self._low), self._low, -1.0) self._high = np.where(np.isfinite(self._high), self._high, 1.0) def act(self, obs: Any, **kwargs: Any) -> torch.Tensor: """Return a random action; observation payload is accepted but unused.""" if isinstance(obs, dict): for key, value in obs.items(): try: tensor_val = np.asarray(value) except Exception: # fall back if conversion fails tensor_val = value self.logger.info("Observation key=%s value=%s", key, tensor_val) else: self.logger.info("Observation value=%s", obs) try: action = self._rng.uniform(self._low, self._high).astype(np.float32) except Exception as exc: # Fallback in case bounds are malformed self.logger.warning("Falling back to action_space.sample() due to: %s", exc) action = self.action_space.sample().astype(np.float32) # Ensure the tensor shape matches the action space action = np.clip(action, self._low, self._high) self.logger.info("Action=%s", action) return torch.from_numpy(action) def reset(self) -> None: """Reset any per-episode state (none required for random agent).""" # No internal state, but method kept for interface completeness. pass