Spaces:
Sleeping
Sleeping
Quincy Hsieh commited on
Commit Β·
dddc53b
1
Parent(s): 53cab5b
Update README for data sync
Browse files35 unmodified lines3637383940394041424314 unmodified lines58596061626361626364656622 unmodified lines89909192929394959696979899100989910010110210310424 unmodified lines1291301311311321331341351361361371381381391401411423 unmodified lines14614714814814915015115216 unmodified lines16917017117117217317417517217317417517617717817918018118218318471 unmodified lines25625725825325425926026126226337 unmodified lines3013023032983043053003063073023083093103115 unmodified lines31731831931432032132232318 unmodified lines34234334433934534634734834935035135235335435535635735835936036136236336436536636736836937037137237313 unmodified lines3873883893623903913923933943953683963973703713723733743753983994004014024033793804044053823834064074084094103 unmodified lines4144154164174183934194204214223 unmodified lines42642742842943043143243343443543643743843944044144244344444544644744844945045145240545345440745545645745825 unmodified lines48448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453544144244353653753853954054154254354420 unmodified lines56556656747056856947247347447557057157257357457557610 unmodified lines58758858949259059159259349459459559659759859960018 unmodified lines61962062151962262362462535 unmodified lines
| Requirement | Solution ||---|---|| LLM API calls | Hugging Face Inference API (`InferenceClient`) || Text β Embeddings | `sentence-transformers/all-MiniLM-L6-v2` (runs locally) || LLM API calls | Azure OpenAI (`gpt-5` via REST) || Text β Embeddings | Azure OpenAI (`text-embedding-3-small` via REST) || Vector Store | ChromaDB (persistent, runs in-process) || API Endpoint | FastAPI with `POST /query` || UI | Gradio Blocks (chat + document ingestion) |14 unmodified linesβ β β² ββ βΌ β ββ ββββββββββββββββββββ βββββββββββββββββββ ββ β HF Inference β β Sentence β ββ β API (LLM) β β Transformers β ββ β Qwen2.5-72B β β (Embeddings) β ββ β Azure OpenAI β β Azure OpenAI β ββ β GPT-5 (LLM) β β text-embedding β ββ β β β -3-small β ββ ββββββββββββββββββββ βββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ```22 unmodified lines
Convert text chunks into dense vector representations that capture semantic meaning.
1. **Load model** β We use `sentence-transformers/all-MiniLM-L6-v2`, a lightweight model that produces 384-dimensional vectors1. **Call Azure OpenAI** β We use the `text-embedding-3-small` model via the Azure OpenAI embeddings endpoint2. **Encode text** β Each chunk is transformed into a fixed-size vector where semantically similar texts are closer together in vector space
```pythonfrom sentence_transformers import SentenceTransformerimport requests as http_requests
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")embeddings = model.encode(["chunk 1 text", "chunk 2 text"])# Result: numpy array of shape (2, 384)headers = {"api-key": AZURE_API_KEY, "Content-Type": "application/json"}payload = {"input": ["chunk 1 text", "chunk 2 text"], "model": "text-embedding-3-small"}resp = http_requests.post(EMBEDDING_ENDPOINT_URL, headers=headers, json=payload)embeddings = [item["embedding"] for item in resp.json()["data"]]```
### Step 3: Store in Vector Database (ChromaDB)24 unmodified lines
When a user asks a question, find the most relevant context.
1. **Embed the query** β Use the same embedding model to convert the question to a vector1. **Embed the query** β Use the same Azure OpenAI embedding model to convert the question to a vector2. **Similarity search** β Find the top-K nearest vectors in ChromaDB (cosine similarity)3. **Return context** β Extract the original text chunks for the closest matches
```pythonquery_embedding = model.encode(["What is the Eiffel Tower?"])query_embedding = generate_embeddings(["What is the Eiffel Tower?"])[0]results = collection.query( query_embeddings=query_embedding.tolist(), query_embeddings=[query_embedding], n_results=3,)```3 unmodified linesCombine retrieved context with the user's question and generate an answer.
1. **Build prompt** β Load the template from [`prompts/rag_prompt.txt`](prompts/rag_prompt.txt), inject retrieved context and the user's question2. **Call LLM API** β Send the prompt to the Hugging Face Inference API (`chat_completion`, Qwen2.5-72B-Instruct)2. **Call Azure OpenAI** β Send the prompt to the Azure OpenAI chat/completions endpoint (`gpt-5`)3. **Return response** β The LLM generates an answer grounded in the provided context
The prompt template (`prompts/rag_prompt.txt`):16 unmodified lines
# At query time:prompt = RAG_PROMPT_TEMPLATE.format(context=context_text, question=user_query)response = llm_client.chat_completion( messages=[{"role": "user", "content": prompt}], max_tokens=512,)answer = response.choices[0].message.contentheaders = {"api-key": AZURE_API_KEY, "Content-Type": "application/json"}payload = { "model": "gpt-5", "messages": [{"role": "user", "content": prompt}], "max_tokens": 512, "temperature": 0.7, "top_p": 0.95,}resp = requests.post(LLM_ENDPOINT_URL, headers=headers, json=payload)answer = resp.json()["choices"][0]["message"]["content"]```
> **Tip:** Edit `prompts/rag_prompt.txt` to tune the model's behaviour (tone, language, output format) without touching application code.71 unmodified lines{ "status": "healthy", "documents_in_store": 42, "embedding_model": "sentence-transformers/all-MiniLM-L6-v2", "llm_model": "HuggingFaceH4/zephyr-7b-beta" "embedding_model": "text-embedding-3-small", "llm_model": "gpt-5"}```
37 unmodified lines# Install dependenciespip install -r requirements.txt
# Set your HF token# Set your Azure API key# macOS / Linuxexport HF_TOKEN="hf_your_token_here"export AZURE_API_KEY="your_azure_api_key_here"# Windows (PowerShell)$env:HF_TOKEN = "hf_your_token_here"$env:AZURE_API_KEY = "your_azure_api_key_here"
# Run the applicationpython app.py5 unmodified lines### Deploy to Hugging Face Spaces
1. Create a new Space on huggingface.co (select Gradio SDK)2. Add `HF_TOKEN` as a Space Secret (Settings β Secrets)2. Add `AZURE_API_KEY` as a Space Secret (Settings β Secrets)3. Push this code to the Space repository4. The Space automatically installs dependencies and starts the app
18 unmodified lines
## Adding Binary Files to the HF Space
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 at `/data`. The `hf sync` command keeps your local folder in sync with the bucket.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.
> **Note:** Git LFS is not supported for Hugging Face Spaces persistent storage. Use the bucket + `hf sync` workflow described here instead.
### The `/data` Shared Folder
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.
| Path in container | Purpose ||---|---|| `/data/chroma_db/` | ChromaDB vector store (survives Space restarts) || `/data/sample_documents/` | Text/PDF files auto-ingested on startup || `/data/DataSet/` | Training and evaluation datasets |
**Default bucket naming convention:** A Space at `https://huggingface.co/spaces/<org>/<space-name>` gets a default storage bucket at `https://huggingface.co/buckets/<org>/<space-name>-storage`
For this project:- Space: `https://huggingface.co/spaces/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026`- Bucket: `https://huggingface.co/buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage`
The `hf://` URI for use with the CLI is: `hf://buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage`
### Prerequisites
```bash13 unmodified lines3. Under **"Attach storage"**, select the existing bucket **`millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage`** (or create a new one)4. Save β Hugging Face will mount the bucket at `/data` inside the Space container
### Step 2 β Upload Files from Your Local Machine### Step 2 β Sync Your Local `./data` with the Space Bucket
Place all persistent files under a local `./data` folder. The expected structure is:
```./data/βββ chroma_db/ # Pre-built ChromaDB vector storeβββ chroma_db/ # Binary files and ChromaDB vector storeβ βββ chroma.sqlite3βββ sample_documents/ # Text/PDF files ingested on startupβ βββ eiffel_tower.txtβ βββ gustave_eiffel.txtβββ DataSet/ # Training/test datasets (PDFs, CSVs, etc.) βββ Automobile/ βββ Climatique/./train_data/ # Training/test datasets (PDFs, CSVs, etc.) βββ Automobile - Train/ βββ Climatique-Train/ βββ ...```
Then push:
**Upload (local β bucket):**```bash# Sync the entire ./data folder to the buckethf sync ./data hf://buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage# Mirror ./data to the bucket β removes remote files deleted locallyhf sync ./data hf://buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage --delete
# Sync only a specific sub-folder (e.g., the vector store)hf sync ./data/chroma_db hf://buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage/chroma_db3 unmodified lines --include "*.pdf" --include "*.sqlite3"```
> **`--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`.
`hf sync` is **incremental** β it computes checksums and only uploads files that have changed.`hf sync` is **incremental** β it computes checksums and only transfers files that have changed.
### Step 3 β Download the Bucket to Another Machine
3 unmodified lineshf sync hf://buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage ./data```
### Step 4 β Sync Hackathon Training Data
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):
```bash# Download all training data locallyhf sync hf://buckets/millimanfrance/Hackathon2026TrainData ./train_data
# Download only a specific categoryhf sync hf://buckets/millimanfrance/Hackathon2026TrainData/Automobile ./train_data/Automobile```
> **Note:** `Hackathon2026TrainData` is a shared read-only bucket. Do not attempt to push to it.
To make this data available inside your Space, push it to your Space's own bucket under a `train_data/` sub-folder:
```bashhf sync ./train_data hf://buckets/millimanfrance/Example-App-Hackathon-Gustave-Eiffel-2026-storage/train_data```
It will then be accessible inside the container at `/data/train_data/`.
### Accessing Files in the Space Application
Once the bucket is mounted, files appear under `/data` inside the Space container regardless of their path in the bucket.Once the bucket is mounted, files appear under `/data` inside the Space container.
The application resolves this automatically via a single `DATA_DIR` constant in `app.py`:The application resolves the data root automatically via a single `DATA_DIR` constant in `app.py`:
```pythonfrom pathlib import Path25 unmodified lines
## Configuration
### Step 1 β Edit `config.json`
Open [`config.json`](config.json) at the project root and replace the placeholders with your Azure OpenAI resource details:
```json{ "embedding": { "endpoint_url": "https://<your-resource>.openai.azure.com/openai/deployments/<your-embedding-deployment>/embeddings?api-version=2024-12-01-preview", "model": "text-embedding-3-small" }, "llm": { "endpoint_url": "https://<your-resource>.openai.azure.com/openai/deployments/<your-deployment>/chat/completions?api-version=2024-12-01-preview", "model": "gpt-5", "max_tokens": 512, "temperature": 0.7, "top_p": 0.95 }}```
| Field | What to put ||---|---|| `<your-resource>` | Your Azure OpenAI resource name (from the Azure Portal) || `<your-embedding-deployment>` | The deployment name for your embedding model || `<your-deployment>` | The deployment name for your LLM || `model` | Must match the model name used when creating the deployment |
> **Note:** The `endpoint_url` for embeddings ends in `/embeddings` and the one for the LLM ends in `/chat/completions`. Keep those suffixes intact.
### Step 2 β Set the API Key
The API key is **not** stored in `config.json`. Set it as an environment variable:
```bash# macOS / Linuxexport AZURE_API_KEY="your_azure_api_key_here"
# Windows (PowerShell)$env:AZURE_API_KEY = "your_azure_api_key_here"```
When deploying to Hugging Face Spaces, add it as a **Space Secret** (Settings β Secrets β New secret β name it `AZURE_API_KEY`).
### Tunable Parameters
The following constants in `app.py` can also be adjusted directly:
| Variable | Default | Description ||---|---|---|| `HF_TOKEN` | (Space Secret) | Hugging Face API token for Inference API || `EMBEDDING_MODEL_NAME` | `sentence-transformers/all-MiniLM-L6-v2` | Model for text embeddings || `LLM_MODEL_NAME` | `Qwen/Qwen2.5-72B-Instruct` | LLM for answer generation || `AZURE_API_KEY` | (env var / Space Secret) | Azure OpenAI API key (shared by LLM and embedding endpoints) || `EMBEDDING_MODEL_NAME` | `text-embedding-3-small` | Azure OpenAI embedding model || `LLM_MODEL_NAME` | `gpt-5` | Azure OpenAI LLM for answer generation || `LLM_MAX_TOKENS` | `512` | Maximum tokens in the LLM response || `LLM_TEMPERATURE` | `0.7` | Sampling temperature for the LLM || `LLM_TOP_P` | `0.95` | Top-p (nucleus) sampling for the LLM || `DATA_DIR` | `/data` (HF Spaces) or `./data` (local) | Root directory for all persistent data || `CHROMA_PERSIST_DIR` | `DATA_DIR/chroma_db` | ChromaDB storage path || `SAMPLE_DOCS_DIR` | `DATA_DIR/sample_documents` | Documents ingested on startup |20 unmodified lines- Uses **HNSW index** for fast approximate nearest neighbor search- Zero configuration required
### Why Sentence Transformers?### Why Azure OpenAI Embeddings?
- Runs **locally** within the Space (no API cost for embeddings)- `all-MiniLM-L6-v2` is small (~80MB) but effective- Produces **384-dimensional** vectors (good balance of quality vs. storage)- Trained on 1B+ sentence pairs for semantic similarity- **High-quality embeddings** β `text-embedding-3-small` produces state-of-the-art embeddings with excellent semantic understanding- **No local model loading** β Eliminates GPU/memory requirements on the Space- **Scalable** β Handles large batch embedding requests via the API- **Consistent** β Same model used across environments (dev, staging, production)
### Evaluation Integration
10 unmodified lines
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`.
### LLM 404 β Model Not Found### LLM / Embedding API Errors
If the `/query` endpoint logs a `503 Service Unavailable` or `401 Unauthorized`:
If the `/query` endpoint logs a `404 Not Found` for the Inference API URL, the configured model has been removed from the free serverless tier. Update `LLM_MODEL_NAME` in `app.py` to an available model. The app now uses `chat_completion` (`/v1/chat/completions`) rather than the legacy `text_generation` endpoint, so any model listed under **Inference Providers** on huggingface.co will work. The prompt in `prompts/rag_prompt.txt` is model-agnostic (no special tokens).1. Verify `AZURE_API_KEY` is set correctly as an environment variable or Space Secret2. Check that the endpoint URLs in `config.json` match your Azure OpenAI deployment3. Ensure your Azure OpenAI deployment is active and the model name matches the deployment name4. The app calls the Azure OpenAI-compatible `chat/completions` and `embeddings` endpoints directly via REST
### SSL Certificate Verification Error
18 unmodified lines$env:REQUESTS_CA_BUNDLE = "C:\path\to\corporate-ca.crt"```
Set the variable **before** running `python app.py`. Both `huggingface_hub` and `sentence-transformers` use the `requests` library, which reads `REQUESTS_CA_BUNDLE` automatically β no code change is needed.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.
> **How to export your corporate CA certificate:**> 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.README.md+155-52