- unwind ai
- Posts
- Build a Multi-Agent Chess Game
Build a Multi-Agent Chess Game
Fully functional AI agent app with step-by-step instructions (100% opensource)
Ever wondered what would happen if you let two AI agents play chess against each other? Let's build something fun - a chess game where two AI agents powered by GPT-4o battle it out on the board, while a third agent makes sure they play by the rules.
For this app, we’re using Microsoft’s Autogen - a powerful open-source multi-agent framework that makes it super easy to create and orchestrate multiple AI agents. What's cool about AutoGen is that it handles all the complex agent-to-agent communication for us, so we can focus on the fun part - making our AI chess players smart and strategic.
What We’re Building
We'll create a Streamlit app where two AI agents play chess against each other. One controls the white pieces, the other black, and a board proxy agent acts as the referee to keep everything fair and square.
Three main AI agents:
Player White: GPT-4o-powered strategic decision-maker
Player Black: GPT-4o-powered tactical opponent
Game Master: Validation agent for move legality and game state
You'll be able to watch the agents' strategic thinking process in real-time through the terminal output while the game is in progress. The number of turns is configurable - perfect for quick test games or longer battles. Once all turns are complete, you'll see a visual history of the entire game in the UI, with the chess board showing each move (complete with helpful arrows showing piece movement).
Each turn follows this flow:
The active agent requests available moves from the Game Master
The agent analyzes the board and chooses a move
The Game Master validates and executes the move
The board updates and displays the new position
Control passes to the other agent
Prerequisites
Before we begin, make sure you have the following:
Python installed on your machine (version 3.10 or higher is recommended)
Your OpenAI API key
A code editor of your choice (we recommend VS Code or PyCharm for their excellent Python support)
Basic familiarity with Python programming
Step-by-Step Instructions
Setting Up the Environment
First, let's get our development environment ready:
Clone the GitHub repository:
git clone https://github.com/Shubhamsaboo/awesome-llm-apps.git
Go to the ai_chess_game folder:
cd ai_agent_tutorials/ai_chess_game
Install the required dependencies:
pip install -r requirements.txt
Get your API Key: You'll need to obtain OpenAI API key - Create a new account > Go to Dashboard > Navigate to API Keys > Generate a new key
Creating the Streamlit App
Let’s create our app. Create a new file ai_chess_agents.py
and add the following code:
Let's set up our imports and initialize session state:
import chess
import chess.svg
import streamlit as st
from autogen import ConversableAgent, register_function
# Initialize session state
if "openai_api_key" not in st.session_state:
st.session_state.openai_api_key = None
if "board" not in st.session_state:
st.session_state.board = chess.Board()
Create chess move execution function:
def execute_move(move: str) -> str:
try:
chess_move = chess.Move.from_uci(move)
if chess_move not in st.session_state.board.legal_moves:
return f"Invalid move: {move}"
st.session_state.board.push(chess_move)
st.session_state.made_move = True
# Generate board visualization
board_svg = chess.svg.board(
st.session_state.board,
arrows=[(chess_move.from_square, chess_move.to_square)],
size=400
)
Add move validation and available moves function:
def available_moves() -> str:
available_moves = [str(move) for move in st.session_state.board.legal_moves]
return "Available moves are: " + ",".join(available_moves)
def check_made_move(msg):
if st.session_state.made_move:
st.session_state.made_move = False
return True
return False
Create White Agent:
agent_white = ConversableAgent(
name="Agent_White",
system_message="You are a professional chess player and you play as white.",
llm_config={"config_list": agent_white_config_list, "cache_seed": None},
)
# Register functions
register_function(
execute_move,
caller=agent_white,
executor=game_master,
name="execute_move"
)
register_function(
available_moves,
caller=agent_white,
executor=game_master,
name="available_moves"
)
Create Black Agent:
agent_black = ConversableAgent(
name="Agent_Black",
system_message="You are a professional chess player and you play as black.",
llm_config={"config_list": agent_black_config_list}
)
# Register similar functions for black agent
Create Game Master Agent:
game_master = ConversableAgent(
name="Game_Master",
llm_config=False,
is_termination_msg=check_made_move,
default_auto_reply="Please make a move.",
human_input_mode="NEVER"
)
Set up agent interaction:
agent_white.register_nested_chats(
trigger=agent_black,
chat_queue=[{
"sender": game_master,
"recipient": agent_white,
"summary_method": "last_msg",
}]
)
agent_black.register_nested_chats(
trigger=agent_white,
chat_queue=[{
"sender": game_master,
"recipient": agent_black,
"summary_method": "last_msg",
}]
)
Create Streamlit interface:
st.title("Chess with AutoGen Agents")
st.sidebar.title("Chess Agent Configuration")
max_turns_input = st.sidebar.number_input(
"Enter number of turns:",
min_value=1,
max_value=1000,
value=st.session_state.max_turns
)
Implement game controls:
if st.button("Start Game"):
st.session_state.board.reset()
st.session_state.made_move = False
chat_result = agent_black.initiate_chat(
recipient=agent_white,
message="Let's play chess!",
max_turns=st.session_state.max_turns
)
Display move history:
st.subheader("Move History")
for i, move_svg in enumerate(st.session_state.move_history):
move_by = "Agent White" if i % 2 == 0 else "Agent Black"
st.write(f"Move {i + 1} by {move_by}")
st.image(move_svg)
Running the App
With our code in place, it's time to launch the app.
In your terminal, navigate to the project folder, and run the following command
streamlit run ai_chess_agents.py
Streamlit will provide a local URL (typically http://localhost:8501).
Working Application Demo
Conclusion
You've just built a multi-agent chess game where two AI agents duke it out on the board! Pretty cool, right?
Want to make it even better? Here are some fun ideas:
Add a feature to play against one of the AI agents yourself
Implement different difficulty levels by adjusting the agents' system prompts
Add move analysis commentary from a third AI agent
Create a tournament system where multiple AI agents compete
Keep experimenting and have fun watching these AI agents try to outsmart each other!
We share hands-on tutorials like this 2-3 times a week, to help you stay ahead in the world of AI. If you're serious about leveling up your AI skills and staying ahead of the curve, subscribe now and be the first to access our latest tutorials.
Reply