Skip to main content
A simple demo showing a smart agent playing Tic Tac Toe against a human. The AI opponent uses GPT-4o to make strategic moves with persistent game state.

What it demonstrates

  • Callable methods - makeMove and clearBoard as RPC endpoints
  • Persistent state - Game board survives restarts
  • AI integration - Uses OpenAI’s GPT-4o for strategic gameplay
  • State validation - Checks for valid moves and win conditions
  • React integration - Real-time UI updates with useAgent

Server Implementation

src/server.ts

How It Works

1

Player makes move

The client calls agent.stub.makeMove([row, col], "X") when clicking a cell.
2

Validate move

The agent validates the move (correct turn, cell empty) and updates the board state.
3

Check win condition

After each move, checkWinner() scans all possible winning lines (rows, columns, diagonals).
4

AI makes counter-move

If the game isn’t over, the agent calls GPT-4o with:
  • Current board state
  • Strategic priorities (win, block, center, fork, etc.)
  • Request for optimal move coordinates
5

State broadcasts

State changes automatically sync to all connected clients via WebSocket.

AI Strategy

The AI follows a strategic priority list:
  1. Win immediately if possible
  2. Block opponent’s winning move
  3. Take center if open (strongest position)
  4. Create a fork (two ways to win)
  5. Block opponent’s fork
  6. Take a corner (second-best positions)
  7. Take an edge (last resort)
The prompt guides GPT-4o through this decision tree:

Game State

The board is a 3x3 grid stored in agent state:
  • null = empty cell
  • "X" = human player
  • "O" = AI opponent

Win Detection

The checkWinner() method scans 8 possible winning lines:
Returns the winner ("X" or "O"), or null if the game continues.

Running the Example

1

Install dependencies

2

Configure OpenAI API key

Copy .env.example to .env:
Add your OpenAI API key:
3

Start the server

4

Play the game

Visit http://localhost:5174 and:
  1. Click any cell to make your move as X
  2. The AI (O) will respond immediately
  3. Continue until someone wins or it’s a draw
  4. Click “New Game” to reset
This example uses GPT-4o which requires an OpenAI API key. The AI makes strategic moves but isn’t unbeatable - try to beat it!

Client Integration

client.tsx

Extending This Example

Ideas for enhancements:
  • Difficulty levels - Adjust AI strategy based on difficulty
  • Move history - Store and replay game moves
  • Undo move - Let players take back their last move
  • Multiplayer - Two humans playing over the network
  • Tournament mode - Track wins/losses over multiple games
  • Different AI models - Compare strategies from different LLMs

Counter

Simplest agent with callable methods

AI Chat

Full-featured AI chat with streaming

Workflows

Multi-step workflows with state

Agent API

Full Agent class documentation