Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tic Tac Toe example #2066

Merged
merged 37 commits into from
Feb 15, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
ac546ab
feat: init agents
anuragts Feb 10, 2025
01501d6
fix: update model
anuragts Feb 10, 2025
3756cdb
feat: Implement Tic Tac Toe game with AI agents
anuragts Feb 10, 2025
63b20a0
feat: streamlit
anuragts Feb 10, 2025
2f9d1be
feat: Add move history display in Tic Tac Toe game
anuragts Feb 10, 2025
fecf056
fix: change to o3 mini and add config class
anuragts Feb 10, 2025
fea085a
feat: Add Ollama model support in ModelConfig
anuragts Feb 10, 2025
549facd
format
anuragts Feb 10, 2025
d8fb802
feat: Enhance Tic Tac Toe game configuration and documentation
anuragts Feb 10, 2025
542e2c3
feat: Refactor Tic Tac Toe agent configuration and model selection
anuragts Feb 10, 2025
dae1598
- Start game when new game is clicked
anuragts Feb 10, 2025
97eea2f
fix imports
anuragts Feb 10, 2025
a9be589
feat: Add player model names display in Tic Tac Toe game header
anuragts Feb 10, 2025
7bd4b69
fix: Improve pause/resume button visibility and game state handling
anuragts Feb 10, 2025
9b1951b
feat: image upload and requirements
anuragts Feb 10, 2025
e8f0276
Merge branch 'main' into feat/tic_tac_toe
manthanguptaa Feb 11, 2025
26ecfeb
fix: dropdown selection
anuragts Feb 11, 2025
f580495
Merge branch 'main' into feat/tic_tac_toe
anuragts Feb 11, 2025
3efde2b
fix: better move history
anuragts Feb 11, 2025
36c6a6a
fix: moves history alignment
anuragts Feb 11, 2025
740fef4
fix: history update
anuragts Feb 11, 2025
612d66f
fix: model name and ui
anuragts Feb 11, 2025
19d7d7a
fix: moves history styling
anuragts Feb 11, 2025
b70a26b
feat: add deepseek
anuragts Feb 11, 2025
a23b499
fix: try again if errors
anuragts Feb 11, 2025
0ad7f1f
fix: remove deepseek
anuragts Feb 11, 2025
4aee58c
Merge branch 'main' into feat/tic_tac_toe
anuragts Feb 11, 2025
ce0d1fc
refactor: move play_tic_tac_toe function to utils module
anuragts Feb 11, 2025
7cf4a2b
fix: remove image upload
anuragts Feb 12, 2025
70107fb
Merge branch 'main' into feat/tic_tac_toe
anuragts Feb 12, 2025
7643003
Merge branch 'main' of https://github.com/agno-agi/agno into feat/tic…
dirkbrnd Feb 12, 2025
2650976
Add README
dirkbrnd Feb 12, 2025
9f3fa0e
update
dirkbrnd Feb 12, 2025
138fd8d
Merge branch 'main' into feat/tic_tac_toe
anuragts Feb 12, 2025
548220c
Merge branch 'main' into feat/tic_tac_toe
anuragts Feb 14, 2025
2f478dc
Merge branch 'main' into feat/tic_tac_toe
ashpreetbedi Feb 15, 2025
a05f2f1
tic tac toe
ashpreetbedi Feb 15, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file.
103 changes: 103 additions & 0 deletions cookbook/examples/apps/tic_tac_toe/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# Tic Tac Toe AI Battle

This example shows how to build an interactive Tic Tac Toe game where AI agents compete against each other. The application showcases how to:
- Coordinate multiple AI agents in a turn-based game
- Use different language models for different players
- Create an interactive web interface with Streamlit
- Handle game state and move validation
- Display real-time game progress and move history

## Features
- Multiple AI models support (GPT-4, Claude, Gemini, etc.)
- Real-time game visualization
- Move history tracking with board states
- Interactive player selection
- Game state management
- Move validation and coordination

### 1. Create a virtual environment

```shell
python3 -m venv .venv
source .venv/bin/activate
```

### 2. Install dependencies

```shell
pip install -r cookbook/examples/apps/tic_tac_toe/requirements.txt
```

### 3. Export API Keys

The game supports multiple AI models. Export the API keys for the models you want to use:

```shell
# Required for OpenAI models
export OPENAI_API_KEY=***

# Optional - for additional models
export ANTHROPIC_API_KEY=*** # For Claude models
export GOOGLE_API_KEY=*** # For Gemini models
export GROQ_API_KEY=*** # For Groq models
```

### 4. Run the Game

```shell
streamlit run cookbook/examples/apps/tic_tac_toe/app.py
```

