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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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
# πŸ“– Unified Embedding API Documentation

Complete API reference for the Unified Embedding API v3.0.0.

**Features:** Dense Embeddings, Sparse Embeddings, and Document Reranking

---

## 🌐 Base URL

```
https://fahmiaziz-api-embedding.hf.space
```

For local development:
```
http://localhost:7860
```

---

## πŸ”‘ Authentication

**Currently no authentication required.** 

---

## πŸ“Š Endpoints Overview

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/api/v1/embeddings/embed` | POST | Generate document embeddings |
| `/api/v1/embeddings/query` | POST | Generate query embeddings |
| `/api/v1/rerank` | POST | Rerank documents by relevance |
| `/api/v1/models` | GET | List available models |
| `/api/v1/models/{model_id}` | GET | Get model information |
| `/health` | GET | Health check |
| `/` | GET | API information |

---

## πŸš€ Embedding Endpoints

### 1. Generate Document Embeddings

**`POST /api/v1/embeddings/embed`**

Generate embeddings for document texts. Supports both single and batch processing.

#### Request Body

```json
{
  "texts": ["string"],           // Required: List of texts (1-100 items)
  "model_id": "string",          // Required: Model identifier
  "prompt": "string",            // Optional: Instruction prompt
  "options": {                   // Optional: Embedding parameters
    "normalize_embeddings": true,
    "batch_size": 32,
    "max_length": 512,
    "show_progress_bar": false
  }
}
```

#### Parameters

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `texts` | array[string] | βœ… Yes | List of texts to embed (min: 1, max: 100) |
| `model_id` | string | βœ… Yes | Model identifier (e.g., "qwen3-0.6b") |
| `prompt` | string | ❌ No | Instruction prompt for the model |
| `options` | object | ❌ No | Additional embedding parameters |

#### Options Parameters

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `normalize_embeddings` | boolean | false | L2 normalize output embeddings |
| `batch_size` | integer | 32 | Processing batch size (1-256) |
| `max_length` | integer | 512 | Maximum sequence length (1-8192) |
| `show_progress_bar` | boolean | false | Display progress during encoding |
| `precision` | string | float32 | Precision ("float32", "int8", "binary") |

#### Response - Single Text (Dense)

```json
{
  "embedding": [0.123, -0.456, 0.789, ...],
  "dimension": 768,
  "model_id": "qwen3-0.6b",
  "processing_time": 0.0523
}
```

#### Response - Batch (Dense)

```json
{
  "embeddings": [
    [0.123, -0.456, ...],
    [0.234, 0.567, ...],
    [0.345, -0.678, ...]
  ],
  "dimension": 768,
  "count": 3,
  "model_id": "qwen3-0.6b",
  "processing_time": 0.1245
}
```

#### Response - Single Text (Sparse)

```json
{
  "sparse_embedding": {
    "text": "Hello world",
    "indices": [10, 25, 42, 100],
    "values": [0.85, 0.62, 0.91, 0.73]
  },
  "model_id": "splade-pp-v2",
  "processing_time": 0.0421
}
```

#### Response - Batch (Sparse)

```json
{
  "embeddings": [
    {
      "text": "First doc",
      "indices": [10, 25, 42],
      "values": [0.85, 0.62, 0.91]
    },
    {
      "text": "Second doc",
      "indices": [15, 30, 50],
      "values": [0.73, 0.88, 0.65]
    }
  ],
  "count": 2,
  "model_id": "splade-pp-v2",
  "processing_time": 0.0892
}
```

#### Examples

**Single Text (Dense Model):**
```bash
curl -X 'POST' \
  'https://fahmiaziz-api-embedding.hf.space/api/v1/embeddings/embed' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "texts": ["What is artificial intelligence?"],
  "model_id": "qwen3-0.6b"
}'
```

**Single Text (Sparse Model):**
```bash
curl -X 'POST' \
  'https://fahmiaziz-api-embedding.hf.space/api/v1/embeddings/embed' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "texts": ["Hello world"],
  "model_id": "splade-pp-v2"
}'
```

**Batch (with Options):**
```bash
curl -X 'POST' \
  'https://fahmiaziz-api-embedding.hf.space/api/v1/embeddings/embed' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "texts": [
    "First document to embed",
    "Second document to embed",
    "Third document to embed"
  ],
  "model_id": "qwen3-0.6b",
  "options": {
    "normalize_embeddings": true,
    "batch_size": 32
  }
}'
```

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

url = "https://fahmiaziz-api-embedding.hf.space/api/v1/embeddings/embed"

payload = {
    "texts": ["Hello world"],
    "model_id": "qwen3-0.6b"
}

response = requests.post(url, json=payload)
data = response.json()

print(f"Embedding dimension: {data['dimension']}")
print(f"Processing time: {data['processing_time']:.3f}s")
```

