Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
.git
.env
.env.*
!.env.example
.venv
venv
**/__pycache__
*.pyc
.pytest_cache
.ruff_cache
chroma_db
chroma_db.before-*
work/chroma_notes
16 changes: 7 additions & 9 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
# Create a Hugging Face token with the permission:
# "Make calls to Inference Providers"
HF_TOKEN=hf_your_token_here

# Embedding model for turning notes and questions into vectors.
# Public embedding model downloaded once, then run locally on CPU.
HF_EMBED_MODEL=sentence-transformers/all-MiniLM-L6-v2

# Chat model used for the final answer.
HF_LLM_MODEL=Qwen/Qwen3-4B-Instruct-2507
# Groq key for question rewriting and answer generation.
GROQ_API_KEY=your_groq_key_here

# Hugging Face inference provider.
HF_PROVIDER=nscale
# Chat model that supports reasoning_effort="none".
# Use a Groq free-plan account for free usage; account limits apply.
GROQ_MODEL=qwen/qwen3.8-27b

# Local folder used for notes.
NOTES_DIR=notes
Expand All @@ -19,6 +16,7 @@ NOTES_DIR=notes
# - ./chroma_db locally
# - /data/chroma_db in Hugging Face Spaces when a Storage Bucket is mounted at /data.
CHROMA_DIR=./chroma_db
# Use an unused collection name when migrating to local embeddings.
CHROMA_COLLECTION=notes

# Public GitHub repo contents endpoint used by `sync-notes`.
Expand Down
51 changes: 40 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ It combines semantic search with an LLM to retrieve relevant information, genera
## Key Features

- **Conversational retrieval:** Rewrites follow-up questions into standalone search queries using conversation history.
- **Semantic search:** Uses Hugging Face embeddings and Chroma for similarity-based retrieval.
- **Semantic search:** Runs Sentence Transformers embeddings locally on CPU and stores vectors in Chroma.
- **Document indexing:** Splits documents into overlapping chunks with source metadata.
- **Grounded generation:** Instructs the LLM to answer using retrieved context and acknowledge missing information.
- **Source inspection:** Displays retrieved passages, filenames, chunk IDs, and retrieval queries.
Expand All @@ -25,11 +25,11 @@ The current flow is:

1. Sync markdown notes from `github.com/ditek/Notes` (can be changed in the `.env` file) or use local files in `notes/`.
2. Split notes into chunks with LangChain's text splitter.
3. Embed chunks with `all-MiniLM-L6-v2`.
3. Embed chunks locally on CPU with `sentence-transformers/all-MiniLM-L6-v2`.
4. Store vectors in Chroma.
5. Retrieve relevant chunks for each question with top-k similarity retrieval.
6. Rewrite follow-up questions using chat history.
7. Generate answer with an appropriate LLM (currently using Qwen3-4B).
5. Rewrite follow-up questions using chat history.
6. Retrieve relevant chunks with top-k similarity retrieval.
7. Generate an answer through Groq (default: `qwen/qwen3.8-27b`).

## Setup
After cloning, run these commands.
Expand All @@ -40,10 +40,11 @@ uv run pre-commit install
cp .env.example .env
```

Edit `.env` and set a Hugging Face token with at least this permission:
Edit `.env` and set your Groq API key and chat model:

```text
Make calls to Inference Providers
GROQ_API_KEY=your_groq_key_here
GROQ_MODEL=qwen/qwen3.8-27b
```

## Usage
Expand All @@ -61,12 +62,17 @@ Download and rebuild the vector index:
uv run main.py sync-notes --index
```

`sync-notes --index` replaces vectors in the selected Chroma collection. Back up an existing index before rebuilding it.

You can also index whatever markdown files are already in `notes/`:

```bash
uv run main.py index --reset
uv run main.py index
```

Indexing without `--reset` appends chunks. Use `--reset` for a full rebuild after
backing up the index.

### Ask From The CLI

