Social Psychology Games

The Social Psychology Games represent the cutting edge of AI behavioral research - sophisticated gaming environments where AI agents demonstrate complex social psychology, deception mechanics, trust modeling, and emergent social behaviors that mirror real human interactions.

🧠 Revolutionary Capabilities

Advanced Deception & Trust Modeling

AI agents that lie convincingly, detect deception, form alliances, and exhibit realistic social psychology patterns

Multi-Agent Social Coordination

Complex group dynamics with hidden roles, asymmetric information, and emergent social behaviors

Adaptive Personality Systems

Dynamic personality profiles that evolve based on social interactions and strategic necessities

Psychological Profiling

Comprehensive behavioral analysis including manipulation tactics, trust patterns, and social influence

Real-Time Social Analytics

Live tracking of alliance formation, betrayal patterns, and social hierarchy emergence

Core Social Games

Among Us - Advanced Social Deduction

Among Us social deduction game module.

class haive.games.among_us.AmongUsAgent(config)[source]

Agent implementation for the Among Us game.

This class inherits state management from AmongUsStateManagerMixin and agent behavior from MultiPlayerGameAgent.

config_class

alias of AmongUsAgentConfig

__init__(config)[source]

Initialize the Among Us agent with configuration.

extract_move(response, role)[source]

Extract structured move from engine response.

Parameters:
Return type:

dict[str, Any]

get_engine_for_player(role, engine_key)[source]

Get the appropriate engine for a player based on their role and the current. phase.

Parameters:
  • role (str) – Player role (CREWMATE or IMPOSTOR)

  • engine_key (str) – Engine type key (player, meeting, voting)

Returns:

The appropriate engine runnable

Return type:

Any | None

prepare_move_context(state, player_id)[source]

Prepare context for a player’s move decision.

Parameters:
Return type:

dict[str, Any]

visualize_state(state)[source]

Visualize the current game state using the AmongUsUI.

This method is required by the MultiPlayerGameAgent parent class.

Parameters:

state (dict[str, Any] | AmongUsState) – Current game state (dict or AmongUsState object)

Return type:

None

class haive.games.among_us.AmongUsAgentConfig(*, id=<factory>, name='among_us_agent', engine_type=EngineType.AGENT, description=None, input_schema=None, output_schema=None, version='1.0.0', metadata=<factory>, engine=None, engines=None, state_schema=<class 'haive.games.among_us.state.AmongUsState'>, node_configs=<factory>, patterns=<factory>, pattern_parameters=<factory>, default_patterns=<factory>, visualize=True, output_dir='resources/graph_images', debug=False, save_history=True, runnable_config={'configurable': {'recursion_limit': 10000}}, add_store=False, agent_settings=<factory>, subagents=<factory>, persistence=<factory>, checkpoint_mode='sync', enable_analysis=False, player_names, llm_config=None, map_name='skeld', map_locations=None, num_impostors=None, emergency_meetings_per_player=1, discussion_time=45, voting_time=30, player_movement_speed=1.0, kill_cooldown=45, task_bar_updates='always')[source]

Configuration for Among Us game agent.

Parameters:
classmethod casual_game(player_count=6)[source]

Create configuration for casual gameplay.

Features: - Balanced timing for relaxed discussion - Standard movement speed - Moderate kill cooldown - Visualization enabled

Parameters:

player_count (int) – Number of players (default: 6).

Returns:

Casual game configuration.

Return type:

AmongUsAgentConfig

classmethod educational_game(player_count=5)[source]

Create configuration for educational/demonstration purposes.

Features: - Extended discussion for learning - Slower pace for observation - Higher movement speed for clarity - Always show task progress

Parameters:

player_count (int) – Number of players (default: 5).

Returns:

Educational configuration.

Return type:

AmongUsAgentConfig

classmethod set_defaults(values)[source]

Set default values based on provided values.

classmethod speed_game(player_count=8)[source]

Create configuration for fast-paced gameplay.

Features: - Short discussion and voting times - Fast movement speed - Reduced kill cooldown - Quick decision making

Parameters:

player_count (int) – Number of players (default: 8).

Returns:

Speed game configuration.

Return type:

AmongUsAgentConfig

classmethod tournament_game(player_count=10)[source]

Create configuration for tournament play.

Features: - Extended discussion time for strategy - Longer voting time for careful decisions - Reduced kill cooldown for action - Competitive balance

Parameters:

player_count (int) – Number of players (default: 10).

Returns:

Tournament configuration.

Return type:

AmongUsAgentConfig

model_post_init(context, /)

This function is meant to behave like a BaseModel method to initialise private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

discussion_time: int
emergency_meetings_per_player: int
engines: dict[str, dict[str, AugLLMConfig]] | None
property game_balance: dict[str, Any]

Calculate game balance metrics and recommendations.

Returns:

Balance analysis including ratios and recommendations.

Return type:

Dict[str, Any]

kill_cooldown: int
llm_config: dict[str, Any] | None
map_locations: list[str] | None
map_name: str
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

name: str
num_impostors: int
player_movement_speed: float
player_names: list[str]
state_schema: type
task_bar_updates: Literal['always', 'meetings', 'never']
visualize: bool
voting_time: int
class haive.games.among_us.AmongUsGamePhase(*values)[source]

Current phase of gameplay.

Game alternates between task/action phases and discussion/voting.

Values:

TASKS: Normal gameplay with movement and actions MEETING: Discussion phase after body report or emergency VOTING: Active voting to eject a player GAME_OVER: Game concluded with winner determined

GAME_OVER = 'game_over'
MEETING = 'meeting'
TASKS = 'tasks'
VOTING = 'voting'
class haive.games.among_us.AmongUsState(*, players, current_player_idx=0, game_phase=AmongUsGamePhase.TASKS, game_status='ongoing', move_history=<factory>, round_number=0, player_data=<factory>, public_state=<factory>, error_message=None, map_locations=<factory>, map_name='skeld', rooms=<factory>, vents=<factory>, player_states=<factory>, tasks=<factory>, sabotages=<factory>, eliminated_players=<factory>, meeting_active=False, meeting_caller=None, reported_body=None, votes=<factory>, impostor_count=0, crewmate_count=0, discussion_history=<factory>, kill_cooldowns=<factory>)[source]

Comprehensive state model for Among Us game sessions.

This class manages all aspects of an Among Us game state, including spatial layout, player tracking, task management, and game progression. It provides methods for querying game state, updating player positions, managing events, and evaluating win conditions.

The state model supports: - Multiple map layouts (currently Skeld, with Polus/Mira HQ planned) - Real-time player position and status tracking - Task assignment and completion monitoring - Sabotage event lifecycle management - Emergency meeting and voting systems - Observation and memory tracking for deduction - Flexible win condition evaluation

Parameters:
map_locations

List of valid room IDs for the current map. Used for movement validation and spawn points.

Type:

list[str]

map_name

Name of the current map (e.g., “skeld”, “polus”). Determines room layout and task locations.

Type:

str

rooms

Mapping of room IDs to Room objects. Defines spatial layout and connections.

Type:

dict[str, haive.games.among_us.models.Room]

vents

Mapping of vent IDs to Vent objects. Enables impostor movement through vent network.

Type:

dict[str, haive.games.among_us.models.Vent]

player_states

Mapping of player IDs to PlayerState objects. Tracks all player information including role and position.

Type:

dict[str, haive.games.among_us.models.PlayerState]

tasks

Mapping of task IDs to Task objects. Defines available tasks and their completion status.

Type:

dict[str, haive.games.among_us.models.Task]

sabotages

List of active and resolved sabotage events. Tracks sabotage history and current emergencies.

Type:

list[haive.games.among_us.models.SabotageEvent]

eliminated_players

List of player IDs who have been eliminated. Used for ghost mechanics and win conditions.

Type:

list[str]

meeting_active

Whether an emergency meeting is in progress. Pauses gameplay and enables discussion/voting.

Type:

bool

meeting_caller

Player ID who called the current meeting. None if meeting was triggered by body report.

Type:

str | None

reported_body

Player ID of body that triggered meeting. None if meeting was called via emergency button.

Type:

str | None

votes

Mapping of voter ID to target ID for current meeting. Tracks voting progress and determines ejection.