---

### 2. Generate Query Embeddings

**`POST /api/v1/embeddings/query`**

Generate embeddings optimized for search queries. Some models differentiate between query and document embeddings.

#### Request Body

Same as `/embed` endpoint.

```json
{
  "texts": ["string"],
  "model_id": "string",
  "prompt": "string",
  "options": {}
}
```

#### Response

Same format as `/embed` endpoint.

#### Examples

**Single Query:**
```bash
curl -X 'POST' \
  'https://fahmiaziz-api-embedding.hf.space/api/v1/embeddings/query' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "texts": ["What is machine learning?"],
  "model_id": "qwen3-0.6b",
  "prompt": "Represent this query for retrieval",
  "options": {
    "normalize_embeddings": true
  }
}'
```

**Batch Queries:**
```bash
curl -X 'POST' \
  'https://fahmiaziz-api-embedding.hf.space/api/v1/embeddings/query' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "texts": [
    "First query",
    "Second query",
    "Third query"
  ],
  "model_id": "qwen3-0.6b"
}'
```

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

url = "https://fahmiaziz-api-embedding.hf.space/api/v1/embeddings/query"

payload = {
    "texts": ["What is AI?"],
    "model_id": "qwen3-0.6b",
    "options": {
        "normalize_embeddings": True
    }
}

response = requests.post(url, json=payload)
embedding = response.json()["embedding"]
```

---

### 3. Rerank Documents

**`POST /api/v1/rerank`**

Rerank documents based on their relevance to a query using CrossEncoder models.

#### Request Body

```json
{
  "query": "string",             // Required: Search query
  "documents": ["string"],       // Required: List of documents (min: 1)
  "model_id": "string",          // Required: Reranking model identifier
  "top_k": integer,              // Required: Number of top results to return
}
```

#### Parameters

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `query` | string | βœ… Yes | Search query text |
| `documents` | array[string] | βœ… Yes | List of documents to rerank (min: 1) |
| `model_id` | string | βœ… Yes | Reranking model identifier |
| `top_k` | integer | βœ… Yes | Maximum number of results to return |

#### Response

```json
{
  "model_id": "jina-reranker-v3",
  "processing_time": 0.56,
  "query": "Python for data science",
  "results": [
    {
      "index": 0,
      "score": 0.95,
      "text": "Python is excellent for data science"
    },
    {
      "index": 2,
      "score": 0.73,
      "text": "R is also used in data science"
    }
  ]
}
```

#### Response Fields

| Field | Type | Description |
|-------|------|-------------|
| `model_id` | string | Model identifier used |
| `processing_time` | float | Processing time in seconds |
| `query` | string | Original search query |
| `results` | array | Reranked documents with scores |
| `results[].index` | integer | Original index in input documents |
| `results[].score` | float | Relevance score (0-1, normalized) |
| `results[].text` | string | Document text |

#### Examples

**Basic Reranking:**
```bash
curl -X 'POST' \
  'https://fahmiaziz-api-embedding.hf.space/api/v1/rerank' \
  -H 'Content-Type: application/json' \
  -d '{
  "query": "Python for data science",
  "documents": [
    "Python is great for data science",
    "Java is used for enterprise applications",
    "R is also used in data science",
    "JavaScript is for web development"
  ],
  "model_id": "jina-reranker-v3",
  "top_k": 2
}'
```


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

url = "https://fahmiaziz-api-embedding.hf.space/api/v1/rerank"

payload = {
    "query": "best programming language for beginners",
    "documents": [
        "Python is beginner-friendly with simple syntax",
        "C++ is powerful but complex for beginners",
        "JavaScript is essential for web development",
        "Rust offers memory safety but steep learning curve"
    ],
    "model_id": "jina-reranker-v3",
    "top_k": 2
}

response = requests.post(url, json=payload)
data = response.json()

print(f"Top result: {data['results'][0]['text']}")
print(f"Score: {data['results'][0]['score']:.3f}")
```

