File size: 5,816 Bytes
bdad329
 
 
 
 
 
 
4c03150
bdad329
 
 
fdfd029
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
---
title: API Bridge
emoji: 😻
colorFrom: red
colorTo: purple
sdk: docker
pinned: false
license: gpl-3.0
short_description: The Bridge of The API's
---

# GambitFlow Bridge API

Unified API gateway for all GambitFlow chess engines with Firebase analytics and caching.

## Features

- **Unified Endpoint**: Single API for all models (Nano, Core, Base)
- **Firebase Analytics**: Real-time tracking of moves and matches
- **Intelligent Caching**: 5-minute cache for repeated positions
- **Batch Predictions**: Process multiple positions in one request
- **Model Health Checks**: Monitor all engine statuses
- **No Rate Limiting**: Unrestricted access for all users

## Quick Start

### Basic Request

```bash
curl -X POST https://YOUR-SPACE.hf.space/predict \
  -H "Content-Type: application/json" \
  -d '{
    "fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
    "model": "core",
    "depth": 5,
    "time_limit": 3000
  }'
```

### Response

```json
{
  "best_move": "e2e4",
  "evaluation": 0.25,
  "depth_searched": 5,
  "nodes_evaluated": 125000,
  "time_taken": 1500,
  "pv": ["e2e4", "e7e5", "Ng1f3"],
  "from_cache": false,
  "model": "core"
}
```

## Endpoints

### POST /predict
Get best move for a position

**Request Body:**
```json
{
  "fen": "string",        // Required: FEN notation
  "model": "core",        // Optional: nano|core|base (default: core)
  "depth": 5,             // Optional: 1-10 (default: 5)
  "time_limit": 3000,     // Optional: ms (default: 3000)
  "track_stats": true     // Optional: track in analytics (default: true)
}
```

### POST /batch
Batch predictions (max 10 positions)

**Request Body:**
```json
{
  "model": "core",
  "positions": [
    {
      "fen": "...",
      "depth": 5,
      "time_limit": 3000
    },
    // ... more positions
  ]
}
```

### POST /match/start
Track match start (increments match counter)

**Request Body:**
```json
{
  "model": "core"
}
```

### GET /stats
Get usage statistics

**Response:**
```json
{
  "total": {
    "moves": 15420,
    "matches": 532
  },
  "models": {
    "nano": {"moves": 4200, "matches": 150},
    "core": {"moves": 8500, "matches": 280},
    "base": {"moves": 2720, "matches": 102}
  },
  "last_updated": 1704724800
}
```

### GET /models
List all available models

### GET /health
Health check

## Configuration

### Environment Variables

Set these in your HuggingFace Space settings:

```bash
# Model Endpoints
NANO_ENDPOINT=https://gambitflow-nexus-nano-inference-api.hf.space
CORE_ENDPOINT=https://gambitflow-nexus-core-inference-api.hf.space
BASE_ENDPOINT=https://gambitflow-synapse-base-inference-api.hf.space

```

### Adding New Models

To add a new model:

1. **Deploy the model inference API** to HuggingFace Spaces

2. **Update `app.py`** - Add model configuration:

```python
MODELS = {
    'nano': {...},
    'core': {...},
    'base': {...},
    'new_model': {  # Add here
        'name': 'New-Model',
        'endpoint': 'https://your-new-model-api.hf.space',
        'timeout': 40
    }
}
```

3. **Set environment variable** (optional, if URL is dynamic):

```bash
NEW_MODEL_ENDPOINT=https://your-new-model-api.hf.space
```

Then update the endpoint loading:
```python
'new_model': {
    'name': 'New-Model',
    'endpoint': os.getenv('NEW_MODEL_ENDPOINT', 'https://fallback-url.hf.space'),
    'timeout': 40
}
```

4. **Update Firebase structure** - Initialize stats for new model in Firebase:

```json
{
  "stats": {
    "models": {
      "new_model": {
        "moves": 0,
        "matches": 0
      }
    }
  }
}
```

5. **Restart the Space** - Changes will take effect immediately

## Firebase Setup

### 1. Create Firebase Project
- Go to [Firebase Console](https://console.firebase.google.com/)
- Create new project
- Enable Realtime Database

### 2. Get Service Account
- Go to Project Settings → Service Accounts
- Generate new private key
- Copy JSON content

### 3. Configure Space
Add to HuggingFace Space secrets:

**FIREBASE_DATABASE_URL:**
```
https://YOUR-PROJECT.firebaseio.com
```

**FIREBASE_CREDENTIALS:**
```json
{
  "type": "service_account",
  "project_id": "your-project-id",
  "private_key_id": "...",
  "private_key": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n",
  "client_email": "firebase-adminsdk-xxxxx@your-project.iam.gserviceaccount.com",
  "client_id": "...",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "..."
}
```

### 4. Database Rules
Set Realtime Database rules:

```json
{
  "rules": {
    "stats": {
      ".read": true,
      ".write": false
    }
  }
}
```

## Integration Examples

### Python

```python
import requests

API_URL = "https://YOUR-SPACE.hf.space"

# Single prediction
response = requests.post(f"{API_URL}/predict", json={
    "fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
    "model": "core",
    "depth": 5
})
result = response.json()
print(f"Best move: {result['best_move']}")

# Get statistics
stats = requests.get(f"{API_URL}/stats").json()
print(f"Total moves: {stats['total']['moves']}")
```

### JavaScript

```javascript
const API_URL = "https://YOUR-SPACE.hf.space";

async function getBestMove(fen, model = 'core') {
  const response = await fetch(`${API_URL}/predict`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      fen: fen,
      model: model,
      depth: 5
    })
  });
  return await response.json();
}

// Usage
const result = await getBestMove('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1');
console.log(`Best move: ${result.best_move}`);
```

---

**GambitFlow Bridge API** - Unified gateway for chess AI engines