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 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
# API REFERENCE - Lightweight AI Backend

Quick reference for integrating the API endpoints into your frontend projects.

## πŸ”— Base URL

```
https://your-username-lightweight-ai-backend.hf.space
```

---

## πŸ“‘ Available Endpoints

All endpoints are accessible via HTTP POST requests to `/api/predict` with different parameters.

### 1. Generate Chat

**Purpose:** General conversational AI responses

**Endpoint:** `POST /api/predict`

**Request:**
```json
{
  "data": [
    "Your question or prompt here",
    150,
    0.7
  ]
}
```

**Parameters:**
| Index | Name | Type | Range | Default | Description |
|-------|------|------|-------|---------|-------------|
| 0 | prompt | string | N/A | N/A | The user's question or message |
| 1 | max_tokens | int | 50-200 | 150 | Maximum length of response |
| 2 | temperature | float | 0.1-1.0 | 0.7 | Randomness (0=deterministic, 1=creative) |

**Response:**
```json
{
  "data": [
    "Your question or prompt here response from the model..."
  ]
}
```

**Examples:**

**Python:**
```python
import requests

response = requests.post(
    "https://your-space-url/api/predict",
    json={"data": ["What is Python?", 150, 0.7]}
)
result = response.json()["data"][0]
print(result)
```

**JavaScript:**
```javascript
const response = await fetch('https://your-space-url/api/predict', {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({data: ["What is AI?", 150, 0.7]})
});
const result = await response.json();
console.log(result.data[0]);
```

**cURL:**
```bash
curl -X POST https://your-space-url/api/predict \
  -H "Content-Type: application/json" \
  -d '{"data": ["Hello!", 150, 0.7]}'
```

---

### 2. Generate Code

**Purpose:** Generate code based on descriptions

**Endpoint:** `POST /api/predict`

**Request:**
```json
{
  "data": [
    "Write a Python function to reverse a string",
    256,
    0.3
  ]
}
```

**Parameters:**
| Index | Name | Type | Range | Default | Description |
|-------|------|------|-------|---------|-------------|
| 0 | prompt | string | N/A | N/A | Description of the code to generate |
| 1 | max_tokens | int | 100-300 | 256 | Maximum code length |
| 2 | temperature | float | 0.1-1.0 | 0.3 | Lower = more deterministic code |

**Response:**
```json
{
  "data": [
    "def reverse_string(s):\n    return s[::-1]\n\n# Usage\nprint(reverse_string('hello'))..."
  ]
}
```

**Example:**

**Python:**
```python
response = requests.post(
    "https://your-space-url/api/predict",
    json={"data": ["Create a function that calculates factorial", 256, 0.3]}
)
code = response.json()["data"][0]
print(code)
```

---

### 3. Summarize Text

**Purpose:** Generate summaries of long text

**Endpoint:** `POST /api/predict`

**Request:**
```json
{
  "data": [
    "Long text to summarize goes here... at least 50 characters.",
    100
  ]
}
```

**Parameters:**
| Index | Name | Type | Range | Default | Description |
|-------|------|------|-------|---------|-------------|
| 0 | text | string | 50+ chars | N/A | Text to summarize |
| 1 | max_length | int | 20-150 | 100 | Maximum summary length |

**Response:**
```json
{
  "data": [
    "Summary of the provided text..."
  ]
}
```

**Example:**

**Python:**
```python
long_text = """
Machine learning is a subset of artificial intelligence (AI) that focuses 
on enabling systems to learn from and make decisions based on data...
"""

response = requests.post(
    "https://your-space-url/api/predict",
    json={"data": [long_text, 100]}
)
summary = response.json()["data"][0]
print(summary)
```

---

### 4. Generate Image

**Purpose:** Generate images from text descriptions

**Endpoint:** `POST /api/predict`

**Request:**
```json
{
  "data": [
    "A sunset over mountains",
    256,
    256
  ]
}
```

**Parameters:**
| Index | Name | Type | Range | Default | Description |
|-------|------|------|-------|---------|-------------|
| 0 | prompt | string | N/A | N/A | Image description |
| 1 | width | int | 128-256 | 256 | Image width in pixels |
| 2 | height | int | 128-256 | 256 | Image height in pixels |

**Response:**
Image returned as binary data (PNG format)

**Example:**

**Python:**
```python
from PIL import Image
from io import BytesIO

response = requests.post(
    "https://your-space-url/api/predict",
    json={"data": ["A red sunset", 256, 256]}
)

# Save image from response
with open('generated_image.png', 'wb') as f:
    f.write(response.content)

# Or load as PIL Image
img = Image.open(BytesIO(response.content))
img.show()
```

**JavaScript (for frontend):**
```javascript
const response = await fetch('https://your-space-url/api/predict', {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({data: ["A blue ocean", 256, 256]})
});

// Get image blob
const blob = await response.blob();
const url = URL.createObjectURL(blob);

// Display in image element
document.getElementById('image').src = url;
```

---

## πŸ”„ Response Codes

