> ## Documentation Index
> Fetch the complete documentation index at: https://docs.chesshacks.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Development

> Local development guide for ChessHacks bots

This guide covers everything you need to know about developing your ChessHacks bot locally.

## Getting Started

<Note>
  New to ChessHacks? Start with the [Platform Overview](/platform/overview) to
  understand the architecture first.
</Note>

After creating your project with `npx chesshacks create`, set up your environment:

### Environment Setup

1. **Set up Python environment:**

```bash theme={null}
python -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate
pip install -r requirements.txt
```

2. **Install Node.js dependencies:**

```bash theme={null}
cd devtools
npm install
```

3. **Configure environment variables:**

Copy `.env.template` to `.env.local` in both the root directory and the `devtools` directory. Fill in:

* Path to your Python environment
* Ports for the backend and frontend (defaults are usually fine)

## Running the Development Server

From the `devtools` directory, run:

```bash theme={null}
npm run dev
```

This single command:

* Starts the Next.js frontend
* Launches the Python backend as a subprocess
* Enables hot reloading for your bot code

<Warning>
  **Important:** Do NOT run the Python files (`serve.py` or `main.py`) directly!
  The Next.js app manages these as subprocesses.
</Warning>

## Development Workflow

### 1. Edit Your Bot

Your bot logic lives in `/src/main.py`. This is where you'll implement your chess engine.

```python theme={null}
# Example structure in main.py
from .utils import chess_manager, GameContext

def get_move(pgn: str) -> str:
    # Your bot logic here
    # Receives board state as PGN
    # Returns move in UCI format
    pass
```

### 2. Test in Browser

Open your browser to `http://localhost:3000` (or your configured port). You'll see:

* An interactive chess board
* Analysis tools
* The ability to play against your bot
* Real-time move feedback

### 3. Hot Reloading

When you save changes to files in `/src`:

* The devtools automatically detect the change
* The Python subprocess restarts
* Your new bot logic is immediately available
* No manual restart needed!

You can also manually reload using the button in the devtools UI.

### 4. View Logs

All logs from both Python files (`serve.py` and `main.py`) appear in your Next.js terminal:

* `stdout` and `stderr` from both processes
* Verbose by default for easier debugging
* Real-time updates on bot moves and decisions

## Where to Code

Focus your development on `/src/main.py` - this is your bot's brain. The other files (`serve.py`, devtools) handle infrastructure and generally don't need editing.

## Model Training

<Note>
  **Important:** You should **not** train your model within this repository.
  Manage training separately and import only the trained weights.
</Note>

### Training Architecture

For bots that use machine learning models, we recommend separating your training pipeline from your competition bot repository:

**Why separate training from deployment?**

* Training requires large datasets, experiment tracking, and computational resources
* Your competition repo should be lightweight and focused on inference
* Version control for training code and model weights have different needs
* Training environments often have different dependencies than inference

### Recommended Workflow

1. **Create a separate training repository or folder**

   * Keep your training scripts, data processing, and experiments separate
   * This can be a completely different repository or a dedicated folder in your project
   * Add training directories to `.gitignore` if keeping them local

2. **Store model weights externally**

   * **Hugging Face Hub** (recommended for most models)
     * Free hosting for model weights
     * Version control for models
     * Easy integration with `transformers` library
   * **GitHub Releases** (for small models only)
     * Suitable for models \< 100MB
     * Use Git LFS for files between 100MB-2GB
   * **Other options:** Weights & Biases, Google Drive, AWS S3

3. **Fetch weights in your bot**
   * Download weights during initialization or deployment
   * Cache them locally to avoid repeated downloads
   * Keep your main repository clean and fast to clone

### Example: Using Hugging Face

**In your training repository:**

```python theme={null}
# After training your model
from transformers import AutoModel

model.save_pretrained("./my-chess-model")
# Push to Hugging Face Hub
model.push_to_hub("your-username/chess-bot-model")
```

**In your competition bot (`src/main.py`):**

```python theme={null}
from transformers import AutoModel
import os

# Load model from Hugging Face
model = AutoModel.from_pretrained(
    "your-username/chess-bot-model",
    cache_dir="./.model_cache"  # Cache locally
)

def get_move(pgn: str) -> str:
    # Use your model for inference
    # ...
    pass
```

### Example: Small Models on GitHub

For very small models (\< 100MB), you can include them directly:

```python theme={null}
# In your bot
import torch
import os

# Load local weights
model_path = os.path.join(os.path.dirname(__file__), "weights", "model.pt")
model.load_state_dict(torch.load(model_path))
```

**Project structure:**

```
your-bot/
├── src/
│   ├── main.py
│   └── weights/
│       └── model.pt  # Small model file
├── serve.py
└── requirements.txt
```

### Best Practices

1. **Document your model source** - Include a README explaining where weights come from
2. **Pin versions** - Use specific model versions/commits to ensure reproducibility
3. **Handle downloads gracefully** - Add error handling for network issues
4. **Consider cold start time** - Large model downloads may slow initial deployment
5. **Test locally first** - Ensure weight loading works before deploying

<Warning>
  **Do not commit large files to git!** Models over 100MB will make your
  repository slow to clone and may violate GitHub's file size limits.
</Warning>

## Troubleshooting

### Import Errors

If you see:

```python theme={null}
ImportError: attempted relative import with no known parent package
```

**Do NOT remove the relative import dots!** This error means you're running `main.py` directly. Instead, run the Next.js app which will manage the Python files correctly.

### Port Conflicts

If the default ports (3000 for frontend, 5058 for backend) are in use:

1. Edit your `.env.local` file
2. Change the port numbers
3. Restart the dev server

### Python Environment Issues

Make sure:

* Your virtual environment is activated
* All dependencies are installed (`pip install -r requirements.txt`)
* The path in `.env.local` points to the correct Python executable

### Subprocess Not Starting

Check that:

* You're running `npm run dev` from the `devtools` directory
* Your `.env.local` file exists and is configured correctly
* The Python path in `.env.local` is correct

## Best Practices

1. **Keep imports relative** in `/src/main.py` - they're designed to work with the subprocess architecture
2. **Use the devtools** - don't run Python files manually
3. **Check logs frequently** - they're verbose for a reason
4. **Test edge cases** - use the analysis board to test specific positions
5. **Iterate quickly** - take advantage of hot reloading

## Next Steps

* [Deploy your bot](/platform/deployment) when you're ready
* [Learn about the game format](/platform/games)
* [Get support](/platform/support) if you need help