**JavaScript Example:**
```javascript
const url = "https://fahmiaziz-api-embedding.hf.space/api/v1/rerank";

const response = await fetch(url, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    query: "AI applications",
    documents: [
      "Computer vision for image recognition",
      "Recipe for chocolate cake",
      "Natural language processing for chatbots",
      "Travel guide to Paris"
    ],
    model_id: "jina-reranker-v3",
    top_k: 2
  })
});

const { results } = await response.json();
console.log("Top results:", results);
```

---

## πŸ€– Model Management

### 3. List Available Models

**`GET /api/v1/models`**

Get a list of all available embedding models.

#### Response

```json
{
  "models": [
    {
      "id": "qwen3-0.6b",
      "name": "Qwen/Qwen3-Embedding-0.6B",
      "type": "embeddings",
      "loaded": true,
      "repository": "https://huggingface.co/Qwen/Qwen3-Embedding-0.6B"
    },
    {
      "id": "splade-pp-v2",
      "name": "prithivida/Splade_PP_en_v2",
      "type": "sparse-embeddings",
      "loaded": true,
      "repository": "https://huggingface.co/prithivida/Splade_PP_en_v2"
    }
  ],
  "total": 2
}
```

#### Example

```bash
curl -X 'GET' \
  'https://fahmiaziz-api-embedding.hf.space/api/v1/models' \
  -H 'accept: application/json'
```

---

### 4. Get Model Information

**`GET /api/v1/models/{model_id}`**

Get detailed information about a specific model.

#### Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `model_id` | string | βœ… Yes | Model identifier |

#### Response

```json
{
  "id": "qwen3-0.6b",
  "name": "Qwen/Qwen3-Embedding-0.6B",
  "type": "embeddings",
  "loaded": true,
  "repository": "https://huggingface.co/Qwen/Qwen3-Embedding-0.6B"
}
```

#### Example

```bash
curl -X 'GET' \
  'https://fahmiaziz-api-embedding.hf.space/api/v1/models/qwen3-0.6b' \
  -H 'accept: application/json'
```

---

## πŸ₯ System Endpoints

### 5. Health Check

**`GET /health`**

Check API health status.

#### Response

```json
{
  "status": "ok",
  "total_models": 2,
  "loaded_models": 2,
  "startup_complete": true
}
```

#### Example

```bash
curl -X 'GET' \
  'https://fahmiaziz-api-embedding.hf.space/health' \
  -H 'accept: application/json'
```

---

### 6. API Information

**`GET /`**

Get basic API information.

#### Response

```json
{
  "message": "Unified Embedding API - Dense & Sparse Embeddings",
  "version": "3.0.0",
  "docs_url": "/docs"
}
```

---

## ❌ Error Responses

All errors follow this format:

```json
{
  "detail": "Error message description"
}
```

### HTTP Status Codes

| Code | Description |
|------|-------------|
| 200 | Success |
| 400 | Bad Request - Invalid input |
| 404 | Not Found - Model not found |
| 422 | Unprocessable Entity - Validation error |
| 500 | Internal Server Error |
| 503 | Service Unavailable - Server not ready |

### Common Errors

**Model Not Found (404):**
```json
{
  "detail": "Model 'unknown-model' not found in configuration"
}
```

**Validation Error (422):**
```json
{
  "detail": [
    {
      "loc": ["body", "texts"],
      "msg": "texts list cannot be empty",
      "type": "value_error"
    }
  ]
}
```