```bash
Expand All @@ -87,6 +93,9 @@ The app includes:
- a `k` slider for retrieved chunks
- buttons to sync notes, rebuild the index, reload the index, and clear chat

Sidebar controls appear when `ENABLE_SIDEBAR_CONTROLS=true`. The **Rebuild index**
button replaces vectors in the selected collection, so back up existing data first.

### Run The FastAPI App

```bash
Expand Down Expand Up @@ -124,8 +133,12 @@ Available admin endpoints:

### Environment Variables

- Set `HF_TOKEN` to allow communication with Hugging Face. Only `Make calls to Inference Providers` permission is needed for that.
- Set `GROQ_API_KEY` for question rewriting and answer generation. Indexing does not require it.
- Set `GROQ_MODEL` to select the chat model (default: `qwen/qwen3.8-27b`).
- Set `HF_EMBED_MODEL` to select the local CPU embedding model (default: `sentence-transformers/all-MiniLM-L6-v2`).
- Set `HF_HOME` if you need a different writable model cache location.
- Set `CHROMA_DIR=./chroma_db` for local development.
- Set `CHROMA_COLLECTION` to select the collection to build and query (default: `notes`).
- Set `API_ALLOWED_ORIGINS` to a comma-separated list of browser origins allowed to call the FastAPI app. It defaults to `*`.
- Set `API_ADMIN_TOKEN` only if you want to enable protected sync/index endpoints.
- Keep `ENABLE_SIDEBAR_CONTROLS=false` to hide the sidebar in public embeds.
Expand All @@ -135,8 +148,24 @@ Available admin endpoints:

Deployment-specific files live under `deploy/`.

For deploying to Hugging Face Spaces, see:
On Hugging Face Spaces, keep the Docker SDK and select CPU Basic hardware. Set
`GROQ_API_KEY` as a **Space secret**, and `GROQ_MODEL`, `HF_EMBED_MODEL`,
and `CHROMA_COLLECTION` as **Space variables**. Existing HF Git credentials or
`HF_DEPLOY_TOKEN` are still used separately for deployment.
Switching the chat provider does not require rebuilding the Chroma index.

The Docker image caches the default MiniLM model during build. Its default notes,
Chroma, and model-cache directories are writable. Set `CHROMA_DIR=/data/chroma_db`
only when writable persistent storage is mounted at `/data`. Without persistent
storage, resync downloaded notes and rebuild the index after container restarts.

See the [Hugging Face deployment guide](deploy/huggingface/README.md) for the deploy commands.

### Tests

```bash
deploy/huggingface/README.md
uv run --locked python -m unittest discover -s tests -v
```

Tests mock model loading and Groq calls, and use temporary Chroma databases.
They require no API keys or model downloads and consume no generation credits.
11 changes: 10 additions & 1 deletion api.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from fastapi import Depends, FastAPI, Header, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field

