Files
AIPLAYER/docs/api_reference.md
T
truetype b9f21c7199 docs: complete documentation and add web monitoring dashboard
- Add comprehensive configuration guide (docs/configuration.md)
- Add development guide with setup instructions (docs/development.md)
- Add complete API reference documentation (docs/api_reference.md)
- Update README.md with new features and project structure
- Update TODO.md to reflect current implementation status
- Add web monitoring dashboard with FastAPI and WebSocket support
- Add tests for sync integration and web monitoring
- Update config example with monitoring settings

The MUD AI Player is now feature-complete with full documentation.
2026-02-09 10:44:25 +01:00

11 KiB

API Reference

Complete API reference for the MUD AI Player.

Table of Contents


Core Components

TelnetClient

Asynchronous telnet client for MUD connection.

Location: src.core.telnet_client.TelnetClient

class TelnetClient:
    def __init__(
        self,
        host: str,
        port: int,
        max_retries: int = 3,
        retry_delay: float = 5.0,
        auto_reconnect: bool = True,
    )

Methods:

  • async connect() -> bool - Connect to MUD server
  • async connect_with_retry() -> bool - Connect with retry logic
  • async disconnect() - Disconnect from server
  • async send(command: str) - Send command to server
  • async receive_loop() - Main receive loop
  • set_receive_callback(callback: Callable) - Set data callback

Example:

client = TelnetClient("mud.example.com", 4000)
await client.connect()
await client.send("look")

GameState

Central game state management.

Location: src.core.game_state.GameState

@dataclass
class GameState:
    character: Character
    current_room: Optional[Room]
    previous_room: Optional[Room]
    inventory: List[str]
    active_quests: List[Quest]
    combat_state: CombatState
    target: Optional[str]

Methods:

  • is_in_combat() -> bool - Check if in combat
  • is_healthy(threshold: float = 0.7) -> bool - Check health threshold
  • update_from_prompt(prompt: ParsedPrompt) - Update vitals
  • update_room(parsed_room: ParsedRoom) - Update current room
  • update_combat(parsed_combat: ParsedCombat) - Update combat state

ANSIParser

Parse and strip ANSI color codes.

Location: src.core.ansi_parser.ANSIParser

class ANSIParser:
    def strip_ansi(self, text: str) -> str
    def parse_colors(self, text: str) -> List[ANSISegment]

Modules

WorldMapper

High-level automapper with hybrid storage.

Location: src.modules.mapper.WorldMapper

class WorldMapper:
    def __init__(
        self,
        db_path: str = "data/maps/active/world.db",
        archive_dir: str = "data/maps/archive",
        enable_sync: bool = True,
        room_count_trigger: int = 500,
        time_interval_hours: float = 24.0,
    )

Methods:

  • on_room_enter(title, description, exits, npcs, items, zone) -> int

    • Process arrival in a room, returns room ID
  • on_move(direction: str)

    • Record movement direction
  • on_move_failed(direction: str)

    • Record blocked exit
  • find_path(to_room_id: int) -> Optional[List[str]]

    • Find path from current room to target
  • find_path_between(from_id: int, to_id: int) -> Optional[List[str]]

    • Find path between two rooms
  • get_next_exploration_target() -> Optional[Dict]

    • Get next unexplored exit
  • get_unexplored_exits(room_id: Optional[int]) -> List[str]

    • Get unexplored directions from room
  • search_rooms(query: str, top_k: int = 5) -> List[Dict]

    • Semantic search on room descriptions
  • close()

    • Close mapper and create final snapshot

Properties:

  • current_room_id: Optional[int]
  • total_rooms: int
  • total_exits: int
  • sync_stats: Dict

DecisionEngine

Central decision-making engine.

Location: src.modules.decision.engine.DecisionEngine

class DecisionEngine:
    def __init__(
        self,
        combat_config: Optional[CombatConfig] = None,
        exploration_strategy: str = "random",
    )

Methods:

  • tick(game_state: GameState)

    • Evaluate world and queue actions
  • next_action() -> Optional[Action]

    • Get most urgent action
  • force_state(state_name: str, game_state: GameState)

    • Force state transition
  • register_state(state: BaseBehaviorState)

    • Add custom behavior state

Properties:

  • current_state: BaseBehaviorState
  • current_state_name: str

ActionQueue

Priority queue for actions.

Location: src.modules.decision.action_queue.ActionQueue

class ActionQueue:
    def push(self, action: Action)
    def pop(self) -> Optional[Action]
    def peek(self) -> Optional[Action]
    def clear(self)
    def clear_by_source(self, source: str)
    
    @property
    def size(self) -> int
    @property
    def is_empty(self) -> bool

CombatAI

Intelligent combat decision-making.

Location: src.modules.decision.combat_ai.CombatAI

class CombatAI:
    def __init__(self, config: Optional[CombatConfig] = None)
    
    def decide(self, game_state: GameState) -> List[Action]
    def reset(self)

GoalManager

Manage AI goals and objectives.

Location: src.modules.decision.goal_manager.GoalManager

class GoalManager:
    def add_goal(self, goal: Goal)
    def remove_goal(self, goal_id: str)
    def get_current_goal(self, game_state: GameState) -> Optional[Goal]
    def get_active_goals(self) -> List[Goal]
    def set_default_goals(self)
    
    @property
    def active_goal_count(self) -> int

LLMBrain

LLM integration with memory.

Location: src.modules.llm.brain.LLMBrain