- Open [localhost:8501](http://localhost:8501) to view the game interface

## How It Works

The game consists of three agents:

1. **Master Agent (Referee)**
- Coordinates the game
- Validates moves
- Maintains game state
- Determines game outcome

2. **Two Player Agents**
- Make strategic moves
- Analyze board state
- Follow game rules
- Respond to opponent moves

## Available Models

The game supports various AI models:
- GPT-4o (OpenAI)
- GPT-o3-mini (OpenAI)
- Gemini (Google)
- Llama 3 (Groq)
- Claude (Anthropic)

## Game Features

1. **Interactive Board**
- Real-time updates
- Visual move tracking
- Clear game status display

2. **Move History**
- Detailed move tracking
- Board state visualization
- Player action timeline

3. **Game Controls**
- Start/Pause game
- Reset board
- Select AI models
- View game history

4. **Performance Analysis**
- Move timing
- Strategy tracking
- Game statistics

## Support

Join our [Discord community](https://agno.link/discord) for help and discussions.
Empty file.
172 changes: 172 additions & 0 deletions cookbook/examples/apps/tic_tac_toe/agents.py
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't use the names Tic Agent and Tac Agent. Use instead Player 1 and Player 2

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Made the changes

Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
"""
Tic Tac Toe Battle
---------------------------------
This example shows how to build a Tic Tac Toe game where two AI agents play against each other.
The game features a referee agent coordinating between two player agents using different
language models.

Usage Examples:
---------------
1. Quick game with default settings:
referee_agent = get_tic_tac_toe_referee()
play_tic_tac_toe()

2. Game with debug mode off:
referee_agent = get_tic_tac_toe_referee(debug_mode=False)
play_tic_tac_toe(debug_mode=False)

The game integrates:
- Multiple AI models (Claude, GPT-4, etc.)
- Turn-based gameplay coordination
- Move validation and game state management
"""

import sys
from pathlib import Path
from textwrap import dedent

from agno.agent import Agent
from agno.models.anthropic import Claude
from agno.models.google import Gemini
from agno.models.groq import Groq
from agno.models.openai import OpenAIChat

project_root = str(Path(__file__).parent.parent.parent.parent)
if project_root not in sys.path:
sys.path.append(project_root)


def get_model_for_provider(provider: str, model_name: str):
"""
Creates and returns the appropriate model instance based on the provider.

Args:
provider: The model provider (e.g., 'openai', 'google', 'anthropic', 'groq')
model_name: The specific model name/ID

Returns:
An instance of the appropriate model class

Raises:
ValueError: If the provider is not supported
"""
if provider == "openai":
return OpenAIChat(id=model_name)
elif provider == "google":
return Gemini(id=model_name)
elif provider == "anthropic":
return Claude(id=model_name)
elif provider == "groq":
return Groq(id=model_name)
else:
raise ValueError(f"Unsupported model provider: {provider}")


def get_tic_tac_toe_referee(
model_x: str = "openai:gpt-4o",
model_o: str = "openai:o3-mini",
model_referee: str = "openai:gpt-4o",
debug_mode: bool = True,
) -> Agent:
"""
Returns an instance of the Tic Tac Toe Referee Agent that coordinates the game.

Args:
model_x: ModelConfig for player X
model_o: ModelConfig for player O
model_referee: ModelConfig for the referee agent
debug_mode: Enable logging and debug features

Returns:
An instance of the configured Referee Agent
"""
# Parse model provider and name
provider_x, model_name_x = model_x.split(":")
provider_o, model_name_o = model_o.split(":")
provider_referee, model_name_referee = model_referee.split(":")

# Create model instances using the helper function
model_x = get_model_for_provider(provider_x, model_name_x)
model_o = get_model_for_provider(provider_o, model_name_o)
model_referee = get_model_for_provider(provider_referee, model_name_referee)

player1 = Agent(
name="Player 1",
description=dedent("""\
You are the X player in Tic Tac Toe. Your goal is to win by placing three X's in a row (horizontally, vertically, or diagonally).

Game Rules:
- You must make valid moves on a 3x3 grid using row (0-2) and column (0-2) coordinates
- The top-left corner is (0,0), and bottom-right is (2,2)
- You can only place X's in empty spaces marked by " " on the board
- You will be given a list of valid moves - only choose from these moves
- Respond with ONLY the row and column numbers for your move, e.g. "1 2"

Strategy:
- Study the board carefully and make strategic moves
- Try to create winning opportunities while blocking your opponent
- Pay attention to the valid moves list to avoid illegal moves
"""),
model=model_x,
)

player2 = Agent(
name="Player 2",
description=dedent("""\
You are the O player in Tic Tac Toe. Your goal is to win by placing three O's in a row (horizontally, vertically, or diagonally).

Game Rules:
- You must make valid moves on a 3x3 grid using row (0-2) and column (0-2) coordinates
- The top-left corner is (0,0), and bottom-right is (2,2)
- You can only place O's in empty spaces marked by " " on the board
- You will be given a list of valid moves - only choose from these moves
- Respond with ONLY the row and column numbers for your move, e.g. "1 2"

Strategy:
- Study the board carefully and make strategic moves to win
- Block your opponent's winning opportunities
- Pay attention to the valid moves list to avoid illegal moves
"""),
model=model_o,
)

t3_agent = Agent(
name="Tic Tac Toe Referee Agent",
description=dedent("""\
You are the referee of a Tic Tac Toe game. Your responsibilities include:

Game Management:
1. Track and maintain the current board state
2. Validate all moves before they are made
3. Ensure moves are only made in empty spaces (marked by " ")
4. Keep track of whose turn it is (X goes first)

Move Validation:
1. Check that moves are within the 3x3 grid (0-2 for rows and columns)
2. Verify the chosen position is empty before allowing a move
3. Maintain and provide the list of valid moves to players

Game State Checking:
1. Check for winning conditions after each move:
- Three X's or O's in a row horizontally
- Three X's or O's in a row vertically
- Three X's or O's in a row diagonally
2. Check for draw conditions:
- Board is full with no winner

Communication:
1. Announce the current state of the board after each move
2. Declare moves as valid or invalid
3. Announce the winner or draw when game ends
4. Provide clear feedback to players about their moves

You will coordinate between the X and O players, ensuring fair play and proper game progression.
"""),
model=model_referee,
team=[player1, player2],
show_tool_calls=True,
markdown=True,
debug_mode=debug_mode,
)

return t3_agent
Loading