from rag import (
Expand All @@ -24,6 +25,14 @@ def _allowed_origins():

app = FastAPI(title="Notes Chat API")


@app.exception_handler(RuntimeError)
async def handle_rag_error(request, exc):
return JSONResponse(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE, content={"detail": str(exc)}
)


app.add_middleware(
CORSMiddleware,
allow_origins=_allowed_origins(),
Expand Down Expand Up @@ -69,9 +78,9 @@ class SyncNotesRequest(BaseModel):

@lru_cache(maxsize=1)
def get_rag_resources():
llm = create_llm()
embeddings = create_embeddings()
vector_store = load_vector_store(embeddings)
llm = create_llm()
return vector_store, llm


Expand Down
26 changes: 16 additions & 10 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@
]


@st.cache_resource
@st.cache_resource(show_spinner=False)
def get_rag_resources():
llm = create_llm()
embeddings = create_embeddings()
vector_store = load_vector_store(embeddings)
llm = create_llm()
return vector_store, llm


Expand Down Expand Up @@ -126,14 +126,20 @@ def select_suggested_question(suggested_question):

with st.chat_message("assistant", avatar=AVATARS["assistant"]):
with st.spinner("Finding the answer..."):
vector_store, llm = get_rag_resources()
answer, docs, retrieval_query = answer_question(
question,
vector_store,
llm,
k=k,
chat_history=chat_history,
)
try:
vector_store, llm = get_rag_resources()
answer, docs, retrieval_query = answer_question(
question,
vector_store,
llm,
k=k,
chat_history=chat_history,
)
except RuntimeError as exc:
# Removed failed requests from chat history
st.session_state.messages.pop()
st.error(str(exc))
st.stop()
st.markdown(answer)

with st.expander("Sources"):
Expand Down
27 changes: 24 additions & 3 deletions deploy/huggingface/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,11 +1,32 @@
FROM python:3.10-slim

WORKDIR /app
RUN useradd --create-home --uid 1000 user \
&& mkdir -p /home/user/app \
&& chown user:user /home/user/app

ENV HOME=/home/user \
HF_HOME=/home/user/.cache/huggingface \
HF_HUB_DISABLE_IMPLICIT_TOKEN=1 \
TOKENIZERS_PARALLELISM=false \
OMP_NUM_THREADS=2 \
MKL_NUM_THREADS=2 \
PYTHONUNBUFFERED=1

WORKDIR /home/user/app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Install only Torch from the CPU index; resolve dependencies from PyPI below.
RUN python -m pip install --no-cache-dir --upgrade pip \
&& pip install --no-cache-dir --no-deps 'torch>=2.2' --index-url https://download.pytorch.org/whl/cpu \
&& pip install --no-cache-dir -r requirements.txt

USER user

# Cache the public default model during build to reduce startup latency.
RUN python -c "from langchain_huggingface import HuggingFaceEmbeddings; HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L6-v2', model_kwargs={'device': 'cpu'})"

COPY . .
COPY --chown=user:user . .
RUN mkdir -p notes chroma_db

EXPOSE 8501

Expand Down
6 changes: 5 additions & 1 deletion deploy/huggingface/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ When `HF_SPACE_REMOTE_URL` is set, the deploy script automatically uses this env

## Space Setup

Set `GROQ_API_KEY` as a **Space secret** and `GROQ_MODEL=qwen/qwen3.8-27b` as a
**Space variable**.

The Space should use persistent storage for Chroma. Mount a Storage Bucket at:

```text
Expand All @@ -54,7 +57,8 @@ CHROMA_DIR=/data/chroma_db

## Deploy

From the repo root:
Commit the reviewed changes first; deployment exports the current commit and
does not include uncommitted edits. From the repo root:

```bash
python deploy/huggingface/deploy.py
Expand Down
20 changes: 19 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,19 @@ requires-python = ">=3.10"
dependencies = [
"chromadb>=0.5",
"fastapi>=0.115",
"huggingface-hub>=0.27",
"langchain>=0.3",
"langchain-chroma>=0.2",
"langchain-huggingface>=0.2",
"langchain-text-splitters>=0.3",
"openai>=1.0",
"python-dotenv>=1.0",
"requests>=2.32",
"sentence-transformers>=3.0",
# Compatibility with the final Intel macOS PyTorch wheel.
"sentence-transformers<4; sys_platform == 'darwin' and platform_machine == 'x86_64'",
"transformers<4.50; sys_platform == 'darwin' and platform_machine == 'x86_64'",
"numpy<2; sys_platform == 'darwin' and platform_machine == 'x86_64'",
"torch>=2.2",
"streamlit>=1.64.0",
"uvicorn[standard]>=0.30",
]
Expand All @@ -35,3 +41,15 @@ extend-exclude = ["*.ipynb"]
[tool.ruff.lint]
select = ["E4", "E7", "E9", "F", "I"]

[tool.uv]
required-environments = ["sys_platform == 'darwin' and platform_machine == 'x86_64' and python_version == '3.10'"]

# Linux deployments install CPU wheels without CUDA libraries.
[tool.uv.sources]
torch = [{ index = "pytorch-cpu", marker = "sys_platform == 'linux'" }]

[[tool.uv.index]]
name = "pytorch-cpu"
url = "https://download.pytorch.org/whl/cpu"
explicit = true

Loading
Loading