class LLMBrain:
    def __init__(
        self,
        config: LLMConfig,
        memory_db_path: str = "data/llm_memory.db",
    )
    
    async def initialize()
    async def decide(game_state: GameState) -> Optional[str]
    async def social_reply(
        message: str,
        sender: str,
        character_class: str,
        character_name: str,
    ) -> Optional[str]
    
    @property
    def is_available(self) -> bool

SocialAI

Detect and respond to social interactions.

Location: src.modules.llm.social_ai.SocialAI

class SocialAI:
    def __init__(
        self,
        client: LLMClient,
        character_name: str,
        character_class: str,
    )
    
    def detect_social_event(self, text: str) -> Optional[Dict]

CharacterCreator

Automated character creation.

Location: src.modules.character.creator.CharacterCreator

class CharacterCreator:
    def __init__(self, config: CreatorConfig)
    
    async def create_character(telnet: TelnetClient) -> bool

QuestManager

Quest tracking and management.

Location: src.modules.quest.quest_manager.QuestManager

class QuestManager:
    def add_quest(self, quest: Quest)
    def complete_quest(self, quest_id: str)
    def get_active_quests(self) -> List[Quest]
    def detect_quest_in_text(self, text: str) -> Optional[Quest]

ProgressionOptimizer

Optimize grinding and progression.

Location: src.modules.progression.optimizer.ProgressionOptimizer

class ProgressionOptimizer:
    def find_optimal_grind_area(
        self,
        game_state: GameState,
        world_mapper: WorldMapper,
    ) -> Optional[str]
    
    def should_grind(self, game_state: GameState) -> bool

MonitoringServer

Web dashboard server.

Location: src.modules.web.server.MonitoringServer

class MonitoringServer:
    def __init__(
        self,
        host: str = "127.0.0.1",
        port: int = 8080,
        game_state: Optional[Any] = None,
        world_mapper: Optional[Any] = None,
        decision_engine: Optional[Any] = None,
    )
    
    async def start()
    async def stop()
    def log_event(self, event_type: str, message: str, data: Optional[Dict] = None)

Configuration

load_config

Load and validate configuration.

Location: src.config.settings.load_config

def load_config(config_path: str = "config.yaml") -> Config

Example:

from src.config.settings import load_config

config = load_config("config.yaml")
print(config.mud.host)
print(config.character.preferred_class)

Config Classes

  • MudConfig - MUD connection settings
  • CharacterConfig - Character preferences
  • AIConfig - AI engine settings
  • LLMProviderConfig - LLM configuration
  • MapperConfig - Mapper settings
  • BehaviorConfig - Behavior simulation
  • LoggingConfig - Logging settings
  • MonitoringConfig - Web dashboard settings

Utilities

setup_logger

Configure application logging.

Location: src.utils.logger.setup_logger

def setup_logger(
    level: str = "INFO",
    log_file: str = "data/logs/game.log",
    console: bool = True,
    max_file_size_mb: int = 10,
    backup_count: int = 5,
) -> logging.Logger

HumanBehavior

Simulate human-like behavior.

Location: src.utils.human_behavior.HumanBehavior

class HumanBehavior:
    def __init__(
        self,
        reaction_time_min_ms: int = 200,
        reaction_time_max_ms: int = 2000,
        pause_probability: float = 0.05,
    )
    
    async def delay(self)
    def maybe_typo(self, text: str) -> str

Data Classes

ParsedRoom

@dataclass
class ParsedRoom:
    title: Optional[str]
    description: Optional[str]
    exits: List[str]
    npcs: List[str]
    items: List[str]

ParsedPrompt

@dataclass
class ParsedPrompt:
    hp: Optional[int]
    max_hp: Optional[int]
    mp: Optional[int]
    max_mp: Optional[int]
    sp: Optional[int]
    max_sp: Optional[int]

ParsedCombat

@dataclass
class ParsedCombat:
    attacker: Optional[str]
    target: Optional[str]
    action: str
    damage: Optional[int]
    is_combat: bool

Action

@dataclass
class Action:
    command: str
    priority: ActionPriority
    description: str
    source: str

Goal

@dataclass
class Goal:
    id: str
    name: str
    description: str
    priority: GoalPriority
    target_state: str
    conditions: List[Callable[[GameState], bool]]
    progress: float

Enums

CombatState

class CombatState(Enum):
    IDLE = "idle"
    IN_COMBAT = "in_combat"
    FLEEING = "fleeing"

ActionPriority

class ActionPriority(Enum):
    CRITICAL = 1
    HIGH = 2
    MEDIUM = 3
    LOW = 4
    IDLE = 5

GoalPriority

class GoalPriority(Enum):
    CRITICAL = 1
    HIGH = 2
    MEDIUM = 3
    LOW = 4

EventType

class EventType(Enum):
    ROOM = "room"
    PROMPT = "prompt"
    COMBAT = "combat"
    INVENTORY = "inventory"
    CHAT = "chat"
    UNKNOWN = "unknown"

Exceptions

All custom exceptions inherit from MUDAIPlayerException:

class MUDAIPlayerException(Exception):
    """Base exception for MUD AI Player"""
    pass

class ConnectionError(MUDAIPlayerException):
    """Connection-related errors"""
    pass

class ParseError(MUDAIPlayerException):
    """Parsing errors"""
    pass

class ConfigurationError(MUDAIPlayerException):
    """Configuration errors"""
    pass