| Code | Meaning | Solution |
|------|---------|----------|
| 200 | Success | Response contains generated output |
| 400 | Bad Request | Check parameters (wrong JSON format) |
| 503 | Service Unavailable | Space is starting/restarting (wait 1-2 min) |
| 504 | Timeout | Request took too long (try shorter max_tokens) |

---

## ⏱️ Performance Tips

### Reduce Latency

1. **Use lower max_tokens:**
   ```python
   # Fast: 50-100 tokens
   max_tokens = 75  # ~2-3 seconds
   
   # Medium: 100-200 tokens
   max_tokens = 150  # ~4-6 seconds
   
   # Slow: 200-300 tokens
   max_tokens = 250  # ~8-12 seconds
   ```

2. **Warm up the model:**
   - First request loads the model (5-10 seconds)
   - Subsequent requests are faster
   - Consider sending a "warm-up" request on app startup

3. **Batch similar requests:**
   - Queue requests intelligently
   - Don't send all at once

### Error Handling

```python
import requests
import time

def call_api_with_retry(url, data, max_retries=3):
    """Call API with retry logic"""
    for attempt in range(max_retries):
        try:
            response = requests.post(
                url,
                json={"data": data},
                timeout=60
            )
            if response.status_code == 200:
                return response.json()["data"][0]
            elif response.status_code == 503:
                # Service restarting, wait and retry
                time.sleep(5)
                continue
            else:
                return f"Error: {response.status_code}"
        except requests.exceptions.Timeout:
            if attempt < max_retries - 1:
                print("Timeout, retrying...")
                time.sleep(2)
            else:
                return "Error: Request timeout"
    
    return "Error: Max retries exceeded"

# Usage
result = call_api_with_retry(
    "https://your-space-url/api/predict",
    ["Your prompt", 150, 0.7]
)
print(result)
```

---

## πŸ’‘ Integration Examples

### React Frontend

```jsx
import React, { useState } from 'react';

export default function ChatApp() {
  const [input, setInput] = useState('');
  const [response, setResponse] = useState('');
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);

    try {
      const result = await fetch(
        'https://your-space-url/api/predict',
        {
          method: 'POST',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify({data: [input, 150, 0.7]})
        }
      );
      
      const data = await result.json();
      setResponse(data.data[0]);
    } catch (error) {
      setResponse('Error: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Ask me anything..."
        />
        <button type="submit" disabled={loading}>
          {loading ? 'Generating...' : 'Send'}
        </button>
      </form>
      {response && <div>{response}</div>}
    </div>
  );
}
```

### Vue.js

```vue
<template>
  <div>
    <input v-model="prompt" placeholder="Ask a question..." />
    <button @click="generateResponse" :disabled="loading">
      {{ loading ? 'Generating...' : 'Send' }}
    </button>
    <p v-if="response">{{ response }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      prompt: '',
      response: '',
      loading: false
    };
  },
  methods: {
    async generateResponse() {
      this.loading = true;
      try {
        const res = await fetch(
          'https://your-space-url/api/predict',
          {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({data: [this.prompt, 150, 0.7]})
          }
        );
        const data = await res.json();
        this.response = data.data[0];
      } catch (error) {
        this.response = 'Error: ' + error.message;
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>
```

### Node.js Backend

```javascript
const express = require('express');
const axios = require('axios');

const app = express();
app.use(express.json());

app.post('/chat', async (req, res) => {
  const { prompt } = req.body;

  try {
    const response = await axios.post(
      'https://your-space-url/api/predict',
      {
        data: [prompt, 150, 0.7]
      }
    );

    res.json({ response: response.data.data[0] });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(3000, () => console.log('Server running on :3000'));
```

---

## πŸ” Important Notes

### Rate Limiting
- Free tier: ~2 requests per second
- Space sleeps after 48h inactivity (wakes on request)
- No hard quota, but be respectful

### Data Privacy
- All requests processed on Space server
- No data sent to external APIs
- Check Hugging Face privacy policy

### Bandwidth
- Requests are queued and processed sequentially
- Typical response: < 2MB
- No file uploads supported

---

## πŸ“ž Troubleshooting API Calls

### 503 Service Unavailable
```
Cause: Space restarting or models loading
Solution: Wait 30-60 seconds and retry
```

### 504 Gateway Timeout
```
Cause: Request took >60 seconds
Solution: Reduce max_tokens or try simpler prompt
```

### Empty Response
```
Cause: Model failed silently
Solution: Check Space logs, try different prompt
```

### Wrong Response Format
```
Cause: Endpoint called incorrectly
Solution: Ensure {"data": [arg1, arg2, ...]} structure
```

---

## 🎯 Production Checklist

- [ ] Replace `your-space-url` with actual URL
- [ ] Add error handling for API failures
- [ ] Implement request timeout (60s)
- [ ] Add retry logic (exponential backoff)
- [ ] Monitor API response times
- [ ] Cache responses if possible
- [ ] Set up alerting for 503/504 errors
- [ ] Test under expected load
- [ ] Document API usage in your project

---

**API Reference v1.0**
**Last Updated: 2024**