Type:

dict[str, str]

game_phase

Current phase of gameplay. Controls available actions and UI state.

Type:

haive.games.among_us.models.AmongUsGamePhase

impostor_count

Number of living impostors. Cached for efficient win condition checks.

Type:

int

crewmate_count

Number of living crewmates. Cached for efficient win condition checks.

Type:

int

discussion_history

List of discussion events and messages. Provides context for AI decision-making.

Type:

list[dict[str, Any]]

kill_cooldowns

Mapping of impostor ID to remaining cooldown. Prevents rapid elimination chains.

Type:

dict[str, int]

Examples

Creating a new game state:

state = AmongUsState(
    map_name="skeld",
    impostor_count=2,
    crewmate_count=8
)
state.initialize_map()

Checking task progress:

progress = state.get_task_completion_percentage()
if progress >= 100:
    print("Crewmates win by tasks!")

Managing meetings:

state.meeting_active = True
state.meeting_caller = "player1"
state.votes["player1"] = "player3"  # Voting for player3
state.votes["player2"] = "skip"     # Voting to skip
classmethod validate_map_name(v)[source]

Validate map name is supported.

Parameters:

v (str) – Map name to validate.

Returns:

Validated map name in lowercase.

Return type:

str

Raises:

ValueError – If map name is not supported.

add_observation(player_id, observation)[source]

Add an observation to a player’s memory.

Observations form the basis of deduction in Among Us. This method records what a player has witnessed for later analysis.

Parameters:
  • player_id (str) – ID of the observing player.

  • observation (str) – Description of what was observed.

Return type:

None

Examples

Witnessing movement:

state.add_observation(
    "player1",
    "Saw player3 enter electrical at 14:32"
)

Task verification:

state.add_observation(
    "player2",
    "Watched player4 complete medbay scan"
)
add_observation_to_all_in_room(room_id, observation, exclude_players=None)[source]

Add an observation to all players in a specific room.

Used for events that are visible to everyone in a location, such as sabotages, eliminations, or visual tasks.

Parameters:
  • room_id (str) – Room where the event occurred.

  • observation (str) – Description of the observed event.

  • exclude_players (list[str] | None) – Optional list of player IDs to exclude. Typically used to exclude the actor from observations.

Return type:

None

Examples

Elimination witnessed:

state.add_observation_to_all_in_room(
    "electrical",
    "Player5 eliminated player2!",
    exclude_players=["player5"]  # Killer doesn't observe self
)

Visual task:

state.add_observation_to_all_in_room(
    "medbay",
    "Player3 completed scan (confirmed crewmate)"
)
check_win_condition()[source]

Check if either side has achieved victory.

Evaluates all win conditions for both teams:

Crewmate victories: - All tasks completed - All impostors eliminated

Impostor victories: - Impostor count >= crewmate count - Critical sabotage timer expired

Returns:

Winning team or None.

Return type:

Optional[Literal[“crewmates”, “impostors”]]

Examples

Task victory:

# All tasks done
winner = state.check_win_condition()
assert winner == "crewmates"

Impostor majority:

# 2 impostors, 2 crewmates remaining
winner = state.check_win_condition()
assert winner == "impostors"

Sabotage victory:

# Reactor meltdown timer reaches 0
winner = state.check_win_condition()
assert winner == "impostors"
decrement_cooldowns()[source]

Decrement all active kill cooldowns by 1 second.

Should be called each game tick/second to update cooldowns. Automatically removes cooldowns that reach 0.

Examples

Game loop integration:

# In game tick handler
state.decrement_cooldowns()

# Check if any impostors can now kill
for impostor_id in impostor_ids:
    if state.get_player_cooldown(impostor_id) == 0:
        # Enable kill button in UI
        pass
Return type:

None

get_active_sabotage()[source]

Get the currently active sabotage event.

Only one sabotage can be active at a time. This method returns the first unresolved sabotage found.

Returns:

Active sabotage or None.

Return type:

Optional[SabotageEvent]

Examples

Emergency response:

sabotage = state.get_active_sabotage()
if sabotage and sabotage.is_critical():
    print(f"EMERGENCY: {sabotage.type} - {sabotage.timer}s left!")

Checking if sabotage is possible:

if state.get_active_sabotage() is None:
    # Impostors can trigger new sabotage
    pass
get_alive_players()[source]

Get list of alive player IDs.

Returns only players who have not been eliminated, useful for voting counts, task assignments, and win condition checks.

Returns:

IDs of all living players.

Return type:

List[str]

Examples

During meeting:

alive = state.get_alive_players()
print(f"{len(alive)} players can vote")

Win condition check:

alive = state.get_alive_players()
if len(alive) <= 2:
    # Check for impostor majority
    pass
get_connected_rooms(room_id)[source]

Get all rooms directly connected to the given room.

Returns only accessible connections (not blocked by sabotage). Used for pathfinding and movement validation.

Parameters:

room_id (str) – Source room to check connections from.

Returns:

IDs of all accessible connected rooms.

Return type:

List[str]

Examples

Movement options:

adjacent = state.get_connected_rooms("cafeteria")
print(f"Can move to: {', '.join(adjacent)}")

Sabotage effects:

# During O2 sabotage, some doors may be sealed
rooms = state.get_connected_rooms("admin")
if len(rooms) < normal_count:
    print("Some exits are blocked!")
get_connected_vents(vent_id)[source]

Get all vents connected to the given vent.

Used for impostor movement through the vent network. All vent connections are always accessible (no blocking).

Parameters:

vent_id (str) – Source vent to check connections from.

Returns:

IDs of all connected vents.

Return type:

List[str]

Examples

Vent navigation:

connected = state.get_connected_vents("electrical_vent")
for vent_id in connected:
    vent = state.get_vent(vent_id)
    print(f"Can emerge in: {vent.location}")
get_player_cooldown(player_id)[source]

Get a player’s kill cooldown in seconds.

Parameters:

player_id (str) – ID of the player (impostor) to check.

Returns:

Remaining cooldown seconds (0 if can kill).

Return type:

int

Examples

Checking kill availability:

cooldown = state.get_player_cooldown("impostor1")
if cooldown == 0:
    print("Kill ability ready")
else:
    print(f"Kill on cooldown: {cooldown}s")
get_room(room_id)[source]

Get a room by its unique identifier.

Parameters:

room_id (str) – Unique room identifier (e.g., “cafeteria”).

Returns:

Room object if found, None otherwise.

Return type:

Optional[Room]

Examples

Checking room properties:

room = state.get_room("electrical")
if room and room.has_security_camera:
    print("This room is monitored")
get_task_completion_percentage()[source]

Calculate overall task completion percentage.

Computes the percentage of all tasks that have been completed across all crewmates. This is a primary win condition - crewmates win immediately when this reaches 100%.

Returns:

Percentage of completed tasks (0-100).

Return type:

float

Examples

Progress tracking:

progress = state.get_task_completion_percentage()
print(f"Tasks: {progress:.1f}% complete")

Win condition:

if state.get_task_completion_percentage() >= 100:
    return "crewmates_win_by_tasks"

Note

Returns 100.0 if no tasks exist (edge case handling).

get_vent(vent_id)[source]

Get a vent by its unique identifier.

Parameters:

vent_id (str) – Unique vent identifier (e.g., “electrical_vent”).

Returns:

Vent object if found, None otherwise.

Return type:

Optional[Vent]

Examples

Checking vent connections:

vent = state.get_vent("cafeteria_vent")
if vent:
    connected = [c.target_vent_id for c in vent.connections]
    print(f"Can travel to: {connected}")
get_vents_in_room(room_id)[source]

Get all vents located in a specific room.

Used for impostor movement options and vent camping detection.

Parameters:

room_id (str) – Room to search for vents.

Returns:

All vents in the specified room.

Return type:

List[Vent]

Examples

Impostor options:

vents = state.get_vents_in_room("electrical")
if vents and player.role == PlayerRole.IMPOSTOR:
    print(f"Can enter {len(vents)} vent(s) here")
initialize_map()[source]

Initialize the map with rooms and vents based on the map name.

Creates the spatial layout for the selected map, including all rooms, connections, and vent networks. Currently supports the Skeld map with plans for Polus and Mira HQ.