**Batch Too Large (422):**
```json
{
  "detail": "Batch size (150) exceeds maximum (100)"
}
```

---

## πŸ“¦ Available Models

### Dense Embedding Models

| Model ID | Name | Dimension | Description |
|----------|------|-----------|-------------|
| `qwen3-0.6b` | Qwen/Qwen3-Embedding-0.6B | 768 | Efficient multilingual embeddings |

### Sparse Embedding Models

| Model ID | Name | Type | Description |
|----------|------|------|-------------|
| `splade-pp-v2` | prithivida/Splade_PP_en_v2 | Sparse | SPLADE++ English v2 |

### Reranking Models

| Model ID | Name | Type | Description |
|----------|------|------|-------------|
| `jina-reranker-v3` | jinaai/jina-reranker-v3-base-en | CrossEncoder | High-quality reranking (English) |
| `bge-v2-m3` | BAAI/bge-reranker-v2-m3 | CrossEncoder | Multilingual reranking |

---

## πŸ”§ Rate Limits

**Current Limits:**
- Max text length: 8,192 characters
- Max batch size: 100 texts per request
- No rate limiting (subject to server resources)

---

## πŸ’‘ Best Practices

### 1. Batch Processing
Always batch multiple texts together for better performance:
```python
# ❌ Bad - Multiple requests
for text in texts:
    response = requests.post(url, json={"texts": [text], ...})

# βœ… Good - Single batch request
response = requests.post(url, json={"texts": texts, ...})
```

### 2. Normalize Embeddings for Similarity
For cosine similarity, always normalize:
```python
payload = {
    "texts": ["text"],
    "model_id": "qwen3-0.6b",
    "options": {"normalize_embeddings": True}
}
```

### 3. Model Selection
- **Dense models** (qwen3-0.6b): Best for semantic similarity
- **Sparse models** (splade-pp-v2): Best for keyword matching + semantic
- **Rerank models** (jina-reranker-v3): Best for re-scoring top candidates

### 4. Two-Stage Retrieval (Recommended for RAG)
```python
# Stage 1: Fast retrieval with embeddings (top 100)
query_embedding = embed_query(query)
candidates = vector_search(query_embedding, top_k=100)

# Stage 2: Precise reranking (top 10)
reranked = rerank(
    query=query,
    documents=[c["text"] for c in candidates],
    model_id="jina-reranker-v3",
    top_k=10
)
```

### 5. Error Handling
Always handle errors gracefully:
```python
try:
    response = requests.post(url, json=payload)
    response.raise_for_status()
    data = response.json()
except requests.exceptions.HTTPError as e:
    print(f"HTTP error: {e}")
except requests.exceptions.RequestException as e:
    print(f"Request failed: {e}")
```

---

## πŸ› Troubleshooting

### Empty Response
- Check `texts` field is not empty
- Validate `model_id` exists

### Slow Performance
- Use batch requests instead of multiple single requests
- Reduce `batch_size` in options if memory issues
- Check model is preloaded (first request is slower)

### Connection Errors
- Verify base URL is correct
- Check network connectivity
- Ensure server is running (`/health` endpoint)

---

## πŸ“ž Support

- **Documentation**: [GitHub README](https://github.com/fahmiaziz/unified-embedding-api)
- **Issues**: [GitHub Issues](https://github.com/fahmiaziz/unified-embedding-api/issues)
- **Hugging Face Space**: [fahmiaziz/api-embedding](https://huggingface.co/spaces/fahmiaziz/api-embedding)

---

## πŸ”„ Changelog

### v3.0.0 (Current)
- ✨ Added reranking endpoint (`/api/v1/rerank`)
- ✨ Support for CrossEncoder models
- ✨ Unified batch-only response format
- ✨ Flexible kwargs support
- ✨ In-memory caching
- ✨ Improved error handling
- ✨ Comprehensive documentation
- πŸ› Fixed type hint errors in RerankModel
- πŸ› Fixed duplicate parameter errors in rerank endpoint

---

**Last Updated**: 2025-11-02