โ ๏ธ Note: This project is HEAVILY WORK IN PROGRESS. Features, APIs, and CLI integrations are subject to rapid change. Use with caution and expect bugs!
AI Mafia is a Python-based simulation engine where Large Language Models (LLMs) play the classic social deduction game Mafia against each other. Watch as AI agents debate, deceive, and deduce their way to victory โ or jump in and play alongside them as a human player!
๐ฎ Play Against AI: Enable human mode and test your deception skills against the world's most advanced language models. Can you outsmart GPT, Claude, and Gemini in a battle of wits?
Supports multiple AI providers including OpenAI, Anthropic, Google Gemini, and Qwen.
Watch the most advanced AI models from competing companies deceive and outsmart each other:
| Player | Provider | Model |
|---|---|---|
| Rick | OpenAI | GPT-5.2 |
| Morty | OpenAI | GPT-5.1 |
| Sonnet | Anthropic | Claude Sonnet 4 |
| Haiku | Anthropic | Claude Haiku 3.5 |
| Pro | Gemini 2.5 Pro | |
| Flash | Gemini 2.5 Flash | |
| Preview | Gemini 3 Flash Preview | |
| Qwen | Groq | Qwen 3 Coder |
Check out some of our best simulated games to see high-level AI deception and deduction in action:
-
Example: The "Manipulation Masterclass"
- Highlights: A flawless victory achieved by weaponizing the "Voice of Reason." The Mafia defends a framed target so effectively that the Town begins executing its own detectives for being "too aggressive." A masterclass in sociological manipulation where the villains are treated as the town's moral compass.
-
Example: The "Cursed Protagonist"
- Highlights: A tragedy of errors where the Town executes a Villager for being "too perfect." The Mafia weaponize "Graveyard Analysis" by systematically killing anyone who interacts with their target, framing him as a silencer. Watch how the Mafia survives a Day 2 trial by convincing the Town that catching scum is "counterproductive."
-
Example 1: The "Trust the Pattern" Trap
- Highlights: Day 1 starts with a brilliant "accountability framework" proposed by Rick (Town) to trap the Mafia. It works perfectly... until the Mafia flips the script. By the end, a Town player (Sonnet) is executed while confidently explaining why their execution is mathematically impossible if they were Town. Watch how "perfect logic" can be weaponized to lead the Town off a cliff.
-
Example 2: The "Mafia Math" Deception
- Highlights: A masterclass in 1v1v1 endgame manipulation! With 3 players left (1 Mafia, 2 Town), Morty (Town) is absolutely convinced he has solved the game using "parity math." He clears one player (Pro) completely based on game theory. But is his math right? Or is he confidently walking into a trap set by a "confirmed townie"? See if Flash can spot the flaw before it's too late.
-
Example 3: 3v2 LYLO: The "Ghost Narrative" Logic Trap
- Highlights: In a tense 3v2 finale, Town player Preview brilliantly exposes a 'Weaponized Consensus' strategy used to control the game. The table is set for a massive turnaround, but it all hinges on Qwen. Will Qwen see through the 'Ghost Narrative,' or will the 'Wall of Logic' prove too strong? Watch the psychological pressure cooker explode.
-
Example 4: The "Illogical Killer" Gambit
- Highlights: Pro (Mafia) attempts a high-risk "Illogical Killer" gambit. After the only player voting for him is killed, he uses the paradox as his defense: "Why would I silence my own critic?" In the endgame, he targets the quietest player (Qwen), arguing that his own "loud and messy" play is proof of innocence. It becomes a showdown of narratives: is Pro a confused Villager, or is he hiding in plain sight?
-
Example 5: The "Victory Speech" Bluff
- Highlights: Facing a mathematical loss in a 2v1 endgame, Haiku (Mafia) tries a bold anti-strategy: he congratulates the Town on their win and abstains from voting, refusing to nominate anyone. It's a high-stakes dare: is he a defeated Villager accepting fate, or a Scum player hoping the Town will eat itself if he refuses to fight? Watch the final two Townies spiral as they try to interpret the silence.
-
Example 6: The "Redemption Arc"
- Highlights: A Town misled by a martyr's error hangs an innocent... only for the loudest accuser to turn Detective and face the lying manipulator in a 1v1 showdown. A masterclass in deception and recovery.
-
Example 7: The "Rustling" Deception
- Highlights: A simple Mafia lie about 'hearing rustling' becomes accepted fact. The Town executes a truthful Villager for contradicting it, and eventually hangs the Real Cop because his actions don't fit the fake narrative. A perfect demo of how a consistent lie defeats the messy truth.
-
Example 8: The "Poisoned Well" Gambit
- Highlights: In their final breath, a caught Mafia member frames a Villager as a "betraying partner." The Town takes the bait, while the actual remaining Mafia member secures their trust by being the only one to defend the innocent victim. A tense finale where "statistical impossibility" faces off against "earned trust."
-
Example 9: The "Clutch Cop" Reveal
- Highlights: A game defined by a single Day 1 slip-up that cascades into a series of deadly misunderstandings. Features a heart-stopping LYLO (Lynch or Lose) moment where the entire game hinges on one player's decision to trust a last-second claim. Watch for a masterclass in "Rules Lawyering" vs "Behavioral Analysis" in the final 1v2 showdown.
- Multi-Model Roster: Pit different models against each other (e.g., GPT-5.2 vs Claude Sonnet vs Gemini 2.5).
- Dual Modes: Run using Local CLI Tools (free/cheap if using local subscriptions) or via Direct API Calls.
- Automated Game Loop: The engine handles phases (Day, Defense, Voting, Last Words, Night), turn management, and death logic automatically.
- Text-to-Speech: Each player has a unique voice (Edge TTS) - hear the AI debate and deceive!
- Detailed Logs: Observe "inner thoughts" of models to understand their strategy and deception.
- Rich Terminal UI: Formatted output with icons for Day/Night cycles and role reveals.
- Game Persistence: Game logs saved to
games/directory with timestamps. - Persistent Memory ๐ง : Models learn from previous games! They write a strategic summary after each match and use it in the next one.
- Human Player Mode ๐ฎ: Play alongside AI models! One human can join the game via terminal input.
Play Mafia alongside AI models! Enable the human player in config.py to join as a regular player with a randomly assigned role.
In config.py, find the human player entry at the bottom and set active: True:
# HUMAN PLAYER - Set active: True to play as human (terminal input)
{"active": True, "use_cli": False, "name": "You", "provider": "human", "model": "human", "voice": "en-US-AriaNeural", "role": "random"},You can set a preferred role for yourself (or any player) using the role field:
"random"- Default, randomly assigned"mafia"- Prefer Mafia role"cop"- Prefer Cop role"villager"- Prefer Villager role
# Play as Mafia
{"active": True, "name": "Player 1", "provider": "human", "model": "human", "voice": "en-US-AriaNeural", "role": "mafia"},Note: Role preferences are honored when possible, but may be overridden if too many players request the same role (e.g., only 2 Mafia slots available).
-
Spoiler-Free Console: You only see what your character would know:
- No other players' strategies (๐ญ)
- No role icons for other players
- Night actions only visible if you're Mafia or Cop
- Full game log still saved to
games/for post-game review
-
Your Role: Shown privately at game start (random assignment like AI players)
-
Input Prompts: When it's your turn, you'll see prompts:
Day Phase:
>>> Your speech: [type your speech here]
>>> Nominate (or Enter to skip): [player name or Enter]
Trial Voting:
>>> Vote for: [player name]
Night Phase (Mafia):
>>> Your thoughts: [internal monologue]
>>> Kill target: [player name]
Night Phase (Cop):
>>> Your thoughts: [internal monologue]
>>> Investigate: [player name]
Night Phase (Villager):
>>> You fall asleep...
- Just type player names directly (no JSON needed)
- Press Enter to skip nomination on Day phase
- TTS continues for AI players so you can hear their speeches
- Check
games/game_*.txtafter the game to see the full log with all secrets revealed
-
Clone the Repository
git clone https://github.com/your-username/ai-mafia.git cd ai-mafia -
Create a Virtual Environment
python3 -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install Dependencies
pip install -r requirements.txt
-
Configuration (Env Vars) Create a
.envfile in the root directory and add your API keys (needed for API mode or some CLI auths):OPENAI_API_KEY=sk-... ANTHROPIC_API_KEY=sk-ant-... GEMINI_API_KEY=AIza... GROQ_API_KEY=gsk_...
Simply run the main script:
python main.pyFollow the on-screen prompts. You will need to press ENTER to advance the game state after each agent moves, allowing you to read specific turns.
If AUTO_CONTINUE = True is set in engine.py, the game will proceed automatically.
- Pause: Press SPACE during the 2-second delay between turns to pause the game.
- Resume: Press SPACE again to resume.
The game now features a learning system:
- Loading: At the start of a game, players load their "Memory" from
memories/{Name}.txt. - Reflection Phase: After the game ends, all players (living and dead) analyze the full logs (including secret Mafia communications).
- Learning: They generate a new 300-word strategic summary, combining old wisdom with new lessons. This file is overwritten for the next game.
Configuration:
In engine.py, you can toggle this system:
MEMORY_ENABLED = True # Set to False to disable memory/learningThe game supports two distinct modes of operation. You can switch between them by editing the api_clients.py file.
- Best for: Running models locally or via already-authenticated CLI tools (saving API costs).
- How it works: The engine shells out to command-line tools like
codex,claude,gemini, andqwen. - Prerequisites: You must have these tools installed in your terminal and authenticated.
- How to Enable:
- Open
api_clients.py. - Find the line
USE_CLI = False(or true). - Set it to True:
USE_CLI = True
- Open
- Best for: Direct, stable connection to model providers using standard API keys.
- How it works: Uses official Python SDKs (
openai,anthropic,google-genai) to send requests over the network. - Prerequisites: You need a
.envfile with valid API keys (see Installation). - How to Enable:
- Open
api_clients.py. - Find the line
USE_CLI = True. - Set it to False:
USE_CLI = False
- Open
If using API Key Mode, ensure your .env file is populated:
# .env file
OPENAI_API_KEY=sk-... # For GPT models
ANTHROPIC_API_KEY=sk-ant-... # For Claude models
GEMINI_API_KEY=AIza... # For Gemini models
GROQ_API_KEY=gsk_... # For Llama/Qwen modelsNote: In CLI mode, these keys might not be needed if your terminal tools are already logged in (e.g., via
glcloud auth loginor similar).
The game uses Edge TTS (free Microsoft neural voices) to give each player a unique voice.
Configure in engine.py:
TTS_ENABLED = True # Set to False to disable
TTS_RATE = "+20%" # Speech speed: "+20%" faster, "-10%" slowerEach player has a distinct voice accent (American, British, Australian, Indian, Irish, Canadian, South African) defined in ROSTER_CONFIG.
Requirements: pip install edge-tts (auto-installed with requirements.txt)
You can customize the game roster in engine.py. Look for ROSTER_CONFIG.
Each entry requires:
name: Display name of the player.provider:openai,anthropic,google, orgroq.model: The exact model string (e.g.,gpt-5.2for CLI orgpt-4ofor API).voice: Edge TTS voice ID (e.g.,en-US-GuyNeural,en-GB-RyanNeural).role: (Optional) Preferred role -"random","mafia","cop", or"villager".
Example:
ROSTER_CONFIG = [
{"name": "Mastermind", "provider": "openai", "model": "gpt-5.2", "role": "random"},
{"name": "The Poet", "provider": "anthropic", "model": "haiku", "role": "mafia"},
]# engine.py
ROSTER_CONFIG = [
{"name": "Agent Name", "provider": "openai", "model": "gpt-4o"},
# ... add up to 8 players
]- Roles:
- Mafia (2): Know each other. Goal is to eliminate all Town members.
- Villagers (6): Do not know who is who. Goal is to vote out the Mafia.
- Phases:
- Day: All players speak publicly.
- Voting: Players vote to eliminate someone. Majority rules.
- Night: Mafia perform a secret kill.
The game generates detailed logs in the /logs directory:
public_logs.txt: What the players see.{PlayerName}_history.txt: Full context window for a specific agent (includes debugging info).memories/: Persistent strategy files for each player key.
Feel free to fork and submit PRs to add new providers, improved prompting strategies, or web interfaces!