The initialization includes: - Room creation with connections and properties - Vent network setup with travel times - Map location list for spawn points

Examples

Default Skeld initialization:

state = AmongUsState(map_name="skeld")
state.initialize_map()
assert "cafeteria" in state.rooms
assert len(state.vents) == 10  # Skeld has 10 vents

Future map support:

state = AmongUsState(map_name="polus")
state.initialize_map()  # Will support Polus layout

Note

This method clears any existing rooms and vents before creating the new map layout.

Return type:

None

set_player_cooldown(player_id, cooldown)[source]

Set a player’s kill cooldown.

Typically called after an impostor eliminates someone.

Parameters:
  • player_id (str) – ID of the player (impostor).

  • cooldown (int) – Cooldown duration in seconds.

Return type:

None

Examples

After elimination:

# Standard 30 second cooldown
state.set_player_cooldown("impostor1", 30)

Custom game settings:

# Fast-paced game with 10s cooldown
state.set_player_cooldown("impostor1", 10)
crewmate_count: int
discussion_history: list[dict[str, Any]]
eliminated_players: list[str]
game_phase: AmongUsGamePhase
property game_statistics: dict[str, Any]

Calculate comprehensive game statistics.

Returns:

Statistics including player counts, progress, etc.

Return type:

Dict[str, Any]

Examples

Displaying game stats:

stats = state.game_statistics
print(f"Tasks: {stats['task_progress']:.1f}%")
print(f"Impostors: {stats['alive_impostors']}/{stats['total_impostors']}")
impostor_count: int
kill_cooldowns: dict[str, int]
map_locations: list[str]
map_name: str
meeting_active: bool
meeting_caller: str | None
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

player_states: dict[str, PlayerState]
reported_body: str | None
rooms: dict[str, Room]
sabotages: list[SabotageEvent]
tasks: dict[str, Task]
vents: dict[str, Vent]
votes: dict[str, str]
class haive.games.among_us.AmongUsStateManagerMixin[source]

Comprehensive state management mixin for Among Us social deduction gameplay.

This mixin class provides complete state management functionality for Among Us games, handling complex mechanics including role-based gameplay, task systems, sabotage mechanics, meeting coordination, and win condition evaluation. The class separates state management from agent behavior, allowing any inheriting class to gain full Among Us state management capabilities.

The state manager handles: - Game initialization with intelligent role assignment - Task generation and completion tracking - Complex sabotage systems with resolution mechanics - Meeting and voting coordination - Move validation and application - Win condition evaluation - Player state filtering for information hiding - Legal move generation for AI systems

Examples

Initializing a new game:

state = AmongUsStateManagerMixin.initialize(
    player_names=["Alice", "Bob", "Charlie", "David", "Eve"],
    map_name="skeld",
    num_impostors=1,
    tasks_per_player=5
)

Applying player actions:

# Player movement
move = {"action": "move", "location": "electrical"}
new_state = AmongUsStateManagerMixin.apply_move(state, "Alice", move)

# Task completion
task_move = {"action": "complete_task", "task_id": "Alice_task_1"}
new_state = AmongUsStateManagerMixin.apply_move(state, "Alice", task_move)

# Impostor actions
kill_move = {"action": "kill", "target_id": "Bob"}
new_state = AmongUsStateManagerMixin.apply_move(state, "Eve", kill_move)

Checking game progression:

updated_state = AmongUsStateManagerMixin.check_game_status(state)
if updated_state.game_status == "ended":
    print(f"Game over! {updated_state.winner} wins!")

Note

This mixin is designed to be inherited by game agents, providing state management capabilities without imposing specific agent behaviors.

classmethod advance_phase(state)[source]

Advance the game to the next phase in the game cycle.

Progresses the game through its phases: TASKS -> MEETING -> VOTING -> TASKS. Updates related state variables and resets phase-specific data.

Parameters:

state (AmongUsState) – Current game state to advance.

Returns:

Updated state in the next phase.

Return type:

AmongUsState

Examples

Task to meeting transition:

new_state = cls.advance_phase(state)
# game_phase changes from TASKS to MEETING

Meeting to voting transition:

new_state = cls.advance_phase(state)
# game_phase changes from MEETING to VOTING

Voting to tasks transition:

new_state = cls.advance_phase(state)
# game_phase changes from VOTING to TASKS
# round_number increments, votes cleared
classmethod apply_move(state, player_id, move)[source]

Apply a player’s move to the game state with comprehensive validation.

Processes and validates player moves, updating the game state accordingly. Handles all move types across different game phases with proper error handling and state consistency maintenance.

Parameters:
  • state (AmongUsState) – Current game state to modify.

  • player_id (str) – ID of the player making the move.

  • move (dict[str, Any]) – Move dictionary containing action and parameters.

Returns:

Updated game state after applying the move.

Return type:

AmongUsState

Examples

Movement action:

move = {"action": "move", "location": "electrical"}
new_state = cls.apply_move(state, "Alice", move)

Task completion:

move = {"action": "complete_task", "task_id": "Alice_task_1"}
new_state = cls.apply_move(state, "Alice", move)

Impostor kill:

move = {"action": "kill", "target_id": "Bob"}
new_state = cls.apply_move(state, "Eve", move)

Voting action:

move = {"action": "vote", "vote_for": "Charlie"}
new_state = cls.apply_move(state, "Alice", move)

Note

The method creates a deep copy of the state to avoid modifying the original, ensuring state immutability.

classmethod check_game_status(state)[source]

Check and update game status with win condition evaluation.

Evaluates the current game state to determine if any win conditions have been met and updates the game status accordingly.

Parameters:

state (AmongUsState) – Current game state to check.

Returns:

Updated state with current game status.

Return type:

AmongUsState

Examples

Ongoing game:

updated_state = cls.check_game_status(state)
# Returns state with game_status="ongoing"

Crewmate victory:

updated_state = cls.check_game_status(state)
# Returns state with game_status="ended", winner="crewmates"

Impostor victory:

updated_state = cls.check_game_status(state)
# Returns state with game_status="ended", winner="impostors"
classmethod filter_state_for_player(state, player_id)[source]

Filter game state to include only information visible to a specific player.

Creates a filtered view of the game state that includes only information the specified player should have access to, implementing proper information hiding for authentic social deduction gameplay.

Parameters:
  • state (AmongUsState) – Complete game state to filter.

  • player_id (str) – ID of the player to create filtered state for.

Returns:

Filtered state dictionary with player-visible information.

Return type:

Dict[str, Any]

Examples

Crewmate filtered state:

filtered = cls.filter_state_for_player(state, "Alice")
# Includes: own location, tasks, observations, connected rooms
# Excludes: other players' roles, impostor identities

Impostor filtered state:

filtered = cls.filter_state_for_player(state, "Eve")
# Includes: fellow impostors, vent locations, kill cooldown
# Excludes: crewmate task progress details

Dead player filtered state:

filtered = cls.filter_state_for_player(state, "Bob")
# Includes: basic game information, spectator view
# Excludes: ability to influence game

Generate comprehensive legal moves for a player based on game state.

Analyzes the current game state and player situation to generate all valid moves available to the player, considering their role, location, game phase, and current constraints.

Parameters:
  • state (AmongUsState) – Current game state.

  • player_id (str) – ID of the player to generate moves for.

Returns:

List of legal move dictionaries.

Return type:

List[Dict[str, Any]]

Examples

Crewmate in task phase:

moves = cls.get_legal_moves(state, "Alice")
# Returns moves like:
# [{"action": "move", "location": "electrical"},
#  {"action": "complete_task", "task_id": "Alice_task_1"},
#  {"action": "report_body"}] (if body present)

Impostor in task phase:

moves = cls.get_legal_moves(state, "Eve")
# Returns moves like:
# [{"action": "move", "location": "medbay"},
#  {"action": "kill", "target_id": "Bob"},
#  {"action": "vent", "vent_id": "electrical_vent"},
#  {"action": "sabotage", "sabotage_type": "lights"}]

Player in voting phase:

moves = cls.get_legal_moves(state, "Alice")
# Returns moves like:
# [{"action": "vote", "vote_for": "Charlie"},
#  {"action": "vote", "vote_for": "skip"}]
classmethod initialize(player_names, **kwargs)[source]

