haive.games.mafia.agent¶
Mafia game agent implementation.
This module provides the core agent implementation for the Mafia game, handling:
Game initialization and setup
Player turn management
Move generation and validation
Game state visualization
Role-specific behavior
The agent uses LLMs to generate player decisions and narrator actions, creating an engaging and strategic game experience.
Example
>>> from mafia.agent import MafiaAgent
>>> from mafia.config import MafiaAgentConfig
>>>
>>> # Create and initialize agent
>>> config = MafiaAgentConfig.default_config(player_count=7)
>>> agent = MafiaAgent(config)
>>>
>>> # Run the game
>>> for state in agent.app.stream(initial_state):
... agent.visualize_state(state)
Classes¶
Agent for playing Mafia. |
Module Contents¶
- class haive.games.mafia.agent.MafiaAgent(config)¶
Bases:
haive.games.framework.multi_player.agent.MultiPlayerGameAgent
[haive.games.mafia.config.MafiaAgentConfig
]Agent for playing Mafia.
This class implements the core game logic for Mafia, managing player turns, move generation, and game progression.
- The agent handles:
Role assignment and management
Turn sequencing and validation
LLM-based decision making
Game state visualization
Win condition checking
- state_manager¶
Manager for game state
- Type:
- role_enum_mapping¶
Role to engine mapping
- Type:
Dict[PlayerRole, str]
- role_mapping¶
Engine to role mapping
- Type:
Dict[str, PlayerRole]
Example
>>> config = MafiaAgentConfig.default_config(player_count=7) >>> agent = MafiaAgent(config) >>> initial_state = MafiaStateManager.initialize( ... ["Player_1", "Player_2", "Narrator"] ... ) >>> for state in agent.app.stream(initial_state): ... agent.visualize_state(state)
Initialize the Mafia agent.
- Parameters:
config (MafiaAgentConfig) – Configuration for the agent
Example
>>> config = MafiaAgentConfig.default_config(player_count=7) >>> agent = MafiaAgent(config)
- determine_next_step_after_player_turn(state)¶
Determine what to do after a player’s turn.
- This method decides the next game action based on:
Current game phase
Completed actions
Game end conditions
Maximum day limit
- Parameters:
state (MafiaGameState) – Current game state
- Returns:
Next action (“end_game”, “phase_transition”, or “next_player”)
- Return type:
Example
>>> next_step = agent.determine_next_step_after_player_turn(state) >>> print(next_step) # Shows what happens next
- extract_move(response, player_id)¶
Extract move from engine response.
This method processes the LLM response into a valid game action, handling:
Response validation
Action type conversion
Default action generation
Error handling
- Parameters:
- Returns:
Validated game action
- Return type:
Union[MafiaAction, NarratorAction]
Example
>>> response = engine.invoke(context) >>> move = agent.extract_move(response, "Player_1") >>> print(move.action_type) # Shows the action type
- get_engine_for_player(role, function)¶
Get the appropriate engine for a player based on role and function.
- Parameters:
role (Union[PlayerRole, str]) – Player’s role or role string
function (str) – Function type (e.g., “player”)
- Returns:
Engine configuration if found, None otherwise
- Return type:
Optional[Any]
Example
>>> engine = agent.get_engine_for_player( ... PlayerRole.MAFIA, "player" ... ) >>> print(engine.name) # Shows "mafia_player"
- get_player_role(state, player_id)¶
Get the role of a player.
- Parameters:
state (MafiaGameState) – Current game state
player_id (str) – ID of the player to check
- Returns:
The player’s role
- Return type:
- Raises:
Exception – If player not found in state
Example
>>> role = agent.get_player_role(state, "Player_1") >>> print(role) # Shows PlayerRole.VILLAGER
- handle_narrator_turn(state)¶
Handle the narrator’s turn.
- This method manages narrator actions, including:
Phase transitions
Night action resolution
Public announcements
Game state updates
- Parameters:
state (MafiaGameState) – Current game state
- Returns:
Updated game state after narrator action
- Return type:
Dict[str, Any]
Example
>>> new_state = agent.handle_narrator_turn(state) >>> print(new_state["public_announcements"][-1])
- handle_player_turn(state)¶
Handle a player’s turn with special Mafia logic.
- This method manages a player’s turn, including:
Role-specific behavior
Move generation and validation
State updates
Error handling
- Parameters:
state (MafiaGameState) – Current game state
- Returns:
Updated game state after the turn
- Return type:
Dict[str, Any]
Example
>>> new_state = agent.handle_player_turn(state) >>> print(new_state["game_phase"]) # Shows current phase
- prepare_move_context(state, player_id)¶
Prepare context for move generation.
This method gathers all relevant information for a player’s move, including:
Game state information
Player-specific knowledge
Legal moves
Recent history
- Parameters:
state (MafiaGameState) – Current game state
player_id (str) – ID of the player making the move
- Returns:
Context for move generation
- Return type:
Dict[str, Any]
Example
>>> context = agent.prepare_move_context(state, "Player_1") >>> print(context["phase"]) # Shows current game phase
- prepare_narrator_context(state)¶
Prepare context for narrator actions.
This method gathers all information needed for narrator decisions, including:
Complete game state
Player summaries
Phase-specific information
Action histories
- Parameters:
state (MafiaGameState) – Current game state
- Returns:
Context for narrator decisions
- Return type:
Dict[str, Any]
Example
>>> context = agent.prepare_narrator_context(state) >>> print(context["phase"]) # Shows current game phase
- state_to_dict(state)¶
Convert state to dictionary consistently.
This method handles various state formats and ensures consistent dictionary conversion for the game graph.
- Parameters:
state (MafiaGameState) – State to convert
- Returns:
Dictionary representation of the state
- Return type:
Dict[str, Any]
Example
>>> state_dict = agent.state_to_dict(state) >>> print(state_dict["game_phase"])
- visualize_state(state_obj, debug=False)¶
Visualize the current game state.
- This method creates a human-readable display of:
Game phase and status
Player information
Recent announcements
Game statistics
Voting results (if applicable)
- Parameters:
state_obj – Game state (dict, MafiaGameState, or agent)
debug (bool, optional) – Show debug information. Defaults to False.
Example
>>> agent.visualize_state(state, debug=True)