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| 6 |
+
|
| 7 |
+
Add to your `.env` file or environment secrets:
|
| 8 |
+
|
| 9 |
+
```bash
|
| 10 |
+
# Hugging Face Spaces URL (use hyphens, not underscores)
|
| 11 |
+
HF_SPACE_URL=https://jatinautonomouslabs-research-ai-assistant-api.hf.space
|
| 12 |
+
|
| 13 |
+
# Alternative if hyphens don't work
|
| 14 |
+
# HF_SPACE_URL=https://jatinautonomouslabs-research_ai_assistant_api.hf.space
|
| 15 |
+
```
|
| 16 |
+
|
| 17 |
+
### 2. Express Code Example
|
| 18 |
+
|
| 19 |
+
```javascript
|
| 20 |
+
const express = require('express');
|
| 21 |
+
const axios = require('axios');
|
| 22 |
+
const app = express();
|
| 23 |
+
|
| 24 |
+
app.use(express.json());
|
| 25 |
+
|
| 26 |
+
// Get HF Space URL from environment
|
| 27 |
+
const HF_SPACE_URL = process.env.HF_SPACE_URL ||
|
| 28 |
+
'https://jatinautonomouslabs-research-ai-assistant-api.hf.space';
|
| 29 |
+
|
| 30 |
+
// Health check function
|
| 31 |
+
async function checkHFHealth() {
|
| 32 |
+
try {
|
| 33 |
+
const response = await axios.get(`${HF_SPACE_URL}/api/health`, {
|
| 34 |
+
timeout: 5000
|
| 35 |
+
});
|
| 36 |
+
return {
|
| 37 |
+
healthy: true,
|
| 38 |
+
status: response.data.status,
|
| 39 |
+
orchestratorReady: response.data.orchestrator_ready
|
| 40 |
+
};
|
| 41 |
+
} catch (error) {
|
| 42 |
+
console.error('HF Space health check failed:', error.message);
|
| 43 |
+
return {
|
| 44 |
+
healthy: false,
|
| 45 |
+
error: error.message
|
| 46 |
+
};
|
| 47 |
+
}
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
// Initialize HF Space connection
|
| 51 |
+
async function initializeHFConnection() {
|
| 52 |
+
console.log('[Init] Using HuggingFace Spaces for AI backend...');
|
| 53 |
+
console.log('[Init] Checking Flask API connection...');
|
| 54 |
+
console.log(`[HFSpaces] Flask API: ${HF_SPACE_URL}`);
|
| 55 |
+
|
| 56 |
+
const health = await checkHFHealth();
|
| 57 |
+
|
| 58 |
+
if (health.healthy && health.orchestratorReady) {
|
| 59 |
+
console.log('[Init] ✅ Flask API healthy and ready');
|
| 60 |
+
return true;
|
| 61 |
+
} else {
|
| 62 |
+
console.log('[Init] ✗ Flask API unhealthy:', health.error || 'Orchestrator not ready');
|
| 63 |
+
console.log('[Init] Make sure your HF Space is running');
|
| 64 |
+
console.log(`[Init] URL: ${HF_SPACE_URL}`);
|
| 65 |
+
return false;
|
| 66 |
+
}
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
// Chat endpoint that proxies to HF Space
|
| 70 |
+
app.post('/api/chat', async (req, res) => {
|
| 71 |
+
try {
|
| 72 |
+
const { message, session_id, user_id, history } = req.body;
|
| 73 |
+
|
| 74 |
+
// Validate input
|
| 75 |
+
if (!message || typeof message !== 'string' || message.trim().length === 0) {
|
| 76 |
+
return res.status(400).json({
|
| 77 |
+
success: false,
|
| 78 |
+
error: 'Message is required and must be a non-empty string'
|
| 79 |
+
});
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
// Filter out CSS/HTML content (basic check)
|
| 83 |
+
if (message.includes('{') && message.includes('}') && message.includes('color:')) {
|
| 84 |
+
console.warn('[Chat] Detected potential CSS/HTML content, filtering...');
|
| 85 |
+
return res.status(400).json({
|
| 86 |
+
success: false,
|
| 87 |
+
error: 'Please send text messages only, not code or CSS'
|
| 88 |
+
});
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
// Call HF Space API
|
| 92 |
+
const response = await axios.post(
|
| 93 |
+
`${HF_SPACE_URL}/api/chat`,
|
| 94 |
+
{
|
| 95 |
+
message: message.trim(),
|
| 96 |
+
session_id: session_id,
|
| 97 |
+
user_id: user_id || 'anonymous',
|
| 98 |
+
history: history || []
|
| 99 |
+
},
|
| 100 |
+
{
|
| 101 |
+
timeout: 30000, // 30 second timeout
|
| 102 |
+
headers: {
|
| 103 |
+
'Content-Type': 'application/json'
|
| 104 |
+
}
|
| 105 |
+
}
|
| 106 |
+
);
|
| 107 |
+
|
| 108 |
+
res.json(response.data);
|
| 109 |
+
} catch (error) {
|
| 110 |
+
console.error('[Chat] Error:', error.message);
|
| 111 |
+
|
| 112 |
+
if (error.response) {
|
| 113 |
+
// HF Space returned an error
|
| 114 |
+
res.status(error.response.status).json({
|
| 115 |
+
success: false,
|
| 116 |
+
error: error.response.data.error || error.response.data.message || 'HF Space API error',
|
| 117 |
+
details: error.response.data
|
| 118 |
+
});
|
| 119 |
+
} else if (error.code === 'ECONNREFUSED' || error.code === 'ETIMEDOUT') {
|
| 120 |
+
// Connection error
|
| 121 |
+
res.status(503).json({
|
| 122 |
+
success: false,
|
| 123 |
+
error: 'HF Space is not reachable. Please check if the space is running.',
|
| 124 |
+
url: HF_SPACE_URL
|
| 125 |
+
});
|
| 126 |
+
} else {
|
| 127 |
+
// Other errors
|
| 128 |
+
res.status(500).json({
|
| 129 |
+
success: false,
|
| 130 |
+
error: 'Internal server error',
|
| 131 |
+
message: error.message
|
| 132 |
+
});
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
});
|
| 136 |
+
|
| 137 |
+
// Start server
|
| 138 |
+
const PORT = process.env.PORT || 5000;
|
| 139 |
+
|
| 140 |
+
async function startServer() {
|
| 141 |
+
// Check HF Space connection on startup
|
| 142 |
+
const hfReady = await initializeHFConnection();
|
| 143 |
+
|
| 144 |
+
if (!hfReady) {
|
| 145 |
+
console.warn('[Init] ⚠ HF Space not reachable');
|
| 146 |
+
console.warn('[Init] Check HF_SPACE_URL in Secrets');
|
| 147 |
+
console.warn('[Init] Make sure your HF Space is running');
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
app.listen(PORT, () => {
|
| 151 |
+
console.log(`[express] serving on port ${PORT}`);
|
| 152 |
+
});
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
startServer();
|
| 156 |
+
```
|
| 157 |
+
|
| 158 |
+
### 3. Testing the Connection
|
| 159 |
+
|
| 160 |
+
```javascript
|
| 161 |
+
// Test script
|
| 162 |
+
const axios = require('axios');
|
| 163 |
+
|
| 164 |
+
async function testConnection() {
|
| 165 |
+
const HF_SPACE_URL = process.env.HF_SPACE_URL ||
|
| 166 |
+
'https://jatinautonomouslabs-research-ai-assistant-api.hf.space';
|
| 167 |
+
|
| 168 |
+
console.log('Testing HF Space connection...');
|
| 169 |
+
console.log(`URL: ${HF_SPACE_URL}`);
|
| 170 |
+
|
| 171 |
+
// Test 1: Root endpoint
|
| 172 |
+
try {
|
| 173 |
+
const root = await axios.get(`${HF_SPACE_URL}/`, { timeout: 5000 });
|
| 174 |
+
console.log('✅ Root endpoint:', root.status, root.data);
|
| 175 |
+
} catch (e) {
|
| 176 |
+
console.log('❌ Root endpoint failed:', e.message);
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
// Test 2: Health endpoint
|
| 180 |
+
try {
|
| 181 |
+
const health = await axios.get(`${HF_SPACE_URL}/api/health`, { timeout: 5000 });
|
| 182 |
+
console.log('✅ Health endpoint:', health.status, health.data);
|
| 183 |
+
} catch (e) {
|
| 184 |
+
console.log('❌ Health endpoint failed:', e.message);
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
// Test 3: Chat endpoint
|
| 188 |
+
try {
|
| 189 |
+
const chat = await axios.post(
|
| 190 |
+
`${HF_SPACE_URL}/api/chat`,
|
| 191 |
+
{ message: 'Hello, test message' },
|
| 192 |
+
{ timeout: 10000 }
|
| 193 |
+
);
|
| 194 |
+
console.log('✅ Chat endpoint:', chat.status, chat.data.message);
|
| 195 |
+
} catch (e) {
|
| 196 |
+
console.log('❌ Chat endpoint failed:', e.message);
|
| 197 |
+
}
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
testConnection();
|
| 201 |
+
```
|
| 202 |
+
|
| 203 |
+
### 4. Common Issues and Solutions
|
| 204 |
+
|
| 205 |
+
#### Issue: 404 Not Found
|
| 206 |
+
|
| 207 |
+
**Causes:**
|
| 208 |
+
- Space is still building (wait 5-15 minutes)
|
| 209 |
+
- Wrong URL format (use hyphens, not underscores)
|
| 210 |
+
- Space is not public
|
| 211 |
+
|
| 212 |
+
**Solutions:**
|
| 213 |
+
1. Check Space status: https://huggingface.co/spaces/JatinAutonomousLabs/Research_AI_Assistant_API
|
| 214 |
+
2. Verify URL format: Use `-` (hyphens) not `_` (underscores)
|
| 215 |
+
3. Test both URL formats:
|
| 216 |
+
```bash
|
| 217 |
+
# With hyphens (recommended)
|
| 218 |
+
curl https://jatinautonomouslabs-research-ai-assistant-api.hf.space/
|
| 219 |
+
|
| 220 |
+
# With underscores (if hyphens don't work)
|
| 221 |
+
curl https://jatinautonomouslabs-research_ai_assistant_api.hf.space/
|
| 222 |
+
```
|
| 223 |
+
|
| 224 |
+
#### Issue: 503 Service Unavailable
|
| 225 |
+
|
| 226 |
+
**Cause:** Space is running but API is initializing
|
| 227 |
+
|
| 228 |
+
**Solution:** Wait 30-60 seconds and retry
|
| 229 |
+
|
| 230 |
+
#### Issue: CSS/HTML Content in Messages
|
| 231 |
+
|
| 232 |
+
**Solution:** Add input validation in your Express app:
|
| 233 |
+
|
| 234 |
+
```javascript
|
| 235 |
+
function isValidMessage(message) {
|
| 236 |
+
// Check for CSS patterns
|
| 237 |
+
if (message.includes('{') && message.includes('}') &&
|
| 238 |
+
(message.includes('color:') || message.includes('background:'))) {
|
| 239 |
+
return false;
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
// Check for HTML tags
|
| 243 |
+
if (/<[^>]+>/.test(message)) {
|
| 244 |
+
return false;
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
return true;
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
// Use in your endpoint
|
| 251 |
+
if (!isValidMessage(message)) {
|
| 252 |
+
return res.status(400).json({
|
| 253 |
+
success: false,
|
| 254 |
+
error: 'Please send text messages only, not code or markup'
|
| 255 |
+
});
|
| 256 |
+
}
|
| 257 |
+
```
|
| 258 |
+
|
| 259 |
+
### 5. Environment Variables Checklist
|
| 260 |
+
|
| 261 |
+
Make sure these are set in your Express app's environment:
|
| 262 |
+
|
| 263 |
+
```bash
|
| 264 |
+
# Required
|
| 265 |
+
HF_SPACE_URL=https://jatinautonomouslabs-research-ai-assistant-api.hf.space
|
| 266 |
+
|
| 267 |
+
# Optional
|
| 268 |
+
PORT=5000
|
| 269 |
+
NODE_ENV=production
|
| 270 |
+
```
|
| 271 |
+
|
| 272 |
+
### 6. Monitoring and Logging
|
| 273 |
+
|
| 274 |
+
Add logging to track HF Space connectivity:
|
| 275 |
+
|
| 276 |
+
```javascript
|
| 277 |
+
// Periodic health check
|
| 278 |
+
setInterval(async () => {
|
| 279 |
+
const health = await checkHFHealth();
|
| 280 |
+
if (!health.healthy) {
|
| 281 |
+
console.warn('[Monitor] HF Space is down:', health.error);
|
| 282 |
+
}
|
| 283 |
+
}, 60000); // Check every minute
|
| 284 |
+
```
|
| 285 |
+
|
| 286 |
+
---
|
| 287 |
+
|
| 288 |
+
## Quick Reference
|
| 289 |
+
|
| 290 |
+
**Correct URL Format:**
|
| 291 |
+
```
|
| 292 |
+
https://jatinautonomouslabs-research-ai-assistant-api.hf.space
|
| 293 |
+
```
|
| 294 |
+
|
| 295 |
+
**Endpoints:**
|
| 296 |
+
- `GET /` - API information
|
| 297 |
+
- `GET /api/health` - Health check
|
| 298 |
+
- `POST /api/chat` - Chat endpoint
|
| 299 |
+
|
| 300 |
+
**Test Command:**
|
| 301 |
+
```bash
|
| 302 |
+
curl https://jatinautonomouslabs-research-ai-assistant-api.hf.space/api/health
|
| 303 |
+
```
|
| 304 |
+
|