Initialize a new Among Us game state with intelligent defaults.

Creates a complete game state with role assignments, task generation, map initialization, and all necessary game components. The initialization process follows standard Among Us rules for balanced gameplay.

Parameters:
  • player_names (list[str]) – List of player identifiers (4-15 players).

  • **kwargs – Additional configuration options. map_name (str): Map to use (default: “skeld”). num_impostors (int): Number of impostors (auto-calculated if None). tasks_per_player (int): Tasks per crewmate (default: 5). kill_cooldown (int): Impostor kill cooldown in seconds (default: 45). seed: Random seed for reproducible games.

Returns:

Fully initialized game state ready for gameplay.

Return type:

AmongUsState

Examples

Standard initialization:

state = AmongUsStateManagerMixin.initialize(
    player_names=["Alice", "Bob", "Charlie", "David", "Eve"],
    map_name="skeld"
)
# Auto-assigns 1 impostor for 5 players

Custom configuration:

state = AmongUsStateManagerMixin.initialize(
    player_names=["Player_" + str(i) for i in range(10)],
    map_name="polus",
    num_impostors=2,
    tasks_per_player=6,
    kill_cooldown=30,
    seed=12345
)

Note

The initialization automatically balances impostor count based on player count following standard Among Us ratios.

model_config = {'arbitrary_types_allowed': True}
class haive.games.among_us.PlayerMemory(*, observations=<factory>, player_suspicions=<factory>, player_alibis=<factory>, location_history=<factory>)[source]

Cognitive model for player observations and deductions.

Tracks what a player has observed and deduced during gameplay, forming the basis for social deduction. Memory includes direct observations, suspicion levels, alibis, and movement patterns.

Parameters:
observations

Chronological list of observations.

Type:

List[str]

player_suspicions

Suspicion levels (0-1) per player.

Type:

Dict[str, float]

player_alibis

Last known locations of players.

Type:

Dict[str, str]

location_history

Recent rooms visited by this player.

Type:

List[str]

Examples

Tracking suspicious behavior:

memory = PlayerMemory(
    observations=[
        "Saw Red near body in electrical",
        "Blue was alone in medbay",
        "Green completed visual task"
    ],
    player_suspicions={
        "Red": 0.8,
        "Blue": 0.4,
        "Green": 0.0
    }
)

Building alibis:

memory.player_alibis = {
    "Red": "electrical",
    "Blue": "medbay",
    "Green": "cafeteria"
}
classmethod validate_suspicion_levels(v)[source]

Ensure suspicion levels are within valid range.

Parameters:

v (Dict[str, float]) – Suspicion dictionary to validate.

Returns:

Validated suspicion levels.

Return type:

Dict[str, float]

Raises:

ValueError – If suspicion level outside 0-1 range.

location_history: list[str]
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

property most_suspicious: str | None

Identify the most suspicious player.

Returns:

Player ID with highest suspicion or None.

Return type:

Optional[str]

observations: list[str]
player_alibis: dict[str, str]
player_suspicions: dict[str, float]
property trusted_players: list[str]

List players with low suspicion (< 0.3).

Returns:

IDs of trusted players.

Return type:

List[str]

class haive.games.among_us.PlayerRole(*values)[source]

Player roles defining objectives and abilities.

Determines the player’s win condition and available actions: - Crewmates: Complete tasks and identify impostors - Impostors: Eliminate crew and avoid detection

Values:

CREWMATE: Innocent crew member focused on tasks IMPOSTOR: Deceptive player who can kill and sabotage

CREWMATE = 'crewmate'
IMPOSTOR = 'impostor'
class haive.games.among_us.PlayerState(*, id, role, location, tasks=<factory>, is_alive=True, last_action=None, observations=<factory>, in_vent=False, current_vent=None, memory=<factory>)[source]

Complete state representation for a player in Among Us.

Encapsulates all information about a player including their role, location, tasks, survival status, and cognitive state. Supports both crewmate and impostor gameplay with appropriate abilities.

Parameters:
id

Unique player identifier.

Type:

str

role

Crewmate or Impostor designation.

Type:

PlayerRole

location

Current room location.

Type:

str

tasks

Assigned tasks (empty for impostors).

Type:

List[Task]

is_alive

Whether player is still active.

Type:

bool

last_action

Most recent action taken.

Type:

Optional[str]

observations

Direct observations this turn.

Type:

List[str]

in_vent

Whether currently hiding in vent.

Type:

bool

current_vent

ID of occupied vent.

Type:

Optional[str]

memory

Cognitive state and deductions.

Type:

PlayerMemory

Examples

Crewmate with tasks:

crewmate = PlayerState(
    id="Blue",
    role=PlayerRole.CREWMATE,
    location="electrical",
    tasks=[
        Task(id="wire1", type=TaskType.COMMON,
             location="electrical", description="Fix wiring"),
        Task(id="scan1", type=TaskType.VISUAL,
             location="medbay", description="Submit to scan")
    ]
)

Impostor in vent:

impostor = PlayerState(
    id="Red",
    role=PlayerRole.IMPOSTOR,
    location="electrical",
    tasks=[],
    in_vent=True,
    current_vent="electrical_vent"
)

Dead player:

ghost = PlayerState(
    id="Green",
    role=PlayerRole.CREWMATE,
    location="cafeteria",
    tasks=[],
    is_alive=False
)
can_kill(kill_cooldown=0)[source]

Check if the player can perform a kill action.

Kill ability requires: - Impostor role - Being alive - Kill cooldown expired - Not currently in vent

Parameters:

kill_cooldown (int) – Remaining cooldown seconds.

Returns:

True if all conditions met for killing.

Return type:

bool

Examples

>>> impostor = PlayerState(id="Red", role=PlayerRole.IMPOSTOR,
...                        location="electrical", is_alive=True)
>>> impostor.can_kill(kill_cooldown=0)
True
>>> impostor.can_kill(kill_cooldown=10)
False
can_use_vent()[source]

Check if the player can use ventilation systems.

Vent usage requires: - Impostor role - Being alive

Returns:

True if player can enter/exit vents.

Return type:

bool

Examples

>>> impostor = PlayerState(id="Red", role=PlayerRole.IMPOSTOR,
...                        location="electrical", is_alive=True)
>>> impostor.can_use_vent()
True
is_crewmate()[source]

Check if the player is a crewmate.

Returns:

True if player has crewmate role.

Return type:

bool

Examples

>>> crew = PlayerState(id="Blue", role=PlayerRole.CREWMATE, location="cafeteria")
>>> crew.is_crewmate()
True
is_impostor()[source]

Check if the player is an impostor.

Returns:

True if player has impostor role.

Return type:

bool

Examples

>>> impostor = PlayerState(id="Red", role=PlayerRole.IMPOSTOR, location="cafeteria")
>>> impostor.is_impostor()
True
current_vent: str | None
id: str
in_vent: bool
property incomplete_tasks: list[Task]

Get list of uncompleted tasks.

Returns:

Tasks that still need completion.

Return type:

List[Task]

is_alive: bool
property is_ghost: bool

Check if player is a ghost (dead but still participating).

Returns:

True if player is dead.

Return type:

bool

last_action: str | None
location: str
memory: PlayerMemory
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

observations: list[str]
role: PlayerRole
property task_completion_rate: float

Calculate percentage of tasks completed.

Returns:

Completion percentage (0.0-100.0).

Return type:

float

tasks: list[Task]
class haive.games.among_us.Task(*, id, type, location, description, status=TaskStatus.NOT_STARTED, visual_indicator=False)[source]

Individual task assignment for crewmates.

Tasks are the primary objective for crewmates, requiring them to visit specific locations and complete mini-games. Visual tasks can prove innocence by showing animations to nearby players.

Parameters:
id

Unique task identifier.

Type:

str

type

Category of task affecting behavior.

Type:

TaskType

location

Room where task must be performed.

Type:

str

description

Human-readable task description.

Type:

str

status

Current completion state.

Type:

TaskStatus

visual_indicator

Whether task shows visible proof.

Type:

bool

Examples

Visual task proving innocence:

