QCTW Umer5881 commited on
Commit
562b07b
·
1 Parent(s): 6dac3de

Upload README.md (#2)

Browse files

- Upload README.md (6577c8e0b4bdb817f01e55ef53f03747d49ed720)


Co-authored-by: Muhammad UMER <Umer5881@users.noreply.huggingface.co>

Files changed (1) hide show
  1. README.md +534 -733
README.md CHANGED
@@ -1,733 +1,534 @@
1
- ---
2
- title: Example App Hackathon Gustave Eiffel 2026
3
- emoji: 🤖
4
- colorFrom: blue
5
- colorTo: purple
6
- sdk: gradio
7
- sdk_version: 4.44.1
8
- python_version: '3.11'
9
- app_file: app.py
10
- pinned: false
11
- license: apache-2.0
12
- ---
13
-
14
- # 🗼 RAG Chat API — Gustave Eiffel Hackathon 2026
15
-
16
- A complete **Retrieval-Augmented Generation (RAG)** system deployed as a Hugging Face Space, with a `/query` API endpoint designed for the RAG evaluation system.
17
-
18
- ---
19
-
20
- ## Table of Contents
21
-
22
- 1. [Overview](#overview)
23
- 2. [Architecture](#architecture)
24
- 3. [Step-by-Step Explanation](#step-by-step-explanation)
25
- 4. [API Endpoints](#api-endpoints)
26
- 5. [Setup & Deployment](#setup--deployment)
27
- 6. [Adding Binary Files to the HF Space](#adding-binary-files-to-the-hf-space)
28
- 7. [Configuration](#configuration)
29
- 8. [How It Works (Detailed)](#how-it-works-detailed)
30
-
31
- ---
32
-
33
- ## Overview
34
-
35
- This application demonstrates how to build a production-ready RAG system within the Hugging Face ecosystem. It covers:
36
-
37
- | Requirement | Solution |
38
- |---|---|
39
- | LLM API calls | Azure OpenAI (`gpt-5` via REST) |
40
- | Text Embeddings | Azure OpenAI (`text-embedding-3-small` via REST) |
41
- | Vector Store | ChromaDB (persistent, runs in-process) |
42
- | API Endpoint | FastAPI with `POST /query` |
43
- | UI | Gradio Blocks (chat + document ingestion) |
44
-
45
- ---
46
-
47
- ## Architecture
48
-
49
- ```
50
- ┌─────────────────────────────────────────────────────────────┐
51
- Hugging Face Space
52
-
53
- ┌──────────┐ ──────────────┐ ┌───────────────┐
54
- │ │ Gradio │ │ FastAPI │ │ ChromaDB │ │
55
- │ UI ────▶│ /query │────▶│ Vector Store │
56
- │ /ingest │ │ (persistent) │ │
57
- └──────────┘ └──────┬───────┘ └───────────────┘
58
- ▲ │
59
-
60
- ┌──────────────────┐ ┌─────────────────┐
61
- │ │ Azure OpenAI │ │ Azure OpenAI │ │
62
- │ GPT-5 (LLM) │ │ text-embedding │
63
- │ │ │ │ -3-small │ │
64
- │ └──────────────────┘ └─────────────────┘ │
65
- └─────────────────────────────────────────────────────────────┘
66
- ```
67
-
68
- ---
69
-
70
- ## Step-by-Step Explanation
71
-
72
- ### Step 1: Document Ingestion & Chunking
73
-
74
- Before we can answer questions, we need to prepare our knowledge base.
75
-
76
- 1. **Load documents** — Read text files from `sample_documents/` directory
77
- 2. **Chunk text** — Split documents into smaller overlapping chunks (512 tokens, 50 token overlap) using `RecursiveCharacterTextSplitter`. This ensures each chunk fits within the embedding model's context window while maintaining semantic coherence.
78
-
79
- ```python
80
- splitter = RecursiveCharacterTextSplitter(
81
- chunk_size=512,
82
- chunk_overlap=50,
83
- separators=["\n\n", "\n", ". ", " ", ""],
84
- )
85
- chunks = splitter.split_text(document_text)
86
- ```
87
-
88
- ### Step 2: Generate Embeddings
89
-
90
- Convert text chunks into dense vector representations that capture semantic meaning.
91
-
92
- 1. **Call Azure OpenAI** — We use the `text-embedding-3-small` model via the Azure OpenAI embeddings endpoint
93
- 2. **Encode text** — Each chunk is transformed into a fixed-size vector where semantically similar texts are closer together in vector space
94
-
95
- ```python
96
- import requests as http_requests
97
-
98
- headers = {"api-key": AZURE_API_KEY, "Content-Type": "application/json"}
99
- payload = {"input": ["chunk 1 text", "chunk 2 text"], "model": "text-embedding-3-small"}
100
- resp = http_requests.post(EMBEDDING_ENDPOINT_URL, headers=headers, json=payload)
101
- embeddings = [item["embedding"] for item in resp.json()["data"]]
102
- ```
103
-
104
- ### Step 3: Store in Vector Database (ChromaDB)
105
-
106
- Persist embeddings in a vector store optimized for similarity search.
107
-
108
- 1. **Initialize ChromaDB** Create a persistent client that stores data on disk (survives Space restarts)
109
- 2. **Create collection** — A named collection with cosine similarity metric
110
- 3. **Add documents** — Store embeddings alongside the original text and metadata
111
-
112
- ```python
113
- import chromadb
114
-
115
- client = chromadb.PersistentClient(path="./data/chroma_db")
116
- collection = client.get_or_create_collection(
117
- name="rag_documents",
118
- metadata={"hnsw:space": "cosine"},
119
- )
120
- collection.add(
121
- ids=["doc_0", "doc_1"],
122
- embeddings=embeddings.tolist(),
123
- documents=["chunk 1 text", "chunk 2 text"],
124
- metadatas=[{"source": "file.txt"}, {"source": "file.txt"}],
125
- )
126
- ```
127
-
128
- ### Step 4: Query & Retrieval
129
-
130
- When a user asks a question, find the most relevant context.
131
-
132
- 1. **Embed the query** — Use the same Azure OpenAI embedding model to convert the question to a vector
133
- 2. **Similarity search** — Find the top-K nearest vectors in ChromaDB (cosine similarity)
134
- 3. **Return context** Extract the original text chunks for the closest matches
135
-
136
- ```python
137
- query_embedding = generate_embeddings(["What is the Eiffel Tower?"])[0]
138
- results = collection.query(
139
- query_embeddings=[query_embedding],
140
- n_results=3,
141
- )
142
- ```
143
-
144
- ### Step 5: LLM Generation (Augmented Response)
145
-
146
- Combine retrieved context with the user's question and generate an answer.
147
-
148
- 1. **Build prompt** Load the template from [`prompts/rag_prompt.txt`](prompts/rag_prompt.txt), inject retrieved context and the user's question
149
- 2. **Call Azure OpenAI** — Send the prompt to the Azure OpenAI chat/completions endpoint (`gpt-5`)
150
- 3. **Return response** — The LLM generates an answer grounded in the provided context
151
-
152
- The prompt template (`prompts/rag_prompt.txt`):
153
-
154
- ```
155
- You are a helpful assistant. Answer the user's question based ONLY on the provided context.
156
- If the context does not contain enough information to answer, say "I don't have enough information to answer this question."
157
- Always be concise and factual.
158
-
159
- Context:
160
- {context}
161
-
162
- Question: {question}
163
- ```
164
-
165
- The template is loaded once at startup and sent as the user message to the chat endpoint:
166
-
167
- ```python
168
- RAG_PROMPT_TEMPLATE = Path("prompts/rag_prompt.txt").read_text(encoding="utf-8")
169
-
170
- # At query time:
171
- prompt = RAG_PROMPT_TEMPLATE.format(context=context_text, question=user_query)
172
- headers = {"api-key": AZURE_API_KEY, "Content-Type": "application/json"}
173
- payload = {
174
- "model": "gpt-5",
175
- "messages": [{"role": "user", "content": prompt}],
176
- "max_completion_tokens": 512,
177
- "temperature": 0.7,
178
- "top_p": 0.95,
179
- }
180
- resp = requests.post(LLM_ENDPOINT_URL, headers=headers, json=payload)
181
- answer = resp.json()["choices"][0]["message"]["content"]
182
- ```
183
-
184
- > **Tip:** Edit `prompts/rag_prompt.txt` to tune the model's behaviour (tone, language, output format) without touching application code.
185
-
186
- ### Step 6: API Endpoint (`/query`)
187
-
188
- The FastAPI endpoint ties everything together for the evaluation system.
189
-
190
- ```python
191
- @app.post("/query")
192
- async def query_endpoint(request: QueryRequest):
193
- # 1. Retrieve relevant context
194
- # 2. Build augmented prompt
195
- # 3. Generate LLM response
196
- # 4. Return answer + sources
197
- result = rag_query(request.query, top_k=request.top_k)
198
- return JSONResponse(content=result)
199
- ```
200
-
201
- ---
202
-
203
- ## API Endpoints
204
-
205
- ### `POST /query`
206
-
207
- The primary endpoint for the RAG evaluation system.
208
-
209
- **Request:**
210
- ```json
211
- {
212
- "query": "What materials is the Eiffel Tower made of?",
213
- "top_k": 3
214
- }
215
- ```
216
-
217
- **Response:**
218
- ```json
219
- {
220
- "answer": "The Eiffel Tower is made of wrought iron (puddled iron)...",
221
- "sources": [
222
- {"source": "eiffel_tower.txt", "score": 0.87},
223
- {"source": "paris_landmarks.txt", "score": 0.72}
224
- ],
225
- "query": "What materials is the Eiffel Tower made of?"
226
- }
227
- ```
228
-
229
- ### `POST /ingest`
230
-
231
- Add new documents to the knowledge base.
232
-
233
- **Request:**
234
- ```json
235
- {
236
- "text": "The Eiffel Tower was built in 1889...",
237
- "source": "my_document.txt"
238
- }
239
- ```
240
-
241
- **Response:**
242
- ```json
243
- {
244
- "status": "success",
245
- "chunks_added": 5,
246
- "total_chunks": 42
247
- }
248
- ```
249
-
250
- ### `GET /health`
251
-
252
- System health check.
253
-
254
- **Response:**
255
- ```json
256
- {
257
- "status": "healthy",
258
- "documents_in_store": 42,
259
- "embedding_model": "text-embedding-3-small",
260
- "llm_model": "gpt-5"
261
- }
262
- ```
263
-
264
- ---
265
-
266
- ## Setup & Deployment
267
-
268
- ### Prerequisites
269
-
270
- - Python 3.11+
271
- - A Hugging Face account with an API token
272
-
273
- ### Local Development
274
-
275
- ```bash
276
- # Clone the repository
277
- git clone https://huggingface.co/spaces/YOUR_USERNAME/Example-App-Hackathon-Gustave-Eiffel-2026
278
- cd Example-App-Hackathon-Gustave-Eiffel-2026
279
- ```
280
-
281
- #### Set Up a Python Virtual Environment
282
-
283
- Using a virtual environment isolates project dependencies from your global Python installation.
284
-
285
- ```bash
286
- # Create the virtual environment (Python 3.11+ required)
287
- python -m venv ~/.venv/hackathon-eiffel
288
-
289
- # Activate it
290
- # macOS / Linux
291
- source ~/.venv/hackathon-eiffel/bin/activate
292
- # Windows (PowerShell)
293
- ~\.venv\hackathon-eiffel\Scripts\Activate.ps1
294
- # Windows (Command Prompt)
295
- ~\.venv\hackathon-eiffel\Scripts\activate.bat
296
- ```
297
-
298
- Once your virtual environment is active, install dependencies and run the app:
299
-
300
- ```bash
301
- # Install dependencies
302
- pip install -r requirements.txt
303
-
304
- # Set your Azure API key
305
- # macOS / Linux
306
- export AZURE_API_KEY="your_azure_api_key_here"
307
- # Windows (PowerShell)
308
- $env:AZURE_API_KEY = "your_azure_api_key_here"
309
-
310
- # Run the application
311
- python app.py
312
- # Server starts at http://localhost:7860
313
- ```
314
-
315
- > **Tip:** To deactivate the virtual environment when you are done, run `deactivate` (venv) or `conda deactivate` (conda).
316
-
317
- ### Deploy to Hugging Face Spaces
318
-
319
- 1. Create a new Space on huggingface.co (select Gradio SDK)
320
- 2. Add `AZURE_API_KEY` as a Space Secret (Settings → Secrets)
321
- 3. Push this code to the Space repository
322
- 4. The Space automatically installs dependencies and starts the app
323
-
324
- ### Testing the API
325
-
326
- ```bash
327
- # Health check
328
- curl http://localhost:7860/health
329
-
330
- # Query the RAG system
331
- curl -X POST http://localhost:7860/query \
332
- -H "Content-Type: application/json" \
333
- -d '{"query": "What is the Eiffel Tower?", "top_k": 3}'
334
-
335
- # Ingest a new document
336
- curl -X POST http://localhost:7860/ingest \
337
- -H "Content-Type: application/json" \
338
- -d '{"text": "Your document text here...", "source": "new_doc.txt"}'
339
- ```
340
-
341
- ---
342
-
343
- ## Adding Binary Files to the HF Space
344
-
345
- Large or binary files (PDFs, pre-built ChromaDB databases, datasets, model weights) are stored in a **Hugging Face bucket** and mounted into the Space container. The `hf sync` command keeps your local folder in sync with the bucket.
346
-
347
- > **Note:** Git LFS is not supported for Hugging Face Spaces persistent storage. Use the bucket + `hf sync` workflow described here instead.
348
-
349
- ### The `/data` Shared Folder
350
-
351
- Each Hugging Face Space has a **persistent storage bucket** that is automatically mounted at `/data` inside the running container. This folder is the single shared location where the application reads and writes all persistent files — the ChromaDB vector store, ingested documents, and any binary assets.
352
-
353
- | Path in container | Purpose |
354
- |---|---|
355
- | `/data/chroma_db/` | ChromaDB vector store (survives Space restarts) |
356
- | `/data/sample_documents/` | Text/PDF files auto-ingested on startup |
357
- | `/data/DataSet/` | Training and evaluation datasets |
358
-
359
- **Default bucket naming convention:** A Space at
360
- `https://huggingface.co/spaces/<org>/<space-name>`
361
- gets a default storage bucket at
362
- `https://huggingface.co/buckets/<org>/<space-name>-storage`
363
-
364
- For this project:
365
- - Space: `https://huggingface.co/spaces/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026`
366
- - Bucket: `https://huggingface.co/buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage`
367
-
368
- The `hf://` URI for use with the CLI is:
369
- `hf://buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage`
370
-
371
- ### Prerequisites
372
-
373
- ```bash
374
- # Install the hf CLI (requires uv)
375
- uv tool install "huggingface_hub[cli]"
376
-
377
- # Authenticate (needs Write access to the bucket)
378
- export HF_TOKEN="hf_your_token_here"
379
- # or interactively:
380
- hf auth login
381
- ```
382
-
383
- ### Step 1 — Attach the Storage Bucket to Your Space
384
-
385
- 1. Open your Space on huggingface.co
386
- 2. Go to **Settings Persistent Storage**
387
- 3. Under **"Attach storage"**, select the existing bucket **`millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage`** (or create a new one)
388
- 4. Save Hugging Face will mount the bucket at `/data` inside the Space container
389
-
390
- ### Step 2 — Sync Your Local `./data` with the Space Bucket
391
-
392
- Place all persistent files under a local `./data` folder. The expected structure is:
393
-
394
- ```
395
- ./data/
396
- ├── chroma_db/ # Binary files and ChromaDB vector store
397
- │ └── chroma.sqlite3
398
- ./train_data/ # Training/test datasets (PDFs, CSVs, etc.)
399
- ├── Automobile - Train/
400
- ├── Climatique-Train/
401
- └── ...
402
- ```
403
-
404
- **Upload (local bucket):**
405
- ```bash
406
- # Mirror ./data to the bucket — removes remote files deleted locally
407
- hf sync ./data hf://buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage --delete
408
-
409
- # Sync only a specific sub-folder (e.g., the vector store)
410
- hf sync ./data/chroma_db hf://buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage/chroma_db
411
-
412
- # Sync only specific file types
413
- hf sync ./data hf://buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage \
414
- --include "*.pdf" --include "*.sqlite3"
415
- ```
416
-
417
- > **`--delete` flag:** Without it, `hf sync` only uploads new/changed files and never removes anything from the remote. Add `--delete` to make the bucket an exact mirror of your local `./data`.
418
-
419
- `hf sync` is **incremental** it computes checksums and only transfers files that have changed.
420
-
421
- ### Step 3 Download the Bucket to Another Machine
422
-
423
- To pull the latest bucket contents back to a local `./data` folder (e.g., on a new dev machine):
424
-
425
- ```bash
426
- hf sync hf://buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage ./data
427
- ```
428
-
429
- ### Step 4 Sync Hackathon Training Data
430
-
431
- The shared training dataset for this hackathon is stored in a separate read-only bucket. Sync it to a local `./train_data` folder (it will be mounted at `/train_data` inside the Space):
432
-
433
- ```bash
434
- # Download all training data locally
435
- hf sync hf://buckets/millimanfrance/Hackathon2026TrainData ./train_data
436
-
437
- # Download only a specific category
438
- hf sync hf://buckets/millimanfrance/Hackathon2026TrainData/Automobile ./train_data/Automobile
439
- ```
440
-
441
- > **Note:** `Hackathon2026TrainData` is a shared read-only bucket. Do not attempt to push to it.
442
-
443
- To make this data available inside your Space, push it to your Space's own bucket under a `train_data/` sub-folder:
444
-
445
- ```bash
446
- hf sync ./train_data hf://buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage/train_data
447
- ```
448
-
449
- It will then be accessible inside the container at `/data/train_data/`.
450
-
451
- ### Accessing Files in the Space Application
452
-
453
- Once the bucket is mounted, files appear under `/data` inside the Space container.
454
-
455
- The application resolves the data root automatically via a single `DATA_DIR` constant in `app.py`:
456
-
457
- ```python
458
- from pathlib import Path
459
-
460
- # /data when running in HF Spaces (bucket mount), ./data for local dev
461
- DATA_DIR = Path("/data") if Path("/data").is_dir() else Path("./data")
462
-
463
- CHROMA_PERSIST_DIR = str(DATA_DIR / "chroma_db")
464
- SAMPLE_DOCS_DIR = DATA_DIR / "sample_documents"
465
- ```
466
-
467
- All persistent data — the vector store, sample documents, datasets — lives under `DATA_DIR` so a single `hf sync ./data ...` covers everything.
468
-
469
- ### Useful `hf sync` Flags
470
-
471
- | Flag | Description |
472
- |---|---|
473
- | `--include "*.pdf"` | Only sync files matching the pattern |
474
- | `--exclude "*.tmp"` | Skip files matching the pattern |
475
- | `--delete` | Remove files in the destination that no longer exist in the source |
476
- | `--dry-run` | Preview what would be transferred without actually doing it |
477
-
478
- ```bash
479
- # Preview before committing
480
- hf sync ./data hf://buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage --dry-run
481
- ```
482
-
483
- ---
484
-
485
- ## Configuration
486
-
487
- The application loads model configuration with the following priority:
488
-
489
- 1. **`./data/config.json`** the live runtime config (read at startup)
490
- 2. **`./config.json`** (project root) example/template file used as fallback when no runtime config exists; **never put real credentials here**
491
-
492
- ### Step 1 — Create `data/config.json`
493
-
494
- Copy the root template to `./data/` and fill in your Azure OpenAI resource details:
495
-
496
- ```bash
497
- cp config.json data/config.json
498
- ```
499
-
500
- Then edit `data/config.json`:
501
-
502
- ```json
503
- {
504
- "embedding": {
505
- "endpoint_url": "https://<your-resource>.openai.azure.com/openai/deployments/<your-embedding-deployment>/embeddings?api-version=2024-12-01-preview",
506
- "model": "text-embedding-3-small"
507
- },
508
- "llm": {
509
- "endpoint_url": "https://<your-resource>.openai.azure.com/openai/deployments/<your-deployment>/chat/completions?api-version=2024-12-01-preview",
510
- "model": "gpt-5",
511
- "max_completion_tokens": 512,
512
- "temperature": 0.7,
513
- "top_p": 0.95
514
- }
515
- }
516
- ```
517
-
518
- | Field | What to put |
519
- |---|---|
520
- | `<your-resource>` | Your Azure OpenAI resource name (from the Azure Portal) |
521
- | `<your-embedding-deployment>` | The deployment name for your embedding model |
522
- | `<your-deployment>` | The deployment name for your LLM |
523
- | `model` | Must match the model name used when creating the deployment |
524
-
525
- > **Note:** The `endpoint_url` for embeddings ends in `/embeddings` and the one for the LLM ends in `/chat/completions`. Keep those suffixes intact.
526
-
527
- ### Step 2 — Set the API Key
528
-
529
- The API key is **not** stored in `config.json`. Set it as an environment variable:
530
-
531
- ```bash
532
- # macOS / Linux
533
- export AZURE_API_KEY="your_azure_api_key_here"
534
-
535
- # Windows (PowerShell)
536
- $env:AZURE_API_KEY = "your_azure_api_key_here"
537
- ```
538
-
539
- When deploying to Hugging Face Spaces, add it as a **Space Secret** (Settings → Secrets → New secret → name it `AZURE_API_KEY`).
540
-
541
- ### Step 3 — Push `data/config.json` to the HF Bucket
542
-
543
- `data/config.json` lives under `./data` so a normal bucket sync includes it automatically:
544
-
545
- ```bash
546
- hf sync ./data hf://buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage --delete
547
- ```
548
-
549
- The Space container will then find it at `/data/config.json` on next restart.
550
-
551
- > **Do not commit `data/config.json` to Git** — it contains endpoint URLs tied to your Azure resource. Add `data/config.json` to `.gitignore`. The root `config.json` is safe to commit as it only contains placeholder values.
552
-
553
- ### Tunable Parameters
554
-
555
- The following constants in `app.py` can also be adjusted directly:
556
-
557
- | Variable | Default | Description |
558
- |---|---|---|
559
- | `AZURE_API_KEY` | (env var / Space Secret) | Azure OpenAI API key (shared by LLM and embedding endpoints) |
560
- | `EMBEDDING_MODEL_NAME` | `text-embedding-3-small` | Azure OpenAI embedding model |
561
- | `LLM_MODEL_NAME` | `gpt-5` | Azure OpenAI LLM for answer generation |
562
- | `LLM_MAX_TOKENS` | `512` | Maximum tokens in the LLM response |
563
- | `LLM_TEMPERATURE` | `0.7` | Sampling temperature for the LLM |
564
- | `LLM_TOP_P` | `0.95` | Top-p (nucleus) sampling for the LLM |
565
- | `DATA_DIR` | `/data` (HF Spaces) or `./data` (local) | Root directory for all persistent data |
566
- | `CHROMA_PERSIST_DIR` | `DATA_DIR/chroma_db` | ChromaDB storage path |
567
- | `SAMPLE_DOCS_DIR` | `DATA_DIR/sample_documents` | Documents ingested on startup |
568
- | `CHUNK_SIZE` | `512` | Text chunk size in characters |
569
- | `CHUNK_OVERLAP` | `50` | Overlap between chunks |
570
- | `TOP_K_RESULTS` | `3` | Number of context chunks to retrieve |
571
-
572
- ---
573
-
574
- ## How It Works (Detailed)
575
-
576
- ### Why RAG?
577
-
578
- Large Language Models have a knowledge cutoff and can hallucinate. RAG solves this by:
579
- - **Grounding** responses in actual documents
580
- - **Updating** knowledge without retraining
581
- - **Providing** source attribution for answers
582
-
583
- ### Why ChromaDB in HF Spaces?
584
-
585
- ChromaDB is ideal for Hugging Face Spaces because:
586
- - Runs **in-process** (no external database needed)
587
- - Supports **persistent storage** (survives Space restarts)
588
- - Uses **HNSW index** for fast approximate nearest neighbor search
589
- - Zero configuration required
590
-
591
- ### Why Azure OpenAI Embeddings?
592
-
593
- - **High-quality embeddings** — `text-embedding-3-small` produces state-of-the-art embeddings with excellent semantic understanding
594
- - **No local model loading** — Eliminates GPU/memory requirements on the Space
595
- - **Scalable** — Handles large batch embedding requests via the API
596
- - **Consistent** — Same model used across environments (dev, staging, production)
597
-
598
- ### Evaluation Integration
599
-
600
- The `/query` endpoint is designed to be called by external RAG evaluation frameworks. It returns:
601
- - The generated `answer` for correctness evaluation
602
- - Source `documents` for faithfulness/groundedness checks
603
- - Similarity `scores` for retrieval quality assessment
604
-
605
- ---
606
-
607
- ## Troubleshooting
608
-
609
- ### ChromaDB Telemetry Error
610
-
611
- If you see `capture() takes 1 positional argument but 3 were given` in the logs, it is a version incompatibility between ChromaDB and the `posthog` library. Telemetry is disabled at startup (`anonymized_telemetry=False`) so this error should no longer appear. If it persists after updating dependencies, pin `posthog<3.0` in `requirements.txt`.
612
-
613
- ### LLM / Embedding API Errors
614
-
615
- If the `/query` endpoint logs a `503 Service Unavailable` or `401 Unauthorized`:
616
-
617
- 1. Verify `AZURE_API_KEY` is set correctly as an environment variable or Space Secret
618
- 2. Check that the endpoint URLs in `config.json` match your Azure OpenAI deployment
619
- 3. Ensure your Azure OpenAI deployment is active and the model name matches the deployment name
620
- 4. The app calls the Azure OpenAI-compatible `chat/completions` and `embeddings` endpoints directly via REST
621
-
622
- ### SSL Certificate Verification Error
623
-
624
- If you see an error like the one below when running `python app.py`, your machine is most likely behind a **corporate proxy that performs SSL inspection** and has its own root CA that Python does not trust by default.
625
-
626
- ```
627
- ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify
628
- failed: unable to get local issuer certificate
629
- ```
630
-
631
- **Fix — point `requests` to your corporate CA bundle:**
632
-
633
- ```bash
634
- # macOS / Linux — use the system bundle (adjust path for your distro)
635
- export REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt # Debian/Ubuntu
636
- export REQUESTS_CA_BUNDLE=/etc/pki/tls/certs/ca-bundle.crt # RHEL/CentOS
637
-
638
- # Or point to a specific corporate certificate file
639
- export REQUESTS_CA_BUNDLE=/path/to/corporate-ca.crt
640
-
641
- # Windows (PowerShell)
642
- $env:REQUESTS_CA_BUNDLE = "C:\path\to\corporate-ca.crt"
643
- ```
644
-
645
- Set the variable **before** running `python app.py`. The `requests` library (used for Azure OpenAI API calls) reads `REQUESTS_CA_BUNDLE` automatically — no code change is needed.
646
-
647
- > **How to export your corporate CA certificate:**
648
- > Open the failing URL (`https://huggingface.co`) in your browser, click the padlock icon → View Certificate → export the root CA as a `.crt` / `.pem` file, then point `REQUESTS_CA_BUNDLE` to that file.
649
-
650
- ### `hf sync` 401 Unauthorized Error
651
-
652
- If `hf sync` fails with:
653
-
654
- ```
655
- Error: Client error '401 Unauthorized' for url
656
- 'https://huggingface.co/api/buckets/.../tree?recursive=true'
657
- Invalid username or password.
658
- ```
659
-
660
- the `hf` CLI has not been authenticated. Log in with your Hugging Face token:
661
-
662
- ```bash
663
- hf auth login
664
- # Paste your token when prompted (needs read + write access to the bucket)
665
- ```
666
-
667
- Or set the token as an environment variable so the CLI picks it up automatically without an interactive prompt:
668
-
669
- ```bash
670
- export HF_TOKEN="hf_your_token_here"
671
- hf sync ./data hf://buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage
672
- ```
673
-
674
- > **Generate a token:** Go to huggingface.co → Settings → Access Tokens → New token. Select **Write** role so the CLI can both read and upload to the bucket.
675
-
676
- > **Check current login state:**
677
- > ```bash
678
- > hf auth whoami
679
- > ```
680
-
681
- ---
682
-
683
- ### `hf sync` SSL Certificate Verification Error
684
-
685
- The `hf` CLI (installed via `uv tool install huggingface_hub`) uses `httpx` internally instead of `requests`, so it ignores `REQUESTS_CA_BUNDLE`. If `hf sync` fails with:
686
-
687
- ```
688
- httpcore.ConnectError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed:
689
- unable to get local issuer certificate
690
- ```
691
-
692
- you must set the certificate bundle through the variables that `httpx` (and the underlying `ssl` module) respects:
693
-
694
- ```bash
695
- # Option A — point to your corporate CA bundle file (recommended)
696
- export SSL_CERT_FILE=/path/to/corporate-ca.crt
697
- export REQUESTS_CA_BUNDLE=/path/to/corporate-ca.crt # keep this too for other tools
698
-
699
- hf sync ./data hf://buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage
700
-
701
- # Option B — append your CA cert to the system bundle and point there
702
- cat /path/to/corporate-ca.crt >> /etc/ssl/certs/ca-certificates.crt
703
- export SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt
704
- ```
705
-
706
- `SSL_CERT_FILE` overrides the default CA store for Python's `ssl` module, which `httpx` / `httpcore` uses directly.
707
-
708
- **If you need to set these variables permanently** (e.g., in a shared dev environment), add them to your shell profile:
709
-
710
- ```bash
711
- # ~/.bashrc or ~/.zshrc
712
- export SSL_CERT_FILE=/path/to/corporate-ca.crt
713
- export REQUESTS_CA_BUNDLE=/path/to/corporate-ca.crt
714
- ```
715
-
716
- > **Finding your corporate CA cert on Linux:**
717
- > ```bash
718
- > # List all trusted CAs and look for your company's entry
719
- > awk -v cmd='openssl x509 -noout -subject' '/BEGIN CERT/{close(cmd)}; {print | cmd}' \
720
- > /etc/ssl/certs/ca-certificates.crt | grep -i "your-company-name"
721
- >
722
- > # Or export the cert directly from the proxy
723
- > echo | openssl s_client -connect huggingface.co:443 -showcerts 2>/dev/null \
724
- > | openssl x509 -outform PEM > /tmp/hf-chain.pem
725
- > export SSL_CERT_FILE=/tmp/hf-chain.pem
726
- > ```
727
-
728
- ---
729
-
730
- ## License
731
-
732
- Apache 2.0
733
-
 
1
+ ---
2
+ title: Example App Hackathon Gustave Eiffel 2026
3
+ emoji: 🤖
4
+ colorFrom: blue
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: 4.44.1
8
+ python_version: '3.11'
9
+ app_file: app.py
10
+ pinned: false
11
+ license: apache-2.0
12
+ ---
13
+
14
+ # 🗼 RAG Chat API — Gustave Eiffel Hackathon 2026
15
+
16
+ A complete **Retrieval-Augmented Generation (RAG)** system deployed as a Hugging Face Space, with a `/query` API endpoint designed for the RAG evaluation system.
17
+
18
+ ---
19
+
20
+ ## Table of Contents
21
+
22
+ 1. [Overview](#overview)
23
+ 2. [Architecture](#architecture)
24
+ 3. [Setup & Deployment](#setup--deployment)
25
+ 4. [Adding Binary Files to the HF Space](#adding-binary-files-to-the-hf-space)
26
+ 5. [Configuration](#configuration)
27
+ 6. [How It Works (Detailed)](#how-it-works-detailed)
28
+
29
+ ---
30
+
31
+ ## Overview
32
+
33
+ This application demonstrates how to build a production-ready RAG system within the Hugging Face ecosystem. It covers:
34
+
35
+ | Requirement | Solution |
36
+ |---|---|
37
+ | LLM API calls | Azure OpenAI (`gpt-5` via REST) |
38
+ | Text → Embeddings | Azure OpenAI (`text-embedding-3-small` via REST) |
39
+ | Vector Store | ChromaDB (persistent, runs in-process) |
40
+ | API Endpoint | FastAPI with `POST /query` |
41
+ | UI | Gradio Blocks (chat + document ingestion) |
42
+
43
+ ---
44
+
45
+ ## Architecture
46
+
47
+ ```
48
+ ┌─────────────────────────────────────────────────────────────┐
49
+ │ Hugging Face Space │
50
+ │ │
51
+ ┌──────────┐ ┌──────────────┐ ┌───────────────┐
52
+ Gradio │ │ FastAPI │ │ ChromaDB │ │
53
+ │ UI ────▶│ /query │────▶│ Vector Store │
54
+ │ │ │ │ /ingest │ │ (persistent) │ │
55
+ └──────────┘ ─────────────┘ └───────────────┘
56
+
57
+
58
+ ┌──────────────────┐ ┌─────────────────┐
59
+ Azure OpenAI │ Azure OpenAI │ │
60
+ │ GPT-5 (LLM) │ │ text-embedding │
61
+ │ │ │ │ -3-small │ │
62
+ └──────────────────┘ └─────────────────┘
63
+ └─────────────────────────────────────────────────────────────┘
64
+ ```
65
+
66
+ ---
67
+
68
+
69
+ ## Setup & Deployment
70
+
71
+ ### Prerequisites
72
+
73
+ - Python 3.11+
74
+ - A Hugging Face account with an API token
75
+
76
+ ### Local Development
77
+
78
+ ```bash
79
+ # Clone the repository
80
+ git clone https://huggingface.co/spaces/YOUR_USERNAME/Example-App-Hackathon-Gustave-Eiffel-2026
81
+ cd Example-App-Hackathon-Gustave-Eiffel-2026
82
+ ```
83
+
84
+ #### Set Up a Python Virtual Environment
85
+
86
+ Using a virtual environment isolates project dependencies from your global Python installation.
87
+
88
+ ```bash
89
+ # Create the virtual environment (Python 3.11+ required)
90
+ python -m venv ~/.venv/hackathon-eiffel
91
+
92
+ # Activate it
93
+ # macOS / Linux
94
+ source ~/.venv/hackathon-eiffel/bin/activate
95
+ # Windows (PowerShell)
96
+ ~\.venv\hackathon-eiffel\Scripts\Activate.ps1
97
+ # Windows (Command Prompt)
98
+ ~\.venv\hackathon-eiffel\Scripts\activate.bat
99
+
100
+ ```
101
+
102
+ Once your virtual environment is active, install dependencies and run the app:
103
+
104
+ ```bash
105
+ # Install dependencies
106
+ pip install -r requirements.txt
107
+
108
+ # Set your Azure API key
109
+ # macOS / Linux
110
+ export AZURE_API_KEY="your_azure_api_key_here"
111
+ # Windows (PowerShell)
112
+ $env:AZURE_API_KEY = "your_azure_api_key_here"
113
+
114
+ # Run the application
115
+ python app.py
116
+ # Server starts at http://localhost:7860
117
+
118
+ # To make it work, you first need to create embeddings , you can learn about it from README_RAG.md
119
+ ```
120
+
121
+ > **Tip:** To deactivate the virtual environment when you are done, run `deactivate` (venv) or `conda deactivate` (conda).
122
+
123
+
124
+
125
+ ### Testing the API
126
+
127
+ ```bash
128
+ # Health check
129
+ curl http://localhost:7860/health
130
+
131
+ # Query the RAG system
132
+ curl -X POST http://localhost:7860/query \
133
+ -H "Content-Type: application/json" \
134
+ -d '{"query": "What is the Eiffel Tower?", "top_k": 3}'
135
+
136
+ # Ingest a new document
137
+ curl -X POST http://localhost:7860/ingest \
138
+ -H "Content-Type: application/json" \
139
+ -d '{"text": "Your document text here...", "source": "new_doc.txt"}'
140
+ ```
141
+
142
+ ---
143
+
144
+ ## Adding Binary Files to the HF Space
145
+
146
+ Large or binary files (PDFs, pre-built ChromaDB databases, datasets, model weights) are stored in a **Hugging Face bucket** and mounted into the Space container. The `hf sync` command keeps your local folder in sync with the bucket.
147
+
148
+ > **Note:** Git LFS is not supported for Hugging Face Spaces persistent storage. Use the bucket + `hf sync` workflow described here instead.
149
+
150
+ ### The `/data` Shared Folder
151
+
152
+ Each Hugging Face Space has a **persistent storage bucket** that is automatically mounted at `/data` inside the running container. This folder is the single shared location where the application reads and writes all persistent files — the ChromaDB vector store, ingested documents, and any binary assets.
153
+
154
+ | Path in container | Purpose |
155
+ |---|---|
156
+ | `/data/chroma_db/` | ChromaDB vector store (survives Space restarts) |
157
+ | `/data/sample_documents/` | Text/PDF files auto-ingested on startup |
158
+ | `/data/DataSet/` | Training and evaluation datasets |
159
+
160
+ **Default bucket naming convention:** A Space at
161
+ `https://huggingface.co/spaces/<org>/<space-name>`
162
+ gets a default storage bucket at
163
+ `https://huggingface.co/buckets/<org>/<space-name>-storage`
164
+
165
+ For this project:
166
+ - Space: `https://huggingface.co/spaces/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026`
167
+ - Bucket: `https://huggingface.co/buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage`
168
+
169
+ The `hf://` URI for use with the CLI is:
170
+ `hf://buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage`
171
+
172
+ ### Prerequisites
173
+
174
+ ```bash
175
+ # Install the hf CLI (requires uv)
176
+ uv tool install "huggingface_hub[cli]"
177
+
178
+ # Authenticate (needs Write access to the bucket)
179
+ export HF_TOKEN="hf_your_token_here"
180
+ # or interactively:
181
+ hf auth login
182
+ ```
183
+
184
+ ### Step 1 Attach the Storage Bucket to Your Space
185
+
186
+ 1. Open your Space on huggingface.co
187
+ 2. Go to **Settings → Persistent Storage**
188
+ 3. Under **"Attach storage"**, select the existing bucket **`millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage`** (or create a new one)
189
+ 4. Save — Hugging Face will mount the bucket at `/data` inside the Space container
190
+
191
+ ### Step 2 — Sync Your Local `./data` with the Space Bucket
192
+
193
+ Place all persistent files under a local `./data` folder. The expected structure is:
194
+
195
+ ```
196
+ ./data/
197
+ ├── chroma_db/ # Binary files and ChromaDB vector store
198
+ │ └── chroma.sqlite3
199
+ ./train_data/ # Training/test datasets (PDFs, CSVs, etc.)
200
+ ├── Automobile - Train/
201
+ ├── Climatique-Train/
202
+ └── ...
203
+ ```
204
+
205
+ **Upload (local → bucket):**
206
+ ```bash
207
+ # Mirror ./data to the bucket removes remote files deleted locally
208
+ hf sync ./data hf://buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage --delete
209
+
210
+ # Sync only a specific sub-folder (e.g., the vector store)
211
+ hf sync ./data/chroma_db hf://buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage/chroma_db
212
+
213
+ # Sync only specific file types
214
+ hf sync ./data hf://buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage \
215
+ --include "*.pdf" --include "*.sqlite3"
216
+ ```
217
+
218
+ > **`--delete` flag:** Without it, `hf sync` only uploads new/changed files and never removes anything from the remote. Add `--delete` to make the bucket an exact mirror of your local `./data`.
219
+
220
+ `hf sync` is **incremental** it computes checksums and only transfers files that have changed.
221
+
222
+ ### Step 3 — Download the Bucket to Another Machine
223
+
224
+ To pull the latest bucket contents back to a local `./data` folder (e.g., on a new dev machine):
225
+
226
+ ```bash
227
+ hf sync hf://buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage ./data
228
+ ```
229
+
230
+ ### Step 4 — Sync Hackathon Training Data
231
+
232
+ The shared training dataset for this hackathon is stored in a separate read-only bucket. Sync it to a local `./train_data` folder (it will be mounted at `/train_data` inside the Space):
233
+
234
+ ```bash
235
+ # Download all training data locally
236
+ hf sync hf://buckets/millimanfrance/Hackathon2026TrainData ./train_data
237
+
238
+ # Download only a specific category
239
+ hf sync hf://buckets/millimanfrance/Hackathon2026TrainData/Automobile ./train_data/Automobile
240
+ ```
241
+
242
+ > **Note:** `Hackathon2026TrainData` is a shared read-only bucket. Do not attempt to push to it.
243
+
244
+ To make this data available inside your Space, push it to your Space's own bucket under a `train_data/` sub-folder:
245
+
246
+ ```bash
247
+ hf sync ./train_data hf://buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage/train_data
248
+ ```
249
+
250
+ It will then be accessible inside the container at `/data/train_data/`.
251
+
252
+ ### Accessing Files in the Space Application
253
+
254
+ Once the bucket is mounted, files appear under `/data` inside the Space container.
255
+
256
+ The application resolves the data root automatically via a single `DATA_DIR` constant in `app.py`:
257
+
258
+ ```python
259
+ from pathlib import Path
260
+
261
+ # /data when running in HF Spaces (bucket mount), ./data for local dev
262
+ DATA_DIR = Path("/data") if Path("/data").is_dir() else Path("./data")
263
+
264
+ CHROMA_PERSIST_DIR = str(DATA_DIR / "chroma_db")
265
+ SAMPLE_DOCS_DIR = DATA_DIR / "sample_documents"
266
+ ```
267
+
268
+ All persistent data — the vector store, sample documents, datasets — lives under `DATA_DIR` so a single `hf sync ./data ...` covers everything.
269
+
270
+ ### Useful `hf sync` Flags
271
+
272
+ | Flag | Description |
273
+ |---|---|
274
+ | `--include "*.pdf"` | Only sync files matching the pattern |
275
+ | `--exclude "*.tmp"` | Skip files matching the pattern |
276
+ | `--delete` | Remove files in the destination that no longer exist in the source |
277
+ | `--dry-run` | Preview what would be transferred without actually doing it |
278
+
279
+ ```bash
280
+ # Preview before committing
281
+ hf sync ./data hf://buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage --dry-run
282
+ ```
283
+
284
+ ---
285
+
286
+ ## Configuration
287
+
288
+ The application loads model configuration with the following priority:
289
+
290
+ 1. **`./data/config.json`** — the live runtime config (read at startup)
291
+ 2. **`./config.json`** (project root) — example/template file used as fallback when no runtime config exists; **never put real credentials here**
292
+
293
+ ### Step 1 — Create `data/config.json`
294
+
295
+ Copy the root template to `./data/` and fill in your Azure OpenAI resource details:
296
+
297
+ ```bash
298
+ cp config.json data/config.json
299
+ ```
300
+
301
+ Then edit `data/config.json`:
302
+
303
+ ```json
304
+ {
305
+ "embedding": {
306
+ "endpoint_url": "https://<your-resource>.openai.azure.com/openai/deployments/<your-embedding-deployment>/embeddings?api-version=2024-12-01-preview",
307
+ "model": "text-embedding-3-small"
308
+ },
309
+ "llm": {
310
+ "endpoint_url": "https://<your-resource>.openai.azure.com/openai/deployments/<your-deployment>/chat/completions?api-version=2024-12-01-preview",
311
+ "model": "gpt-5",
312
+ "max_completion_tokens": 512,
313
+ "temperature": 0.7,
314
+ "top_p": 0.95
315
+ }
316
+ }
317
+ ```
318
+
319
+ | Field | What to put |
320
+ |---|---|
321
+ | `<your-resource>` | Your Azure OpenAI resource name (from the Azure Portal) |
322
+ | `<your-embedding-deployment>` | The deployment name for your embedding model |
323
+ | `<your-deployment>` | The deployment name for your LLM |
324
+ | `model` | Must match the model name used when creating the deployment |
325
+
326
+ > **Note:** The `endpoint_url` for embeddings ends in `/embeddings` and the one for the LLM ends in `/chat/completions`. Keep those suffixes intact.
327
+
328
+ ### Step 2 — Set the API Key
329
+
330
+ The API key is **not** stored in `config.json`. Set it as an environment variable:
331
+
332
+ ```bash
333
+ # macOS / Linux
334
+ export AZURE_API_KEY="your_azure_api_key_here"
335
+
336
+ # Windows (PowerShell)
337
+ $env:AZURE_API_KEY = "your_azure_api_key_here"
338
+ ```
339
+
340
+ When deploying to Hugging Face Spaces, add it as a **Space Secret** (Settings → Secrets → New secret → name it `AZURE_API_KEY`).
341
+
342
+ ### Step 3 — Push `data/config.json` to the HF Bucket
343
+
344
+ `data/config.json` lives under `./data` so a normal bucket sync includes it automatically:
345
+
346
+ ```bash
347
+ hf sync ./data hf://buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage --delete
348
+ ```
349
+
350
+ The Space container will then find it at `/data/config.json` on next restart.
351
+
352
+ > **Do not commit `data/config.json` to Git** — it contains endpoint URLs tied to your Azure resource. Add `data/config.json` to `.gitignore`. The root `config.json` is safe to commit as it only contains placeholder values.
353
+
354
+ ### Tunable Parameters
355
+
356
+ The following constants in `app.py` can also be adjusted directly:
357
+
358
+ | Variable | Default | Description |
359
+ |---|---|---|
360
+ | `AZURE_API_KEY` | (env var / Space Secret) | Azure OpenAI API key (shared by LLM and embedding endpoints) |
361
+ | `EMBEDDING_MODEL_NAME` | `text-embedding-3-small` | Azure OpenAI embedding model |
362
+ | `LLM_MODEL_NAME` | `gpt-5` | Azure OpenAI LLM for answer generation |
363
+ | `LLM_MAX_TOKENS` | `512` | Maximum tokens in the LLM response |
364
+ | `LLM_TEMPERATURE` | `0.7` | Sampling temperature for the LLM |
365
+ | `LLM_TOP_P` | `0.95` | Top-p (nucleus) sampling for the LLM |
366
+ | `DATA_DIR` | `/data` (HF Spaces) or `./data` (local) | Root directory for all persistent data |
367
+ | `CHROMA_PERSIST_DIR` | `DATA_DIR/chroma_db` | ChromaDB storage path |
368
+ | `SAMPLE_DOCS_DIR` | `DATA_DIR/sample_documents` | Documents ingested on startup |
369
+ | `CHUNK_SIZE` | `512` | Text chunk size in characters |
370
+ | `CHUNK_OVERLAP` | `50` | Overlap between chunks |
371
+ | `TOP_K_RESULTS` | `3` | Number of context chunks to retrieve |
372
+
373
+ ---
374
+
375
+ ## How It Works (Detailed)
376
+
377
+ ### Why RAG?
378
+
379
+ Large Language Models have a knowledge cutoff and can hallucinate. RAG solves this by:
380
+ - **Grounding** responses in actual documents
381
+ - **Updating** knowledge without retraining
382
+ - **Providing** source attribution for answers
383
+
384
+ ### Why ChromaDB in HF Spaces?
385
+
386
+ ChromaDB is ideal for Hugging Face Spaces because:
387
+ - Runs **in-process** (no external database needed)
388
+ - Supports **persistent storage** (survives Space restarts)
389
+ - Uses **HNSW index** for fast approximate nearest neighbor search
390
+ - Zero configuration required
391
+
392
+ ### Why Azure OpenAI Embeddings?
393
+
394
+ - **High-quality embeddings** — `text-embedding-3-small` produces state-of-the-art embeddings with excellent semantic understanding
395
+ - **No local model loading** — Eliminates GPU/memory requirements on the Space
396
+ - **Scalable** Handles large batch embedding requests via the API
397
+ - **Consistent** — Same model used across environments (dev, staging, production)
398
+
399
+ ### Evaluation Integration
400
+
401
+ The `/query` endpoint is designed to be called by external RAG evaluation frameworks. It returns:
402
+ - The generated `answer` for correctness evaluation
403
+ - Source `documents` for faithfulness/groundedness checks
404
+ - Similarity `scores` for retrieval quality assessment
405
+
406
+ ---
407
+
408
+ ## Troubleshooting
409
+
410
+ ### ChromaDB Telemetry Error
411
+
412
+ If you see `capture() takes 1 positional argument but 3 were given` in the logs, it is a version incompatibility between ChromaDB and the `posthog` library. Telemetry is disabled at startup (`anonymized_telemetry=False`) so this error should no longer appear. If it persists after updating dependencies, pin `posthog<3.0` in `requirements.txt`.
413
+
414
+ ### LLM / Embedding API Errors
415
+
416
+ If the `/query` endpoint logs a `503 Service Unavailable` or `401 Unauthorized`:
417
+
418
+ 1. Verify `AZURE_API_KEY` is set correctly as an environment variable or Space Secret
419
+ 2. Check that the endpoint URLs in `config.json` match your Azure OpenAI deployment
420
+ 3. Ensure your Azure OpenAI deployment is active and the model name matches the deployment name
421
+ 4. The app calls the Azure OpenAI-compatible `chat/completions` and `embeddings` endpoints directly via REST
422
+
423
+ ### SSL Certificate Verification Error
424
+
425
+ If you see an error like the one below when running `python app.py`, your machine is most likely behind a **corporate proxy that performs SSL inspection** and has its own root CA that Python does not trust by default.
426
+
427
+ ```
428
+ ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify
429
+ failed: unable to get local issuer certificate
430
+ ```
431
+
432
+ **Fix — point `requests` to your corporate CA bundle:**
433
+
434
+ ```bash
435
+ # macOS / Linux — use the system bundle (adjust path for your distro)
436
+ export REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt # Debian/Ubuntu
437
+ export REQUESTS_CA_BUNDLE=/etc/pki/tls/certs/ca-bundle.crt # RHEL/CentOS
438
+
439
+ # Or point to a specific corporate certificate file
440
+ export REQUESTS_CA_BUNDLE=/path/to/corporate-ca.crt
441
+
442
+ # Windows (PowerShell)
443
+ $env:REQUESTS_CA_BUNDLE = "C:\path\to\corporate-ca.crt"
444
+ ```
445
+
446
+ Set the variable **before** running `python app.py`. The `requests` library (used for Azure OpenAI API calls) reads `REQUESTS_CA_BUNDLE` automatically — no code change is needed.
447
+
448
+ > **How to export your corporate CA certificate:**
449
+ > Open the failing URL (`https://huggingface.co`) in your browser, click the padlock icon → View Certificate → export the root CA as a `.crt` / `.pem` file, then point `REQUESTS_CA_BUNDLE` to that file.
450
+
451
+ ### `hf sync` 401 Unauthorized Error
452
+
453
+ If `hf sync` fails with:
454
+
455
+ ```
456
+ Error: Client error '401 Unauthorized' for url
457
+ 'https://huggingface.co/api/buckets/.../tree?recursive=true'
458
+ Invalid username or password.
459
+ ```
460
+
461
+ the `hf` CLI has not been authenticated. Log in with your Hugging Face token:
462
+
463
+ ```bash
464
+ hf auth login
465
+ # Paste your token when prompted (needs read + write access to the bucket)
466
+ ```
467
+
468
+ Or set the token as an environment variable so the CLI picks it up automatically without an interactive prompt:
469
+
470
+ ```bash
471
+ export HF_TOKEN="hf_your_token_here"
472
+ hf sync ./data hf://buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage
473
+ ```
474
+
475
+ > **Generate a token:** Go to huggingface.co Settings Access Tokens New token. Select **Write** role so the CLI can both read and upload to the bucket.
476
+
477
+ > **Check current login state:**
478
+ > ```bash
479
+ > hf auth whoami
480
+ > ```
481
+
482
+ ---
483
+
484
+ ### `hf sync` SSL Certificate Verification Error
485
+
486
+ The `hf` CLI (installed via `uv tool install huggingface_hub`) uses `httpx` internally instead of `requests`, so it ignores `REQUESTS_CA_BUNDLE`. If `hf sync` fails with:
487
+
488
+ ```
489
+ httpcore.ConnectError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed:
490
+ unable to get local issuer certificate
491
+ ```
492
+
493
+ you must set the certificate bundle through the variables that `httpx` (and the underlying `ssl` module) respects:
494
+
495
+ ```bash
496
+ # Option A — point to your corporate CA bundle file (recommended)
497
+ export SSL_CERT_FILE=/path/to/corporate-ca.crt
498
+ export REQUESTS_CA_BUNDLE=/path/to/corporate-ca.crt # keep this too for other tools
499
+
500
+ hf sync ./data hf://buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage
501
+
502
+ # Option B — append your CA cert to the system bundle and point there
503
+ cat /path/to/corporate-ca.crt >> /etc/ssl/certs/ca-certificates.crt
504
+ export SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt
505
+ ```
506
+
507
+ `SSL_CERT_FILE` overrides the default CA store for Python's `ssl` module, which `httpx` / `httpcore` uses directly.
508
+
509
+ **If you need to set these variables permanently** (e.g., in a shared dev environment), add them to your shell profile:
510
+
511
+ ```bash
512
+ # ~/.bashrc or ~/.zshrc
513
+ export SSL_CERT_FILE=/path/to/corporate-ca.crt
514
+ export REQUESTS_CA_BUNDLE=/path/to/corporate-ca.crt
515
+ ```
516
+
517
+ > **Finding your corporate CA cert on Linux:**
518
+ > ```bash
519
+ > # List all trusted CAs and look for your company's entry
520
+ > awk -v cmd='openssl x509 -noout -subject' '/BEGIN CERT/{close(cmd)}; {print | cmd}' \
521
+ > /etc/ssl/certs/ca-certificates.crt | grep -i "your-company-name"
522
+ >
523
+ > # Or export the cert directly from the proxy
524
+ > echo | openssl s_client -connect huggingface.co:443 -showcerts 2>/dev/null \
525
+ > | openssl x509 -outform PEM > /tmp/hf-chain.pem
526
+ > export SSL_CERT_FILE=/tmp/hf-chain.pem
527
+ > ```
528
+
529
+ ---
530
+
531
+ ## License
532
+
533
+ Apache 2.0
534
+