A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.
audit: fix hyde_rag - add env comment, fix model contradiction, fix pip install, rewrite em dashes, add docstrings
Tiioluwanib089ee871800
diff --git a/rag_apps/hyde_rag/.env.example b/rag_apps/hyde_rag/.env.exampleindex 39bb49f..2348918 100644--- a/rag_apps/hyde_rag/.env.example+++ b/rag_apps/hyde_rag/.env.example@@ -1 +1,3 @@+# Google API key used to authenticate Gemini 3 Flash and Gemini Embedding 2 requests.+# Get one free at https://aistudio.google.comGOOGLE_API_KEY=your_google_api_key_herediff --git a/rag_apps/hyde_rag/README.md b/rag_apps/hyde_rag/README.mdindex f51ad06..efda45f 100644--- a/rag_apps/hyde_rag/README.md+++ b/rag_apps/hyde_rag/README.md@@ -7,7 +7,7 @@Standard RAG embeds the user's raw query and uses it to search the vector store. The problem: a short question and a long detailed answer live in very different regions of the embedding space, so the nearest-neighbour search often misses the most relevant chunks.-HyDE solves this by flipping the retrieval signal. Instead of embedding the query, the system prompts an LLM to generate N hypothetical answers — documents that *would* contain the answer. Each is embedded, the resulting vectors are averaged into a single HyDE embedding, and that richer signal is used to retrieve from the vector store. Hypothetical answers sit much closer to real answers in embedding space than the original query does.+HyDE solves this by flipping the retrieval signal. Instead of embedding the query, the system prompts an LLM to generate N hypothetical answers, documents that *would* contain the answer. Each is embedded, the resulting vectors are averaged into a single HyDE embedding, and that richer signal is used to retrieve from the vector store. Hypothetical answers sit much closer to real answers in embedding space than the original query does.## Demo@@ -15,9 +15,9 @@ HyDE solves this by flipping the retrieval signal. Instead of embedding the quer## Features-- **Hypothetical Document Generation:** MiniMax M2.5 generates N configurable hypothetical answer documents per query+- **Hypothetical Document Generation:** Gemini 3 Flash generates N configurable hypothetical answer documents per query- **HyDE Averaging:** Gemini Embedding 2 embeds each hypothetical doc; vectors are averaged with NumPy into a single retrieval signal-- **ChromaDB Vector Store:** Lightweight, in-process vector store — no external service required+- **ChromaDB Vector Store:** Lightweight, in-process vector store that requires no external service- **Transparent Intermediate Steps:** The UI surfaces the hypothetical documents and retrieved chunks so you can see exactly how retrieval worked- **Configurable Retrieval:** Sliders for chunk size, chunk overlap, number of hypothetical docs, and number of retrieved chunks- **PDF and TXT support:** LangChain document loaders handle both formats@@ -36,7 +36,7 @@ HyDE solves this by flipping the retrieval signal. Instead of embedding the quer## Prerequisites- Python 3.11 or later-- A Google API key — get one free at [aistudio.google.com](https://aistudio.google.com)+- A Google API key, get one free at [aistudio.google.com](https://aistudio.google.com)## Installation@@ -64,7 +64,7 @@ python -m venv .venv**Install dependencies**```bash-pip install -r pyproject.toml+pip install .```Or with `uv`:@@ -109,7 +109,7 @@ Open `http://127.0.0.1:7860` in your browser.User question│▼-MiniMax M2.5 generates N hypothetical answer documents+Gemini 3 Flash generates N hypothetical answer documents│▼Gemini Embedding 2 embeds each hypothetical document@@ -124,7 +124,7 @@ ChromaDB similarity search with HyDE embeddingTop-K chunks retrieved│▼-MiniMax M2.5 synthesises final answer from retrieved context+Gemini 3 Flash synthesises final answer from retrieved context```## Project Structure@@ -132,11 +132,13 @@ MiniMax M2.5 synthesises final answer from retrieved context```texthyde_rag/├── app.py # Gradio UI-├── rag.py # HyDERAG class — ingest and query pipeline-├── embedder.py # GeminiEmbedder — embedding + HyDE vector averaging+├── rag.py # HyDERAG class, ingest and query pipeline+├── embedder.py # GeminiEmbedder, embedding + HyDE vector averaging├── pyproject.toml # Project dependencies├── .env # Your API keys (git-ignored)├── .env.example # Template for .env└── assets/- └── demo.png+ └── demo.gif```++[Back to top](#hyde-rag)diff --git a/rag_apps/hyde_rag/app.py b/rag_apps/hyde_rag/app.pyindex 84f5903..25e6cc5 100644--- a/rag_apps/hyde_rag/app.py+++ b/rag_apps/hyde_rag/app.py@@ -1,5 +1,5 @@"""-HyDE RAG — Gradio UI+HyDE RAG, Gradio UI"""import os@@ -17,6 +17,7 @@ pipeline: HyDERAG | None = Nonedef get_or_create_pipeline(google_key: str) -> HyDERAG:+ """Return the existing pipeline, creating one with the given key if none exists yet."""global pipelineif pipeline is None:pipeline = HyDERAG(google_api_key=google_key)@@ -26,12 +27,14 @@ def get_or_create_pipeline(google_key: str) -> HyDERAG:# ── Handlers ───────────────────────────────────────────────────────────────────def validate_keys(google_key: str) -> tuple[bool, str]:+ """Check that a Google API key was provided, returning a success flag and error message."""if not google_key.strip():return False, "Google API key is required."return True, ""def ingest_document(file, chunk_size, chunk_overlap, google_key):+ """Validate inputs and run the uploaded file through the ingest pipeline, updating the status panel."""if file is None:return gr.update(value="No file uploaded.", visible=True), gr.update(value=None, visible=False)@@ -54,6 +57,7 @@ def ingest_document(file, chunk_size, chunk_overlap, google_key):def run_query(question, n_hypothetical, n_results, google_key):+ """Validate inputs, run the HyDE query pipeline, and format the hypothetical docs, chunks, and answer for display."""if not question.strip():return "", "", ""@@ -99,6 +103,7 @@ def run_query(question, n_hypothetical, n_results, google_key):def clear_all():+ """Reset the pipeline and clear all UI fields back to their initial state."""global pipelineif pipeline is not None:pipeline.clear()diff --git a/rag_apps/hyde_rag/embedder.py b/rag_apps/hyde_rag/embedder.pyindex a1d1e33..bd6abd5 100644--- a/rag_apps/hyde_rag/embedder.py+++ b/rag_apps/hyde_rag/embedder.py@@ -10,7 +10,7 @@ class GeminiEmbedder:"""Wraps the google-genai SDK to embed text using Gemini Embedding 2.Also provides hyde_embed(), which embeds N hypothetical documents and- returns their averaged vector — the core of the HyDE retrieval strategy.+ returns their averaged vector, the core of the HyDE retrieval strategy."""MODEL = "gemini-embedding-2"diff --git a/rag_apps/hyde_rag/pyproject.toml b/rag_apps/hyde_rag/pyproject.tomlindex 9d0990d..0daaafc 100644--- a/rag_apps/hyde_rag/pyproject.toml+++ b/rag_apps/hyde_rag/pyproject.toml@@ -1,7 +1,7 @@[project]name = "hyde-rag"version = "0.1.0"-description = "HyDE RAG pipeline — Hypothetical Document Embeddings with Gemini 3 Flash and Gemini Embedding 2"+description = "HyDE RAG pipeline using Hypothetical Document Embeddings with Gemini 3 Flash and Gemini Embedding 2"requires-python = ">=3.11"dependencies = [diff --git a/rag_apps/hyde_rag/rag.py b/rag_apps/hyde_rag/rag.pyindex 6223aea..d68c60e 100644--- a/rag_apps/hyde_rag/rag.py+++ b/rag_apps/hyde_rag/rag.py@@ -18,7 +18,7 @@ from langchain_text_splitters import RecursiveCharacterTextSplitterfrom embedder import GeminiEmbedder-# ── Prompts ────────────────────────────────────────────────────────────────────+# PromptsHYPOTHETICAL_PROMPT = """\You are a knowledgeable assistant. A user has asked the following question:@@ -26,7 +26,7 @@ You are a knowledgeable assistant. A user has asked the following question:"{question}"Write a detailed, factual hypothetical document excerpt that directly answers \-this question. Write it as if extracted from a real reference document — \+this question. Write it as if extracted from a real reference document, \specific, informative, and self-contained. Do not explain that it is hypothetical."""@@ -44,7 +44,7 @@ Answer:"""-# ── Pipeline ───────────────────────────────────────────────────────────────────+# Pipelineclass HyDERAG:"""End-to-end HyDE retrieval-augmented generation pipeline."""@@ -59,7 +59,7 @@ class HyDERAG:self._collection = self._chroma.get_or_create_collection(self.COLLECTION)self.doc_info: dict | None = None- # ── Ingest ──────────────────────────────────────────────────────────────+ # Ingestdef ingest(self,@@ -121,7 +121,7 @@ class HyDERAG:}return self.doc_info- # ── Query ───────────────────────────────────────────────────────────────+ # Querydef _generate_hypothetical_docs(self, question: str, n: int) -> list[str]:"""Use Gemini 3 Flash to generate N hypothetical answer documents."""@@ -154,13 +154,13 @@ class HyDERAG:n_results = min(n_results, self._collection.count())- # Step 1 — generate hypothetical documents+ # Step 1: generate hypothetical documentshypo_docs = self._generate_hypothetical_docs(question, n_hypothetical)- # Step 2 — HyDE embedding (average of hypothetical doc embeddings)+ # Step 2: HyDE embedding (average of hypothetical doc embeddings)hyde_vector = self.embedder.hyde_embed(hypo_docs)- # Step 3 — retrieve from ChromaDB using the HyDE vector+ # Step 3: retrieve from ChromaDB using the HyDE vectorresults = self._collection.query(query_embeddings=[hyde_vector],n_results=n_results,@@ -168,7 +168,7 @@ class HyDERAG:retrieved_texts = results["documents"][0]retrieved_meta = results["metadatas"][0]- # Step 4 — generate final answer+ # Step 4: generate final answercontext = "\n\n---\n\n".join(retrieved_texts)response = self.client.models.generate_content(model=self.MODEL_ID,