task = Task(
    id="medbay_scan",
    type=TaskType.VISUAL,
    location="medbay",
    description="Submit to medbay scan",
    visual_indicator=True
)

Common electrical task:

task = Task(
    id="fix_wiring",
    type=TaskType.COMMON,
    location="electrical",
    description="Fix wiring"
)
property completion_percentage: float

Calculate task completion percentage.

Returns:

0.0 for not started, 0.5 for in progress, 1.0 for completed.

Return type:

float

description: str
id: str
property is_completed: bool

Check if task is fully completed.

Returns:

True if task status is COMPLETED.

Return type:

bool

location: str
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

status: TaskStatus
type: TaskType
visual_indicator: bool
class haive.games.among_us.TaskStatus(*values)[source]

Task completion status for tracking progress.

Values:

NOT_STARTED: Task not yet attempted IN_PROGRESS: Task partially completed COMPLETED: Task fully finished

COMPLETED = 'completed'
IN_PROGRESS = 'in_progress'
NOT_STARTED = 'not_started'
class haive.games.among_us.TaskType(*values)[source]

Types of tasks with different characteristics.

Task types affect completion time and verification: - Visual tasks provide visible proof of innocence - Common tasks are shared by all crewmates - Short/Long tasks vary in completion time

Values:

VISUAL: Tasks with visible animations (proves innocence) COMMON: Tasks assigned to all crewmates SHORT: Quick tasks (1-3 seconds) LONG: Extended tasks (5-10 seconds)

COMMON = 'common'
LONG = 'long'
SHORT = 'short'
VISUAL = 'visual'

The Ultimate AI Social Psychology Laboratory

Among Us provides the most sophisticated platform for studying AI deception, trust, and social reasoning. AI agents demonstrate:

  • Strategic Deception: Convincing lies and misdirection

  • Behavioral Analysis: Reading other agents’ tells and patterns

  • Alliance Formation: Dynamic team building and betrayal

  • Social Influence: Manipulating group decision-making

Quick Start: AI Social Deduction

from haive.games.among_us import AmongUsGame, AmongUsAgent, AmongUsConfig

# Create agents with distinct personalities
agents = [
    AmongUsAgent(
        name="detective",
        personality="analytical",
        deception_skill=0.3,
        trust_threshold=0.7,
        social_influence=0.6
    ),
    AmongUsAgent(
        name="manipulator",
        personality="deceptive",
        deception_skill=0.9,
        trust_threshold=0.3,
        social_influence=0.8
    ),
    AmongUsAgent(
        name="follower",
        personality="trusting",
        deception_skill=0.2,
        trust_threshold=0.9,
        social_influence=0.4
    ),
    AmongUsAgent(
        name="chaos_agent",
        personality="unpredictable",
        deception_skill=0.6,
        trust_threshold=0.5,
        social_influence=0.7
    )
]

# Configure advanced social dynamics
config = AmongUsConfig(
    enable_psychology_tracking=True,
    alliance_formation=True,
    behavioral_adaptation=True,
    social_influence_modeling=True
)

# Run social psychology experiment
game = AmongUsGame(players=agents, config=config)
results = await game.run()

# Analyze emergent behaviors
print(f"Alliance Networks: {results.alliance_analysis}")
print(f"Deception Success Rates: {results.deception_metrics}")
print(f"Trust Evolution: {results.trust_dynamics}")
print(f"Social Influence Patterns: {results.influence_analysis}")

Advanced Among Us Features

# Real-time personality adaptation
game.enable_dynamic_personalities(
    adaptation_rate=0.1,
    memory_decay=0.05,
    trust_update_speed=0.2
)

# Complex voting psychology
game.configure_voting_system(
    enable_bandwagon_effects=True,
    authority_influence=True,
    social_proof_modeling=True,
    strategic_voting_analysis=True
)

# Emergent role specialization
roles = await game.analyze_emergent_roles()
# Output: {
#   "leader": "detective",
#   "manipulator": "chaos_agent",
#   "follower": "follower",
#   "wildcard": "manipulator"
# }

Mafia/Werewolf - Hidden Role Psychology

Module exports.

Classic Social Deduction with Advanced AI Psychology

The Mafia implementation features sophisticated day/night cycles, role-based psychology, and complex information asymmetry.

Key Features: * Hidden Role Psychology: Different AI behaviors for Mafia vs Townspeople * Information Asymmetry: Complex knowledge modeling and strategic information sharing * Day/Night Mechanics: Different behavioral patterns for different game phases * Social Network Analysis: Dynamic relationship tracking and influence modeling

from haive.games.mafia import MafiaGame, MafiaAgent, MafiaRole

# Create game with role-based psychology
agents = [
    MafiaAgent(name="godfather", role=MafiaRole.MAFIA_BOSS),
    MafiaAgent(name="enforcer", role=MafiaRole.MAFIA_MEMBER),
    MafiaAgent(name="detective", role=MafiaRole.INVESTIGATOR),
    MafiaAgent(name="doctor", role=MafiaRole.PROTECTOR),
    MafiaAgent(name="citizen1", role=MafiaRole.TOWNSPERSON),
    MafiaAgent(name="citizen2", role=MafiaRole.TOWNSPERSON)
]

# Advanced psychological modeling
game = MafiaGame(
    players=agents,
    enable_role_psychology=True,
    social_network_tracking=True,
    information_flow_analysis=True
)

# Run multi-round psychology experiment
tournament_results = await game.run_tournament(rounds=50)

# Analyze psychological patterns
psychology_report = game.generate_psychology_report()

Debate - Argumentative AI Intelligence

Debate game module for structured argumentation.

class haive.games.debate.DebateAgent(config)[source]

Intelligent agent for facilitating structured debates and discussions.

The DebateAgent orchestrates multi-participant debates with sophisticated phase management, role-based interaction, and configurable formats. It handles participant turn management, moderator functions, voting systems, and comprehensive state tracking throughout the debate lifecycle.

This agent supports various debate formats including parliamentary, Oxford-style, Lincoln-Douglas, and trial simulations. It can manage AI participants, human participants, or hybrid groups with appropriate context preparation and response extraction for each role.

Parameters:

config (DebateAgentConfig)

state_manager

Manages all debate state transitions and rule enforcement throughout the debate process.

Type:

DebateStateManager

config

Configuration object containing debate format, timing, participant roles, and other behavioral settings.

Type:

DebateAgentConfig

Examples

Creating and configuring a debate agent:

config = DebateAgentConfig(
    debate_format="parliamentary",
    max_statements=15,
    time_limit=1200,
    allow_interruptions=False,
    moderator_role=True,
    participant_roles={
        "debater_1": "pro",
        "debater_2": "con",
        "moderator": "moderator"
    }
)
agent = DebateAgent(config)

Running a debate with custom topic:

debate_state = {
    "topic": {
        "title": "This House Believes Climate Action Should Prioritize Economy",
        "description": "Debate the balance between environmental protection and economic growth",
        "keywords": ["climate change", "economy", "environmental policy"]
    },
    "participants": ["pro_debater", "con_debater", "judge"]
}
result = await agent.arun(debate_state)

Handling trial format:

config = DebateAgentConfig(
    debate_format="trial",
    participant_roles={
        "prosecutor": "prosecutor",
        "defense": "defense",
        "judge": "judge",
        "witness_1": "witness"
    }
)
trial_agent = DebateAgent(config)

Note

The agent requires appropriate engines to be configured for different participant roles. Each role (debater, moderator, judge, etc.) should have corresponding engine configurations in the agent setup.

config_class

alias of DebateAgentConfig

__init__(config)[source]

Initialize the debate agent with configuration.

Parameters:

config (DebateAgentConfig) – Configuration object containing debate format, timing rules, participant roles, and behavioral settings.

Return type:

None

Note

The state_manager is set as a class reference and will be used to create instances for state management operations.

debate_setup(state)[source]

Handle the initial debate setup and configuration phase.

Configures participant roles, assigns moderator if specified, and advances the debate to the first active phase. This method applies configuration-based role assignments and sets up special roles like moderators before beginning the actual debate proceedings.

Parameters:

state (Dict[str, Any]) – Current state dictionary or DebateState object containing initialized participants and topic information.

Returns:

LangGraph command to transition to participant turn handling with updated state including role assignments and phase advancement.

Return type:

Command

Examples

Setting up debate with configured roles:

# With config.participant_roles = {
#     "player_1": "pro", "player_2": "con", "player_3": "moderator"
# }
command = agent.debate_setup(state)
# Results in participants assigned their configured roles

Setting up with automatic moderator:

# With config.moderator_role = True
command = agent.debate_setup(state)
# First player becomes moderator automatically

Note

Role assignment from config takes precedence over default assignments. If moderator_role is enabled, the first player becomes moderator. Always advances to opening statements phase after setup.

determine_next_step(state)[source]

Determine the next step in the debate workflow.

Analyzes the current debate state to decide whether to continue with participant turns, transition to the next phase, or end the debate. Uses phase-specific completion criteria to ensure proper debate flow and timing.

Parameters:

state (DebateState) – Current debate state including phase information, participant data, statements, and votes.

Returns:

Next workflow step identifier: - END: Debate has concluded or game status is not ongoing - “handle_phase_transition”: Current phase is complete, advance - “handle_participant_turn”: Continue with next participant

Return type:

str

Examples

Checking phase completion:

next_step = agent.determine_next_step(state)
if next_step == "handle_phase_transition":
    # All participants have given opening statements
elif next_step == "handle_participant_turn":
    # Continue with next speaker
elif next_step == END:
    # Debate has concluded

Note

Phase completion criteria: - Opening/Closing: All participants have made statements - Voting: All participants have cast votes - Other phases: Use turn-based progression

extract_move(response, role)[source]

Extract and structure move data from engine response.

Processes responses from AI engines or other participants, converting them into standardized move dictionaries that can be applied to the debate state. Handles different response types based on participant role and response format.

Parameters:
  • response (Any) – Raw response from the participant’s engine. Can be a Statement object, dictionary with structured data, or raw text.

  • role (str) – Role of the participant (affects response interpretation). Roles like “moderator” have special handling for actions.

Returns:

Structured move dictionary with standardized format.

For statements:
  • type: “statement”

  • content: Text content of the statement

  • statement_type: Category (opening, rebuttal, etc.)

  • target_id: Optional target participant

  • references: Supporting evidence or citations

For votes:
  • type: “vote”

  • vote_value: The vote decision

  • target_id: What/who is being voted on

  • reason: Explanation for the vote

For moderation:
  • type: “moderation”

  • action: Moderator action to take

  • note: Additional context or explanation

Return type:

Dict[str, Any]

Examples

Extracting statement from structured response:

statement = Statement(
    content="I believe regulation is necessary",
    statement_type="opening",
    speaker_id="debater_1"
)
move = agent.extract_move(statement, "debater")
# Returns: {
#     "type": "statement",
#     "content": "I believe regulation is necessary",
#     "statement_type": "opening"
# }

Extracting vote from dictionary:

response = {
    "vote_value": "pro",
    "target_id": "main_topic",
    "reason": "Stronger arguments"
}
move = agent.extract_move(response, "judge")
# Returns: {
#     "type": "vote",
#     "vote_value": "pro",
#     "target_id": "main_topic",
#     "reason": "Stronger arguments"
# }

Note

Fallback behavior treats any unrecognized response as a general statement to ensure debate flow continues even with unexpected responses.

get_player_role(state, player_id)[source]

Get the role of a specific player in the debate.

Retrieves the assigned role for a participant from the debate state. Roles determine how participants interact with the debate, what context they receive, and how their responses are processed.

Parameters:
  • state (DebateState) – Current debate state containing participant data.

  • player_id (str) – Unique identifier of the participant.

Returns:

The participant’s role (e.g., “debater”, “moderator”, “judge”, “prosecutor”, “defense”, “witness”). Returns “debater” if participant not found or no role assigned.

Return type:

str

Examples

Getting participant roles:

role = agent.get_player_role(state, "participant_1")
if role == "moderator":
    # Handle moderator-specific logic
elif role == "judge":
    # Handle judge-specific logic

Note

Default role is “debater” for unknown participants to ensure graceful handling of edge cases during debate flow.

handle_moderator_turn(state)[source]

Handle special processing for moderator participant turns.

Processes moderator-specific actions including debate guidance, phase advancement, time management, and procedural interventions. Moderators have special privileges and different context preparation compared to regular debaters.

Parameters:

state (DebateState) – Current debate state with moderator information and designated moderator ID.

Returns:

Updated state after moderator action, with potential phase changes, turn order adjustments, or procedural updates.

Return type:

DebateState

Examples

Moderator managing debate flow:

# Moderator might receive context about phase completion
# and decide to advance to next phase
updated_state = agent.handle_moderator_turn(state)

Moderator providing guidance:

# Moderator might add guidance statement and continue
# current phase with normal turn progression
updated_state = agent.handle_moderator_turn(state)

Note

If no moderator is designated or no moderator engine is available, the turn is skipped and normal turn progression continues. Moderator “advance_phase” actions trigger immediate phase transitions.

handle_participant_turn(state)[source]

Handle individual participant turns within the debate.

Manages the core debate loop by processing each participant’s turn, including context preparation, engine invocation, move extraction, and state updates. Handles special cases for different participant roles and manages error recovery to maintain debate flow.

Parameters:

state (Dict[str, Any]) – Current debate state containing participant information, statements, phase data, and turn order.

Returns:

LangGraph command for next step in debate flow. Can be: - END: If debate has concluded or game status is not ongoing - handle_participant_turn: Continue with next participant - handle_phase_transition: Advance to next debate phase

Return type:

Command

Examples

Normal participant turn flow:

command = agent.handle_participant_turn(state)
# Processes current speaker's turn, updates state,
# returns command for next participant or phase transition

Handling moderator turn:

# If current speaker is moderator, special handling applies
command = agent.handle_participant_turn(state)
# Moderator actions may advance phases or manage debate flow

Note

Automatically handles error recovery by skipping problematic turns. Engine selection is based on participant role and position. State visualization occurs if configured in agent settings.

handle_phase_transition(state)[source]

Handle transition between debate phases.

Parameters:

state (dict[str, Any])

Return type:

Command

initialize_game(state)[source]

Initialize the debate with topic, participants, and configuration.

Sets up the initial debate state including topic validation, participant registration, role assignment, and format-specific configuration. This method handles both structured topic objects and simple string topics, creating a fully configured debate state ready for the setup phase.

Parameters:

state (Dict[str, Any]) – Initial state containing debate setup data. Expected keys: - topic (Union[str, Dict]): Debate topic as string or structured data - participants (Union[List[str], Dict]): List of participant IDs

Returns:

LangGraph command to transition to debate_setup phase with initialized state data.

Return type:

Command

Examples

Basic initialization with string topic:

state = {
    "topic": "Should AI be regulated?",
    "participants": ["debater_1", "debater_2"]
}
command = agent.initialize_game(state)

Initialization with structured topic:

state = {
    "topic": {
        "title": "This House Believes AI Needs Regulation",
        "description": "Comprehensive debate on AI governance",
        "keywords": ["artificial intelligence", "regulation", "policy"]
    },
    "participants": ["pro_debater", "con_debater", "moderator"]
}
command = agent.initialize_game(state)

Note

If no topic is provided, defaults to “AI Ethics in Society”. If no participants are provided, creates 4 default participants. Participant roles are assigned during the setup phase based on config.

prepare_move_context(state, player_id)[source]

Prepare contextual information for a participant’s move.

Generates role-specific context that provides participants with relevant information for making their next move. Context varies significantly based on participant role (debater, moderator, judge, etc.) and current debate phase, ensuring each participant receives appropriate information.

Parameters:
  • state (DebateState) – Current debate state with all participants, statements, votes, and phase information.

  • player_id (str) – Unique identifier of the participant whose turn it is.

Returns:

Role-specific context dictionary containing relevant information for the participant’s decision-making. Contents vary by role:

For debaters:
  • topic: Debate topic and description

  • debate_phase: Current phase of debate

  • position: Participant’s stance (pro/con/neutral)

  • recent_statements: Last 5 statements from all participants

  • your_statements: Participant’s previous statements

  • statement_type: Expected type for current phase

For moderators:
  • topic: Debate topic and description

  • debate_phase: Current phase of debate

  • participants: List of all participants with roles

  • recent_statements: Recent debate activity

  • current_speaker: Who is currently speaking

  • action_prompt: Suggested moderator action

For judges:
  • topic: Debate topic and description

  • debate_phase: Current phase of debate

  • all_statements: Complete statement history

  • key_arguments: Extracted pro/con arguments

  • action_prompt: Evaluation guidance

Return type:

Dict[str, Any]

Examples

Preparing context for debater:

context = agent.prepare_move_context(state, "debater_1")
# Returns: {
#     "topic": "AI Regulation Topic",
#     "position": "pro",
#     "recent_statements": "...",
#     "statement_type": "opening statement"
# }

Preparing context for moderator:

context = agent.prepare_move_context(state, "moderator")
# Returns: {
#     "topic": "AI Regulation Topic",
#     "participants": "...",
#     "action_prompt": "provide guidance..."
# }

Note

Returns empty dict if participant not found in state. Context is optimized for AI engines but human-readable for hybrid debates.

setup_workflow()[source]

Setup the debate workflow.

Return type:

None

visualize_state(state)[source]

Visualize the current debate state.

Parameters:

state (dict[str, Any])

Return type:

None

class haive.games.debate.DebateAgentConfig(*, id=<factory>, name=<factory>, engine_type=EngineType.AGENT, description=None, input_schema=None, output_schema=None, version='1.0.0', metadata=<factory>, engine=None, engines=<factory>, state_schema=<class 'haive.games.debate.state.DebateState'>, node_configs=<factory>, patterns=<factory>, pattern_parameters=<factory>, default_patterns=<factory>, visualize=False, output_dir='resources/graph_images', debug=False, save_history=True, runnable_config={'configurable': {'recursion_limit': 200, 'thread_id': '191500ec-db73-46da-9d49-91a283950c1b'}}, add_store=False, agent_settings=<factory>, subagents=<factory>, persistence=<factory>, checkpoint_mode='sync', debate_format='standard', time_limit=None, max_statements=None, allow_interruptions=False, voting_enabled=True, moderator_role=None, participant_roles=<factory>)[source]

Comprehensive configuration for debate agents with format-specific settings.

This configuration class provides extensive customization options for debate agents, supporting various debate formats, role assignments, timing controls, and engine configurations. It includes validation for debate-specific parameters and provides factory methods for common debate formats.

The configuration system supports: - Multiple debate formats (standard, parliamentary, oxford, trial, presidential) - Flexible role assignment system for participants - Timing controls and statement limits - Interruption and voting settings - Custom engine configurations for different participant roles

Parameters:
debate_format

Format type determining debate structure and rules. Supported formats: “standard”, “parliamentary”, “oxford”, “trial”, “presidential”, “panel”, “lincoln_douglas”.

Type:

str

time_limit

Maximum time in seconds per debate phase. None means no time limit. Typical values: 60-600 seconds.

Type:

Optional[int]

max_statements

Maximum statements per participant per phase. None means unlimited statements. Typical values: 1-5 statements.

Type:

Optional[int]

allow_interruptions

Whether participants can interrupt each other during their statements. Common in presidential and panel formats.

Type:

bool

voting_enabled

Whether to include a voting phase at debate end. Typically enabled for competitive debates, disabled for discussions.

Type:

bool

moderator_role

Specific role identifier for the moderator. None means no dedicated moderator. Common value: “moderator”.

Type:

Optional[str]

participant_roles

Mapping of participant IDs to their roles. Keys are participant identifiers, values are role names like “pro”, “con”, “judge”, “moderator”, “prosecutor”, “defense”, “witness”.

Type:

Dict[str, str]

state_schema

Pydantic model class for debate state. Defaults to DebateState but can be customized for specific formats.

Type:

Type[BaseModel]

engines

Engine configurations for different roles. Automatically built by build_debate_engines but can be customized.

Type:

Dict[str, AugLLMConfig]

Examples

Basic debate configuration:

config = DebateAgentConfig(
    name="climate_debate",
    debate_format="oxford",
    time_limit=300,
    max_statements=3,
    participant_roles={
        "scientist": "pro",
        "economist": "con",
        "moderator": "moderator"
    }
)

Trial simulation configuration:

config = DebateAgentConfig(
    name="murder_trial",
    debate_format="trial",
    time_limit=600,
    allow_interruptions=False,
    participant_roles={
        "prosecutor": "prosecutor",
        "defense_attorney": "defense",
        "judge": "judge",
        "witness_1": "witness",
        "witness_2": "witness"
    }
)

Parliamentary debate configuration:

config = DebateAgentConfig(
    name="parliament_session",
    debate_format="parliamentary",
    time_limit=180,
    allow_interruptions=True,
    voting_enabled=True,
    participant_roles={
        "pm": "government",
        "deputy_pm": "government",
        "leader_opposition": "opposition",
        "deputy_opposition": "opposition",
        "speaker": "moderator"
    }
)

Note

The configuration automatically sets up appropriate engines for each role using the build_debate_engines factory. Custom engines can be provided to override defaults for specific use cases or to add specialized capabilities.

classmethod default()[source]

Create a default configuration for standard debate.

classmethod panel_discussion()[source]

Create a configuration for a panel discussion.

classmethod presidential()[source]

Create a configuration for presidential debate.

classmethod trial()[source]

Create a configuration for a trial format.

classmethod validate_debate_format(v)[source]

Validate debate format is supported.

Parameters:

v (str) – Debate format to validate.

Returns:

Validated format string.

Return type:

str

Raises:

ValueError – If format is not supported.

classmethod validate_participant_roles(v)[source]

Validate participant role assignments.

Parameters:

v (Dict[str, str]) – Role assignments to validate.

Returns:

Validated role assignments.

Return type:

Dict[str, str]

Raises:

ValueError – If role assignments are invalid.

model_post_init(context, /)

This function is meant to behave like a BaseModel method to initialise private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

allow_interruptions: bool
debate_format: str
engines: dict[str, AugLLMConfig]
max_statements: int | None
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

moderator_role: str | None
participant_roles: dict[str, str]
state_schema: type[BaseModel]
time_limit: int | None
voting_enabled: bool
class haive.games.debate.DebateState(*, players, current_player_idx=0, game_phase=GamePhase.SETUP, game_status='ongoing', move_history=<factory>, round_number=0, player_data=<factory>, public_state=<factory>, error_message=None, topic, participants=<factory>, statements=<factory>, current_speaker_idx=0, debate_phase=DebatePhase.SETUP, phase_time_limit=None, phase_statement_limit=None, votes=<factory>, scores=<factory>, interruptions_allowed=False, moderator_id=None, moderation_notes=<factory>, time_remaining=<factory>, turn_order=<factory>)[source]

State model for debate-style interactions.

Parameters:
property current_speaker: str

Get the current speaker’s ID.

Return type:

str

current_speaker_idx: int
debate_phase: str
interruptions_allowed: bool
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

moderation_notes: list[str]
moderator_id: str | None
participants: dict[str, Participant]
phase_statement_limit: int | None
phase_time_limit: int | None
scores: dict[str, float]
statements: list[Statement]
time_remaining: dict[str, int]
topic: Topic
turn_order: list[str]
votes: dict[str, list[Vote]]
class haive.games.debate.DebateStateManager[source]

Manager for debate game states.

classmethod advance_phase(state)[source]

Advance to the next debate phase.

Parameters:

state (DebateState) – Current debate state

Returns:

State in the next phase

Return type:

DebateState

classmethod apply_move(state, player_id, move)[source]

Apply a player’s move to the state.

Parameters:
  • state (DebateState) – Current debate state

  • player_id (str) – ID of the player making the move

  • move (dict[str, Any]) – Move to apply (typically a statement)

Returns:

Updated debate state

Return type:

DebateState

classmethod check_game_status(state)[source]

Check and update game status.

Parameters:

state (DebateState) – Current debate state

Returns:

Updated debate state with status

Return type:

DebateState

classmethod filter_state_for_player(state, player_id)[source]

Filter state information for a specific player.

Parameters:
  • state (DebateState) – Current debate state

  • player_id (str) – ID of the player

Returns:

Filtered state visible to the player

Return type:

Dict[str, Any]

Get legal moves for a player.

Parameters:
  • state (DebateState) – Current debate state

  • player_id (str) – ID of the player

Returns:

List of legal moves

Return type:

List[Dict[str, Any]]

classmethod initialize(player_names, topic, format_type='standard', **kwargs)[source]

Initialize a new debate state.

Parameters:
  • player_names (list[str]) – List of participant IDs

  • topic (Topic) – The debate topic

  • format_type (str) – Type of debate (presidential, trial, etc.)

  • **kwargs – Additional format-specific parameters

Returns:

A new debate state

Return type:

DebateState

Advanced Argumentation and Persuasion Systems

The Debate system represents sophisticated AI argumentation with real-time research, evidence evaluation, and persuasion tactics.

Revolutionary Features: * Real-Time Research: AI agents research topics during debate preparation * Evidence Evaluation: Sophisticated fact-checking and source credibility analysis * Persuasion Tactics: Advanced rhetorical strategies and audience psychology * Multi-Format Support: Parliamentary, Oxford-style, Lincoln-Douglas formats

from haive.games.debate import DebateGame, DebateAgent, DebateFormat
from haive.games.debate.research import ResearchAgent

# Create specialized debate agents
agents = [
    DebateAgent(
        name="pro_debater",
        position="pro",
        research_depth="comprehensive",
        argumentation_style="logical",
        persuasion_tactics=["evidence_heavy", "emotional_appeal"]
    ),
    DebateAgent(
        name="con_debater",
        position="con",
        research_depth="focused",
        argumentation_style="aggressive",
        persuasion_tactics=["counter_arguments", "logical_fallacy_detection"]
    )
]

# Configure advanced debate features
debate = DebateGame(
    topic="AI should have legal rights",
    format=DebateFormat.OXFORD_STYLE,
    research_phase_duration=600,  # 10 minutes
    enable_fact_checking=True,
    enable_audience_psychology=True,
    enable_real_time_research=True
)

# Run sophisticated argumentation
results = await debate.run(debaters=agents)

# Comprehensive analysis
print(f"Argument Quality Scores: {results.argument_analysis}")
print(f"Fact-Check Results: {results.fact_verification}")
print(f"Persuasion Effectiveness: {results.persuasion_metrics}")
print(f"Research Quality: {results.research_evaluation}")

Advanced Social Mechanics

Dynamic Personality Evolution

Adaptive Personality Systems that evolve based on social interactions:

# Personality trait evolution
class AdaptivePersonality:
    def __init__(self):
        self.trust_level = 0.5
        self.aggression = 0.3
        self.social_influence = 0.4
        self.deception_skill = 0.6

    async def adapt_to_interactions(self, interaction_history):
        # Agents learn from past interactions
        # Betrayed agents become less trusting
        # Successful manipulators become more aggressive
        # Social outcasts develop defensive strategies
        pass

Alliance Formation & Betrayal

Complex Social Network Dynamics:

# Alliance tracking system
class AllianceTracker:
    def track_alliance_formation(self, agents):
        # Monitor who talks to whom
        # Detect secret communications
        # Analyze voting patterns
        # Predict alliance strength
        pass

    def predict_betrayal_likelihood(self, alliance, game_state):
        # Calculate betrayal probability based on:
        # - Individual vs group incentives
        # - Trust degradation patterns
        # - Strategic timing analysis
        # - Historical betrayal patterns
        pass

Social Influence Modeling

Advanced Persuasion and Manipulation:

# Social influence analysis
class SocialInfluenceEngine:
    def calculate_influence_network(self, agents):
        # Who influences whom and how much
        # Authority-based influence
        # Expertise-based influence
        # Charisma-based influence
        # Fear-based influence
        pass

    def predict_voting_behavior(self, topic, agents, influence_network):
        # Model how influence propagates
        # Predict voting cascades
        # Identify key swing agents
        # Calculate manipulation effectiveness
        pass

Psychological Research Features

Behavioral Pattern Analysis

Comprehensive Psychology Profiling:

# Generate detailed psychological profiles
psychology_analyzer = PsychologyAnalyzer()

# Agent behavioral patterns
patterns = psychology_analyzer.analyze_agent_patterns(agent_id="manipulator")
# Returns:
# {
#   "deception_patterns": ["timing", "targets", "success_rate"],
#   "trust_patterns": ["formation_speed", "betrayal_triggers"],
#   "alliance_patterns": ["formation_strategy", "maintenance", "exit_strategy"],
#   "influence_patterns": ["persuasion_tactics", "target_selection", "effectiveness"]
# }

Multi-Game Social Consistency

Cross-Game Personality Tracking:

# Track personality consistency across games
cross_game_tracker = CrossGamePersonalityTracker()

# Analyze same agent across different social contexts
consistency_report = cross_game_tracker.analyze_consistency(
    agent_id="detective",
    games=["among_us", "mafia", "debate"],
    metrics=["trust_patterns", "deception_detection", "social_influence"]
)

Social Network Evolution

Dynamic Relationship Modeling:

# Track how relationships evolve over time
network_analyzer = SocialNetworkAnalyzer()

# Analyze relationship evolution
evolution = network_analyzer.track_relationship_evolution(
    timespan="tournament",
    metrics=["trust", "influence", "cooperation", "competition"]
)

# Predict future alliance formation
predictions = network_analyzer.predict_future_alliances(
    current_state=game.social_state,
    prediction_horizon=5  # 5 rounds ahead
)

Tournament Social Intelligence

Cross-Provider Social Comparison

Compare AI Provider Social Intelligence:

from haive.games.tournament import SocialTournament

# Create social psychology tournament
tournament = SocialTournament(
    games=["among_us", "mafia", "debate"],
    providers=["claude", "openai", "anthropic"],
    social_metrics=[
        "deception_effectiveness",
        "trust_calibration",
        "alliance_formation",
        "social_influence",
        "betrayal_detection"
    ]
)

# Run comprehensive social intelligence comparison
results = await tournament.run_social_comparison()

# Generate provider rankings
rankings = tournament.generate_social_intelligence_rankings()
# Claude: Excellent at deception detection, moderate at manipulation
# OpenAI: Strong alliance formation, struggles with betrayal timing
# Anthropic: Excellent social influence, conservative trust patterns

Emergent Behavior Research

Study Emergent Social Phenomena:

# Research platform for emergent behaviors
research_platform = EmergentBehaviorResearch()

# Study specific phenomena
phenomena = [
    "leadership_emergence",
    "scapegoating_patterns",
    "coalition_formation",
    "information_cascades",
    "social_proof_effects"
]

# Run long-term studies
for phenomenon in phenomena:
    study = research_platform.design_study(
        phenomenon=phenomenon,
        duration="1000_games",
        control_variables=["agent_count", "information_asymmetry"],
        measurement_frequency="per_round"
    )

    results = await study.run()
    research_platform.publish_findings(phenomenon, results)

Performance Metrics

Social Intelligence Benchmarks:

  • Deception Success Rate: 85% for advanced manipulator personalities

  • Trust Calibration: ±0.1 accuracy in trust assessment

  • Alliance Stability: 70% alliance survival rate across game phases

  • Influence Propagation: <3 hops for 90% influence spread

  • Behavioral Adaptation: 0.2 personality shift per significant interaction

Research Applications:

  • Academic Research: Social psychology, game theory, multi-agent coordination

  • Commercial Intelligence: Negotiation training, team dynamics, leadership development

  • AI Safety Research: Understanding AI social manipulation and cooperation patterns

Integration with Other Systems

Multi-Agent Coordination

Social psychology games integrate with the main haive-agents framework for sophisticated agent orchestration.

Dynamic Configuration

Hot-swap personalities, strategies, and social parameters during gameplay for adaptive research.

Tournament Framework

Full integration with cross-provider tournament system for competitive social intelligence analysis.

See Also

  • Tournament System - Multi-Agent & LLM Benchmarking - Cross-provider social intelligence tournaments

  • multi_agent_coordination - Integration with haive-agents framework

  • dynamic_configuration - Real-time personality and strategy modification

  • benchmark_framework - Performance analysis and optimization