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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"id": "12a9fcb2",
|
| 6 |
+
"metadata": {},
|
| 7 |
+
"source": [
|
| 8 |
+
"### Step 1: Load 2 text PDFs"
|
| 9 |
+
]
|
| 10 |
+
},
|
| 11 |
+
{
|
| 12 |
+
"cell_type": "code",
|
| 13 |
+
"execution_count": 91,
|
| 14 |
+
"id": "e322de88",
|
| 15 |
+
"metadata": {},
|
| 16 |
+
"outputs": [
|
| 17 |
+
{
|
| 18 |
+
"name": "stdout",
|
| 19 |
+
"output_type": "stream",
|
| 20 |
+
"text": [
|
| 21 |
+
"Note: you may need to restart the kernel to use updated packages.\n"
|
| 22 |
+
]
|
| 23 |
+
}
|
| 24 |
+
],
|
| 25 |
+
"source": [
|
| 26 |
+
"# Step 0 (Setup): Install required packages (run once per environment)\n",
|
| 27 |
+
"%pip install -q langchain langchain-classic langchain-community langchain-openai langchain-text-splitters langchain-huggingface langchain-chroma chromadb sentence-transformers python-dotenv rank-bm25 gradio pypdf"
|
| 28 |
+
]
|
| 29 |
+
},
|
| 30 |
+
{
|
| 31 |
+
"cell_type": "code",
|
| 32 |
+
"execution_count": 92,
|
| 33 |
+
"id": "24647d78",
|
| 34 |
+
"metadata": {},
|
| 35 |
+
"outputs": [
|
| 36 |
+
{
|
| 37 |
+
"name": "stdout",
|
| 38 |
+
"output_type": "stream",
|
| 39 |
+
"text": [
|
| 40 |
+
"Number of documents loaded: 1201\n",
|
| 41 |
+
"\n",
|
| 42 |
+
"Sample of first document content:\n",
|
| 43 |
+
"\n",
|
| 44 |
+
"Chip Huyen\n",
|
| 45 |
+
" AI Engineering\n",
|
| 46 |
+
"Building Applications \n",
|
| 47 |
+
"with Foundation Models\n"
|
| 48 |
+
]
|
| 49 |
+
}
|
| 50 |
+
],
|
| 51 |
+
"source": [
|
| 52 |
+
"# Step 1 (Load): Load two text-based PDFs into LangChain Documents\n",
|
| 53 |
+
"\n",
|
| 54 |
+
"from langchain_community.document_loaders import PyPDFLoader\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"# Define the PDF file paths (assumed to be in the current working directory)\n",
|
| 57 |
+
"pdf_paths = [\"textbook_1.pdf\", \"textbook_2.pdf\"]\n",
|
| 58 |
+
"\n",
|
| 59 |
+
"# Load each PDF into a list of Document objects (typically one Document per page)\n",
|
| 60 |
+
"all_documents = []\n",
|
| 61 |
+
"for path in pdf_paths:\n",
|
| 62 |
+
" loader = PyPDFLoader(path)\n",
|
| 63 |
+
" docs = loader.load()\n",
|
| 64 |
+
" all_documents.extend(docs)\n",
|
| 65 |
+
"\n",
|
| 66 |
+
"# Print assignment-required outputs\n",
|
| 67 |
+
"print(f\"Number of documents loaded: {len(all_documents)}\")\n",
|
| 68 |
+
"\n",
|
| 69 |
+
"# Print a sample from the first loaded document (first 700 characters)\n",
|
| 70 |
+
"if all_documents:\n",
|
| 71 |
+
" sample_text = all_documents[0].page_content[:700]\n",
|
| 72 |
+
" print(\"\\nSample of first document content:\\n\")\n",
|
| 73 |
+
" print(sample_text)\n",
|
| 74 |
+
"else:\n",
|
| 75 |
+
" print(\"\\nNo documents were loaded.\")"
|
| 76 |
+
]
|
| 77 |
+
},
|
| 78 |
+
{
|
| 79 |
+
"cell_type": "code",
|
| 80 |
+
"execution_count": 93,
|
| 81 |
+
"id": "490ed688",
|
| 82 |
+
"metadata": {},
|
| 83 |
+
"outputs": [
|
| 84 |
+
{
|
| 85 |
+
"name": "stdout",
|
| 86 |
+
"output_type": "stream",
|
| 87 |
+
"text": [
|
| 88 |
+
"Configuration: chunk_size=500, chunk_overlap=100\n",
|
| 89 |
+
"Total number of chunks created: 4979\n",
|
| 90 |
+
"Character count of the smallest chunk: 2\n",
|
| 91 |
+
"Character count of the largest chunk: 500\n",
|
| 92 |
+
"Sample metadata from first chunk: {'source': 'textbook_1.pdf', 'date': '2023-01-01', 'section': 'pages_1_20'}\n",
|
| 93 |
+
"------------------------------------------------------------\n",
|
| 94 |
+
"Configuration: chunk_size=1000, chunk_overlap=150\n",
|
| 95 |
+
"Total number of chunks created: 2571\n",
|
| 96 |
+
"Character count of the smallest chunk: 2\n",
|
| 97 |
+
"Character count of the largest chunk: 1000\n",
|
| 98 |
+
"Sample metadata from first chunk: {'source': 'textbook_1.pdf', 'date': '2023-01-01', 'section': 'pages_1_20'}\n",
|
| 99 |
+
"------------------------------------------------------------\n"
|
| 100 |
+
]
|
| 101 |
+
}
|
| 102 |
+
],
|
| 103 |
+
"source": [
|
| 104 |
+
"# Step 2 (Chunk): Split loaded documents into chunks with two configurations + metadata\n",
|
| 105 |
+
"import os\n",
|
| 106 |
+
"from langchain_text_splitters import RecursiveCharacterTextSplitter\n",
|
| 107 |
+
"\n",
|
| 108 |
+
"# Prefer the full Step 1 output, but support `docs` if that's your loaded list name\n",
|
| 109 |
+
"if \"all_documents\" in globals() and all_documents:\n",
|
| 110 |
+
" source_docs = all_documents\n",
|
| 111 |
+
"elif \"docs\" in globals() and docs:\n",
|
| 112 |
+
" source_docs = docs\n",
|
| 113 |
+
"else:\n",
|
| 114 |
+
" source_docs = []\n",
|
| 115 |
+
"\n",
|
| 116 |
+
"# Map each textbook to a date tag (adjust these to your real document dates if available)\n",
|
| 117 |
+
"source_date_map = {\n",
|
| 118 |
+
" \"textbook_1.pdf\": \"2023-01-01\",\n",
|
| 119 |
+
" \"textbook_2.pdf\": \"2024-01-01\",\n",
|
| 120 |
+
"}\n",
|
| 121 |
+
"\n",
|
| 122 |
+
"# Add metadata fields requested for filtered retrieval\n",
|
| 123 |
+
"# - source: source file name\n",
|
| 124 |
+
"# - date: date tag per source document\n",
|
| 125 |
+
"# - section: derived from page number bucket (chapter/section proxy)\n",
|
| 126 |
+
"def enrich_chunk_metadata(chunks):\n",
|
| 127 |
+
" for chunk in chunks:\n",
|
| 128 |
+
" src_path = chunk.metadata.get(\"source\", \"\")\n",
|
| 129 |
+
" source_file = os.path.basename(src_path) if src_path else \"unknown_source\"\n",
|
| 130 |
+
" page_num = int(chunk.metadata.get(\"page\", -1)) + 1\n",
|
| 131 |
+
"\n",
|
| 132 |
+
" if page_num <= 0:\n",
|
| 133 |
+
" section = \"unknown_section\"\n",
|
| 134 |
+
" else:\n",
|
| 135 |
+
" section_start = ((page_num - 1) // 20) * 20 + 1\n",
|
| 136 |
+
" section_end = section_start + 19\n",
|
| 137 |
+
" section = f\"pages_{section_start}_{section_end}\"\n",
|
| 138 |
+
"\n",
|
| 139 |
+
" chunk.metadata[\"source\"] = source_file\n",
|
| 140 |
+
" chunk.metadata[\"date\"] = source_date_map.get(source_file, \"unknown_date\")\n",
|
| 141 |
+
" chunk.metadata[\"section\"] = section\n",
|
| 142 |
+
" return chunks\n",
|
| 143 |
+
"\n",
|
| 144 |
+
"# Helper to split documents and print assignment-required chunk statistics\n",
|
| 145 |
+
"def chunk_and_report(documents, chunk_size, chunk_overlap):\n",
|
| 146 |
+
" splitter = RecursiveCharacterTextSplitter(\n",
|
| 147 |
+
" chunk_size=chunk_size,\n",
|
| 148 |
+
" chunk_overlap=chunk_overlap,\n",
|
| 149 |
+
" )\n",
|
| 150 |
+
" chunks = splitter.split_documents(documents)\n",
|
| 151 |
+
" chunks = enrich_chunk_metadata(chunks)\n",
|
| 152 |
+
"\n",
|
| 153 |
+
" chunk_lengths = [len(chunk.page_content) for chunk in chunks]\n",
|
| 154 |
+
" min_len = min(chunk_lengths) if chunk_lengths else 0\n",
|
| 155 |
+
" max_len = max(chunk_lengths) if chunk_lengths else 0\n",
|
| 156 |
+
"\n",
|
| 157 |
+
" print(f\"Configuration: chunk_size={chunk_size}, chunk_overlap={chunk_overlap}\")\n",
|
| 158 |
+
" print(f\"Total number of chunks created: {len(chunks)}\")\n",
|
| 159 |
+
" print(f\"Character count of the smallest chunk: {min_len}\")\n",
|
| 160 |
+
" print(f\"Character count of the largest chunk: {max_len}\")\n",
|
| 161 |
+
"\n",
|
| 162 |
+
" if chunks:\n",
|
| 163 |
+
" sample_meta = {k: chunks[0].metadata.get(k) for k in [\"source\", \"date\", \"section\"]}\n",
|
| 164 |
+
" print(f\"Sample metadata from first chunk: {sample_meta}\")\n",
|
| 165 |
+
"\n",
|
| 166 |
+
" print(\"-\" * 60)\n",
|
| 167 |
+
" return chunks\n",
|
| 168 |
+
"\n",
|
| 169 |
+
"# First required configuration\n",
|
| 170 |
+
"chunks_500_100 = chunk_and_report(source_docs, chunk_size=500, chunk_overlap=100)\n",
|
| 171 |
+
"\n",
|
| 172 |
+
"# Second required configuration\n",
|
| 173 |
+
"chunks_1000_150 = chunk_and_report(source_docs, chunk_size=1000, chunk_overlap=150)"
|
| 174 |
+
]
|
| 175 |
+
},
|
| 176 |
+
{
|
| 177 |
+
"cell_type": "code",
|
| 178 |
+
"execution_count": 94,
|
| 179 |
+
"id": "bdc95c2f",
|
| 180 |
+
"metadata": {},
|
| 181 |
+
"outputs": [
|
| 182 |
+
{
|
| 183 |
+
"name": "stdout",
|
| 184 |
+
"output_type": "stream",
|
| 185 |
+
"text": [
|
| 186 |
+
"Loading weights: 100%|██████████| 103/103 [00:00<00:00, 6986.89it/s]\n",
|
| 187 |
+
"\u001b[1mBertModel LOAD REPORT\u001b[0m from: sentence-transformers/all-MiniLM-L6-v2\n",
|
| 188 |
+
"Key | Status | | \n",
|
| 189 |
+
"------------------------+------------+--+-\n",
|
| 190 |
+
"embeddings.position_ids | UNEXPECTED | | \n",
|
| 191 |
+
"\n",
|
| 192 |
+
"Notes:\n",
|
| 193 |
+
"- UNEXPECTED:\tcan be ignored when loading from different task/architecture; not ok if you expect identical arch.\n"
|
| 194 |
+
]
|
| 195 |
+
},
|
| 196 |
+
{
|
| 197 |
+
"name": "stdout",
|
| 198 |
+
"output_type": "stream",
|
| 199 |
+
"text": [
|
| 200 |
+
"Number of vectors stored: 4979\n",
|
| 201 |
+
"Sample embedding shape: 384\n"
|
| 202 |
+
]
|
| 203 |
+
}
|
| 204 |
+
],
|
| 205 |
+
"source": [
|
| 206 |
+
"# Step 3 (Embed + Store): Embed 500-size chunks and persist them in ChromaDB\n",
|
| 207 |
+
"import os\n",
|
| 208 |
+
"from langchain_community.embeddings import HuggingFaceEmbeddings\n",
|
| 209 |
+
"from langchain_community.vectorstores import Chroma\n",
|
| 210 |
+
"\n",
|
| 211 |
+
"# Use the smaller chunk set from Step 2\n",
|
| 212 |
+
"if \"chunks_500_100\" not in globals() or not chunks_500_100:\n",
|
| 213 |
+
" raise ValueError(\"`chunks_500_100` is missing. Run Step 2 first.\")\n",
|
| 214 |
+
"\n",
|
| 215 |
+
"# Initialize embedding model\n",
|
| 216 |
+
"embedding_model = HuggingFaceEmbeddings(\n",
|
| 217 |
+
" model_name=\"sentence-transformers/all-MiniLM-L6-v2\"\n",
|
| 218 |
+
")\n",
|
| 219 |
+
"\n",
|
| 220 |
+
"# Create persistent ChromaDB directory\n",
|
| 221 |
+
"persist_dir = \"./chroma_db\"\n",
|
| 222 |
+
"os.makedirs(persist_dir, exist_ok=True)\n",
|
| 223 |
+
"\n",
|
| 224 |
+
"# Recreate the collection each run to avoid duplicate vectors from repeated executions\n",
|
| 225 |
+
"try:\n",
|
| 226 |
+
" existing_store = Chroma(\n",
|
| 227 |
+
" collection_name=\"textbook_rag\",\n",
|
| 228 |
+
" embedding_function=embedding_model,\n",
|
| 229 |
+
" persist_directory=persist_dir,\n",
|
| 230 |
+
" )\n",
|
| 231 |
+
" existing_store.delete_collection()\n",
|
| 232 |
+
"except Exception:\n",
|
| 233 |
+
" pass\n",
|
| 234 |
+
"\n",
|
| 235 |
+
"vectorstore = Chroma.from_documents(\n",
|
| 236 |
+
" documents=chunks_500_100,\n",
|
| 237 |
+
" embedding=embedding_model,\n",
|
| 238 |
+
" collection_name=\"textbook_rag\",\n",
|
| 239 |
+
" persist_directory=persist_dir,\n",
|
| 240 |
+
")\n",
|
| 241 |
+
"\n",
|
| 242 |
+
"# Print assignment-required stats\n",
|
| 243 |
+
"num_vectors = vectorstore._collection.count()\n",
|
| 244 |
+
"sample_embedding = embedding_model.embed_query(\"sample text\")\n",
|
| 245 |
+
"\n",
|
| 246 |
+
"print(f\"Number of vectors stored: {num_vectors}\")\n",
|
| 247 |
+
"print(f\"Sample embedding shape: {len(sample_embedding)}\")"
|
| 248 |
+
]
|
| 249 |
+
},
|
| 250 |
+
{
|
| 251 |
+
"cell_type": "code",
|
| 252 |
+
"execution_count": 95,
|
| 253 |
+
"id": "d659b193",
|
| 254 |
+
"metadata": {},
|
| 255 |
+
"outputs": [
|
| 256 |
+
{
|
| 257 |
+
"name": "stdout",
|
| 258 |
+
"output_type": "stream",
|
| 259 |
+
"text": [
|
| 260 |
+
"Loading weights: 100%|██████████| 103/103 [00:00<00:00, 7916.97it/s]\n",
|
| 261 |
+
"\u001b[1mBertModel LOAD REPORT\u001b[0m from: sentence-transformers/all-MiniLM-L6-v2\n",
|
| 262 |
+
"Key | Status | | \n",
|
| 263 |
+
"------------------------+------------+--+-\n",
|
| 264 |
+
"embeddings.position_ids | UNEXPECTED | | \n",
|
| 265 |
+
"\n",
|
| 266 |
+
"Notes:\n",
|
| 267 |
+
"- UNEXPECTED:\tcan be ignored when loading from different task/architecture; not ok if you expect identical arch.\n"
|
| 268 |
+
]
|
| 269 |
+
},
|
| 270 |
+
{
|
| 271 |
+
"name": "stdout",
|
| 272 |
+
"output_type": "stream",
|
| 273 |
+
"text": [
|
| 274 |
+
"==========================================================================================\n",
|
| 275 |
+
"Query: What is the definition of X?\n",
|
| 276 |
+
"\n",
|
| 277 |
+
"Result 1 (trimmed):\n",
|
| 278 |
+
"3 While I love writing, one of the things I absolutely do not enjoy is trying to condense everyone’s opinions into\n",
|
| 279 |
+
"one single definition. IBM defined data quality along seven dimensions: completeness, uniqueness, validity,\n",
|
| 280 |
+
"timeliness, accuracy, consistency, and fitness for purpose. Wikipedia added a...\n",
|
| 281 |
+
"Relevant: No — because there is no clear keyword overlap with the query.\n",
|
| 282 |
+
"\n",
|
| 283 |
+
"Result 2 (trimmed):\n",
|
| 284 |
+
"Your goal is to predict what someone with 10 years of\n",
|
| 285 |
+
"experience should earn. In this example, x = 10, and you want\n",
|
| 286 |
+
"to predict what y should be.\n",
|
| 287 |
+
"Relevant: No — because there is no clear keyword overlap with the query.\n",
|
| 288 |
+
"\n",
|
| 289 |
+
"Result 3 (trimmed):\n",
|
| 290 |
+
"a 5% chance that the point corresponds to class 1. But if x =\n",
|
| 291 |
+
"10, there is about a 76% chance that it’s class 1. If asked\n",
|
| 292 |
+
"to classify that point as a red or a blue, you would conclude\n",
|
| 293 |
+
"that it’s a red because it’s much more likely to be red\n",
|
| 294 |
+
"than blue.\n",
|
| 295 |
+
"Relevant: No — because there is no clear keyword overlap with the query.\n",
|
| 296 |
+
"==========================================================================================\n",
|
| 297 |
+
"Query: Explain concept Y.\n",
|
| 298 |
+
"\n",
|
| 299 |
+
"Result 1 (trimmed):\n",
|
| 300 |
+
"Another instance of the model (Bob) asks Alice a series of questions to try to identify\n",
|
| 301 |
+
"this concept. Alice can only answer yes or no. The score is based on whether Bob suc‐\n",
|
| 302 |
+
"cessfully guesses the concept, and how many questions it takes for Bob to guess it.\n",
|
| 303 |
+
"Here’s an example of a plausible conversat...\n",
|
| 304 |
+
"Relevant: No — because there is no clear keyword overlap with the query.\n",
|
| 305 |
+
"\n",
|
| 306 |
+
"Result 2 (trimmed):\n",
|
| 307 |
+
"neural network layers to tease more meaning from it before\n",
|
| 308 |
+
"subjecting it to further processing.\n",
|
| 309 |
+
"Relevant: No — because there is no clear keyword overlap with the query.\n",
|
| 310 |
+
"\n",
|
| 311 |
+
"Result 3 (trimmed):\n",
|
| 312 |
+
"finding patterns in numbers and exploiting those patterns to\n",
|
| 313 |
+
"make predictions. ML makes it possible to train a model with\n",
|
| 314 |
+
"rows or sequences of 1s and 0s, and to learn from the data so\n",
|
| 315 |
+
"that, given a new sequence, the model can predict what the\n",
|
| 316 |
+
"result will be. Learning is the process by which ML fin...\n",
|
| 317 |
+
"Relevant: No — because there is no clear keyword overlap with the query.\n",
|
| 318 |
+
"==========================================================================================\n",
|
| 319 |
+
"Query: How does Z work?\n",
|
| 320 |
+
"\n",
|
| 321 |
+
"Result 1 (trimmed):\n",
|
| 322 |
+
"separable in n dimensions. Here’s a quick example.\n",
|
| 323 |
+
"The classes in the two-dimensional dataset on the left in\n",
|
| 324 |
+
"Figure 2-10 can’t be separated with a line. But if you add\n",
|
| 325 |
+
"a third dimension so that points closer to the center have\n",
|
| 326 |
+
"higher z values and points farther from the center have lower\n",
|
| 327 |
+
"z values, a...\n",
|
| 328 |
+
"Relevant: No — because there is no clear keyword overlap with the query.\n",
|
| 329 |
+
"\n",
|
| 330 |
+
"Result 2 (trimmed):\n",
|
| 331 |
+
"Figure 10-9. The yellow arrow allows the generated response to be fed back into the sys‐\n",
|
| 332 |
+
"tem, allowing more complex application patterns.\n",
|
| 333 |
+
"A model’s outputs also can be used to invoke write actions, such as composing an\n",
|
| 334 |
+
"email, placing an order, or initializing a bank transfer. Write actions allow a s...\n",
|
| 335 |
+
"Relevant: No — because there is no clear keyword overlap with the query.\n",
|
| 336 |
+
"\n",
|
| 337 |
+
"Result 3 (trimmed):\n",
|
| 338 |
+
"mechanism. Understanding this mechanism is necessary to understand how trans‐\n",
|
| 339 |
+
"former models work. Under the hood, the attention mechanism leverages key, value,\n",
|
| 340 |
+
"and query vectors:\n",
|
| 341 |
+
"• The query vector (Q) represents the current state of the decoder at each decoding\n",
|
| 342 |
+
"step. Using the same book summary exa...\n",
|
| 343 |
+
"Relevant: No — because there is no clear keyword overlap with the query.\n",
|
| 344 |
+
"\n",
|
| 345 |
+
"Retrieval test complete. (No LLM calls, no RAG chain built.)\n"
|
| 346 |
+
]
|
| 347 |
+
}
|
| 348 |
+
],
|
| 349 |
+
"source": [
|
| 350 |
+
"# Step 4 (Test Retrieval): Query existing ChromaDB before building a RAG chain\n",
|
| 351 |
+
"from langchain_community.embeddings import HuggingFaceEmbeddings\n",
|
| 352 |
+
"from langchain_community.vectorstores import Chroma\n",
|
| 353 |
+
"\n",
|
| 354 |
+
"# Reconnect to the same embedding model and persisted Chroma collection\n",
|
| 355 |
+
"embedding_model = HuggingFaceEmbeddings(\n",
|
| 356 |
+
" model_name=\"sentence-transformers/all-MiniLM-L6-v2\"\n",
|
| 357 |
+
")\n",
|
| 358 |
+
"\n",
|
| 359 |
+
"vectorstore = Chroma(\n",
|
| 360 |
+
" collection_name=\"textbook_rag\",\n",
|
| 361 |
+
" embedding_function=embedding_model,\n",
|
| 362 |
+
" persist_directory=\"./chroma_db\",\n",
|
| 363 |
+
")\n",
|
| 364 |
+
"\n",
|
| 365 |
+
"# Placeholder test queries (replace with your assignment-specific questions later)\n",
|
| 366 |
+
"test_queries = [\n",
|
| 367 |
+
" \"What is the definition of X?\",\n",
|
| 368 |
+
" \"Explain concept Y.\",\n",
|
| 369 |
+
" \"How does Z work?\",\n",
|
| 370 |
+
"]\n",
|
| 371 |
+
"\n",
|
| 372 |
+
"# Helper for a simple relevance note based on keyword overlap\n",
|
| 373 |
+
"stop_words = {\"what\", \"is\", \"the\", \"of\", \"explain\", \"how\", \"does\", \"work\", \"concept\", \"definition\"}\n",
|
| 374 |
+
"\n",
|
| 375 |
+
"def relevance_note(query, chunk_text):\n",
|
| 376 |
+
" query_terms = {w.lower().strip(\".,?!:;()[]{}\\\"'\") for w in query.split()}\n",
|
| 377 |
+
" query_terms = {w for w in query_terms if w and w not in stop_words and len(w) > 1}\n",
|
| 378 |
+
" chunk_lower = chunk_text.lower()\n",
|
| 379 |
+
"\n",
|
| 380 |
+
" matches = [term for term in query_terms if term in chunk_lower]\n",
|
| 381 |
+
" if matches:\n",
|
| 382 |
+
" return f\"Relevant: Yes — because it contains query term(s): {', '.join(matches)}\"\n",
|
| 383 |
+
" return \"Relevant: No — because there is no clear keyword overlap with the query.\"\n",
|
| 384 |
+
"\n",
|
| 385 |
+
"# Run top-3 similarity retrieval for each query and print readable output\n",
|
| 386 |
+
"for query in test_queries:\n",
|
| 387 |
+
" print(\"=\" * 90)\n",
|
| 388 |
+
" print(f\"Query: {query}\")\n",
|
| 389 |
+
"\n",
|
| 390 |
+
" results = vectorstore.similarity_search(query, k=3)\n",
|
| 391 |
+
" for i, doc in enumerate(results, start=1):\n",
|
| 392 |
+
" chunk_text = doc.page_content.strip()\n",
|
| 393 |
+
" preview = (chunk_text[:300] + \"...\") if len(chunk_text) > 300 else chunk_text\n",
|
| 394 |
+
"\n",
|
| 395 |
+
" print(f\"\\nResult {i} (trimmed):\")\n",
|
| 396 |
+
" print(preview)\n",
|
| 397 |
+
" print(relevance_note(query, chunk_text))\n",
|
| 398 |
+
"\n",
|
| 399 |
+
"print(\"\\nRetrieval test complete. (No LLM calls, no RAG chain built.)\")"
|
| 400 |
+
]
|
| 401 |
+
},
|
| 402 |
+
{
|
| 403 |
+
"cell_type": "code",
|
| 404 |
+
"execution_count": 96,
|
| 405 |
+
"id": "fe1ef0a6",
|
| 406 |
+
"metadata": {},
|
| 407 |
+
"outputs": [
|
| 408 |
+
{
|
| 409 |
+
"name": "stdout",
|
| 410 |
+
"output_type": "stream",
|
| 411 |
+
"text": [
|
| 412 |
+
"Loading weights: 100%|██████████| 103/103 [00:00<00:00, 2939.85it/s]\n",
|
| 413 |
+
"\u001b[1mBertModel LOAD REPORT\u001b[0m from: sentence-transformers/all-MiniLM-L6-v2\n",
|
| 414 |
+
"Key | Status | | \n",
|
| 415 |
+
"------------------------+------------+--+-\n",
|
| 416 |
+
"embeddings.position_ids | UNEXPECTED | | \n",
|
| 417 |
+
"\n",
|
| 418 |
+
"Notes:\n",
|
| 419 |
+
"- UNEXPECTED:\tcan be ignored when loading from different task/architecture; not ok if you expect identical arch.\n"
|
| 420 |
+
]
|
| 421 |
+
},
|
| 422 |
+
{
|
| 423 |
+
"name": "stdout",
|
| 424 |
+
"output_type": "stream",
|
| 425 |
+
"text": [
|
| 426 |
+
"Active metadata filter: None\n",
|
| 427 |
+
"BM25 candidate docs after filtering: 4979\n",
|
| 428 |
+
"Hybrid retrieval check (vector vs ensemble top-3 overlap):\n",
|
| 429 |
+
"- Query: 'What is the definition of X?' | overlap=3/3\n",
|
| 430 |
+
"- Query: 'Explain concept Y.' | overlap=3/3\n",
|
| 431 |
+
"- Query: 'How does Z work?' | overlap=3/3\n",
|
| 432 |
+
"------------------------------------------------------------------------------------------\n",
|
| 433 |
+
"Query: What is the definition of X?\n",
|
| 434 |
+
"Answer: I don't know based on the provided context.\n",
|
| 435 |
+
"------------------------------------------------------------------------------------------\n",
|
| 436 |
+
"Query: Explain concept Y.\n",
|
| 437 |
+
"Answer: I don't know based on the provided context.\n",
|
| 438 |
+
"------------------------------------------------------------------------------------------\n",
|
| 439 |
+
"Query: How does Z work?\n",
|
| 440 |
+
"Answer: I don't know based on the provided context.\n",
|
| 441 |
+
"------------------------------------------------------------------------------------------\n"
|
| 442 |
+
]
|
| 443 |
+
}
|
| 444 |
+
],
|
| 445 |
+
"source": [
|
| 446 |
+
"# Step 5 (Build RAG Chain): Hybrid retrieval + metadata-filtered retrieval + RetrievalQA\n",
|
| 447 |
+
"import os\n",
|
| 448 |
+
"from pathlib import Path\n",
|
| 449 |
+
"from dotenv import load_dotenv\n",
|
| 450 |
+
"from langchain_community.embeddings import HuggingFaceEmbeddings\n",
|
| 451 |
+
"from langchain_community.vectorstores import Chroma\n",
|
| 452 |
+
"from langchain_community.retrievers import BM25Retriever\n",
|
| 453 |
+
"from langchain_openai import ChatOpenAI\n",
|
| 454 |
+
"\n",
|
| 455 |
+
"# EnsembleRetriever location differs across LangChain packaging layouts\n",
|
| 456 |
+
"try:\n",
|
| 457 |
+
" from langchain.retrievers import EnsembleRetriever\n",
|
| 458 |
+
"except ModuleNotFoundError:\n",
|
| 459 |
+
" from langchain_classic.retrievers import EnsembleRetriever\n",
|
| 460 |
+
"\n",
|
| 461 |
+
"# Compatibility imports for different LangChain package layouts\n",
|
| 462 |
+
"try:\n",
|
| 463 |
+
" from langchain.chains import RetrievalQA\n",
|
| 464 |
+
" from langchain.prompts import ChatPromptTemplate\n",
|
| 465 |
+
"except ModuleNotFoundError:\n",
|
| 466 |
+
" from langchain_classic.chains import RetrievalQA\n",
|
| 467 |
+
" from langchain_core.prompts import ChatPromptTemplate\n",
|
| 468 |
+
"\n",
|
| 469 |
+
"# Load environment variables from .env (works in notebooks even when cwd differs)\n",
|
| 470 |
+
"load_dotenv()\n",
|
| 471 |
+
"project_env = Path.cwd() / \".env\"\n",
|
| 472 |
+
"if project_env.exists():\n",
|
| 473 |
+
" load_dotenv(project_env, override=False)\n",
|
| 474 |
+
"\n",
|
| 475 |
+
"# Reconnect to the same embedding model and persisted Chroma collection from Step 3\n",
|
| 476 |
+
"embedding_model = HuggingFaceEmbeddings(\n",
|
| 477 |
+
" model_name=\"sentence-transformers/all-MiniLM-L6-v2\"\n",
|
| 478 |
+
")\n",
|
| 479 |
+
"vectorstore = Chroma(\n",
|
| 480 |
+
" collection_name=\"textbook_rag\",\n",
|
| 481 |
+
" embedding_function=embedding_model,\n",
|
| 482 |
+
" persist_directory=\"./chroma_db\",\n",
|
| 483 |
+
")\n",
|
| 484 |
+
"\n",
|
| 485 |
+
"# Use Step 2 chunks for BM25 and metadata filtering\n",
|
| 486 |
+
"if \"chunks_500_100\" not in globals() or not chunks_500_100:\n",
|
| 487 |
+
" raise ValueError(\"Run Step 2 first so `chunks_500_100` exists.\")\n",
|
| 488 |
+
"\n",
|
| 489 |
+
"# Optional metadata filters for retrieval. Set to None to disable a filter.\n",
|
| 490 |
+
"active_filters = {\n",
|
| 491 |
+
" \"source\": None, # Example: \"textbook_1.pdf\"\n",
|
| 492 |
+
" \"section\": None, # Example: \"pages_1_20\"\n",
|
| 493 |
+
" \"date\": None, # Example: \"2023-01-01\"\n",
|
| 494 |
+
"}\n",
|
| 495 |
+
"\n",
|
| 496 |
+
"# Build a Chroma filter dict from enabled filters\n",
|
| 497 |
+
"def build_chroma_filter(filters):\n",
|
| 498 |
+
" return {k: v for k, v in filters.items() if v is not None}\n",
|
| 499 |
+
"\n",
|
| 500 |
+
"# Apply filters to in-memory chunks (used by BM25)\n",
|
| 501 |
+
"def filter_documents_by_metadata(documents, filters):\n",
|
| 502 |
+
" filtered = []\n",
|
| 503 |
+
" for d in documents:\n",
|
| 504 |
+
" keep = True\n",
|
| 505 |
+
" for k, v in filters.items():\n",
|
| 506 |
+
" if v is not None and d.metadata.get(k) != v:\n",
|
| 507 |
+
" keep = False\n",
|
| 508 |
+
" break\n",
|
| 509 |
+
" if keep:\n",
|
| 510 |
+
" filtered.append(d)\n",
|
| 511 |
+
" return filtered\n",
|
| 512 |
+
"\n",
|
| 513 |
+
"active_filter_dict = build_chroma_filter(active_filters)\n",
|
| 514 |
+
"filtered_docs_for_bm25 = filter_documents_by_metadata(chunks_500_100, active_filters)\n",
|
| 515 |
+
"\n",
|
| 516 |
+
"if not filtered_docs_for_bm25:\n",
|
| 517 |
+
" raise ValueError(\"Metadata filters returned 0 docs. Relax `active_filters` and rerun Step 5.\")\n",
|
| 518 |
+
"\n",
|
| 519 |
+
"# Vector retriever with metadata filtering\n",
|
| 520 |
+
"vector_search_kwargs = {\"k\": 3}\n",
|
| 521 |
+
"if active_filter_dict:\n",
|
| 522 |
+
" vector_search_kwargs[\"filter\"] = active_filter_dict\n",
|
| 523 |
+
"\n",
|
| 524 |
+
"retriever_vector = vectorstore.as_retriever(\n",
|
| 525 |
+
" search_type=\"similarity\",\n",
|
| 526 |
+
" search_kwargs=vector_search_kwargs,\n",
|
| 527 |
+
")\n",
|
| 528 |
+
"\n",
|
| 529 |
+
"# BM25 retriever on the same filtered subset\n",
|
| 530 |
+
"retriever_bm25 = BM25Retriever.from_documents(filtered_docs_for_bm25)\n",
|
| 531 |
+
"retriever_bm25.k = 3\n",
|
| 532 |
+
"\n",
|
| 533 |
+
"# Combine retrievers: tune weights for more keyword vs semantic influence\n",
|
| 534 |
+
"retriever = EnsembleRetriever(\n",
|
| 535 |
+
" retrievers=[retriever_vector, retriever_bm25],\n",
|
| 536 |
+
" weights=[0.5, 0.5],\n",
|
| 537 |
+
")\n",
|
| 538 |
+
"\n",
|
| 539 |
+
"# Quick retrieval comparison on Step 4 queries\n",
|
| 540 |
+
"queries_compare = test_queries if \"test_queries\" in globals() else [\n",
|
| 541 |
+
" \"What is the definition of X?\",\n",
|
| 542 |
+
" \"Explain concept Y.\",\n",
|
| 543 |
+
" \"How does Z work?\",\n",
|
| 544 |
+
"]\n",
|
| 545 |
+
"\n",
|
| 546 |
+
"def _doc_fingerprint(doc):\n",
|
| 547 |
+
" return hash((doc.page_content or \"\").strip())\n",
|
| 548 |
+
"\n",
|
| 549 |
+
"print(f\"Active metadata filter: {active_filter_dict if active_filter_dict else 'None'}\")\n",
|
| 550 |
+
"print(f\"BM25 candidate docs after filtering: {len(filtered_docs_for_bm25)}\")\n",
|
| 551 |
+
"print(\"Hybrid retrieval check (vector vs ensemble top-3 overlap):\")\n",
|
| 552 |
+
"for q in queries_compare:\n",
|
| 553 |
+
" v_docs = retriever_vector.invoke(q)\n",
|
| 554 |
+
" h_docs = retriever.invoke(q)\n",
|
| 555 |
+
" v_fps = {_doc_fingerprint(d) for d in v_docs}\n",
|
| 556 |
+
" h_fps = {_doc_fingerprint(d) for d in h_docs}\n",
|
| 557 |
+
" overlap = len(v_fps & h_fps)\n",
|
| 558 |
+
" print(f\"- Query: {q!r} | overlap={overlap}/3\")\n",
|
| 559 |
+
"print(\"-\" * 90)\n",
|
| 560 |
+
"\n",
|
| 561 |
+
"# Define a chat prompt with an explicit system message\n",
|
| 562 |
+
"custom_prompt = ChatPromptTemplate.from_messages([\n",
|
| 563 |
+
" (\n",
|
| 564 |
+
" \"system\",\n",
|
| 565 |
+
" \"You are a warm, friendly, and helpful assistant. \"\n",
|
| 566 |
+
" \"If the user message is only a greeting (like hi, hey, or hello), respond with a short friendly greeting and ask how you can help. \"\n",
|
| 567 |
+
" \"For non-greeting questions, use ONLY the provided context. \"\n",
|
| 568 |
+
" \"If the answer is not in the context, say: 'I don't know based on the provided context.'\",\n",
|
| 569 |
+
" ),\n",
|
| 570 |
+
" (\n",
|
| 571 |
+
" \"human\",\n",
|
| 572 |
+
" \"CONTEXT:\\nThe information in the two PDF documents textbook_1.pdf and textbook_2.pdf.\\n{context}\\n\\n\"\n",
|
| 573 |
+
" \"QUESTION:\\n{question}\\n\\nANSWER:\",\n",
|
| 574 |
+
" ),\n",
|
| 575 |
+
"])\n",
|
| 576 |
+
"\n",
|
| 577 |
+
"# Initialize LLM after loading .env\n",
|
| 578 |
+
"if not os.getenv(\"OPENAI_API_KEY\"):\n",
|
| 579 |
+
" raise EnvironmentError(\"OPENAI_API_KEY is not set. Confirm .env is in the notebook working directory and restart/re-run this cell.\")\n",
|
| 580 |
+
"\n",
|
| 581 |
+
"llm = ChatOpenAI(model=\"gpt-3.5-turbo\", temperature=0.7)\n",
|
| 582 |
+
"\n",
|
| 583 |
+
"# Build RetrievalQA chain using 'stuff' strategy and custom prompt\n",
|
| 584 |
+
"qa_chain = RetrievalQA.from_chain_type(\n",
|
| 585 |
+
" llm=llm,\n",
|
| 586 |
+
" chain_type=\"stuff\",\n",
|
| 587 |
+
" retriever=retriever,\n",
|
| 588 |
+
" return_source_documents=False,\n",
|
| 589 |
+
" chain_type_kwargs={\"prompt\": custom_prompt},\n",
|
| 590 |
+
")\n",
|
| 591 |
+
"\n",
|
| 592 |
+
"# Reuse Step 4 queries when available; otherwise default placeholders\n",
|
| 593 |
+
"queries = queries_compare\n",
|
| 594 |
+
"\n",
|
| 595 |
+
"# Run the same 3 queries and print answers cleanly\n",
|
| 596 |
+
"for query in queries:\n",
|
| 597 |
+
" result = qa_chain.invoke({\"query\": query})\n",
|
| 598 |
+
" answer = result[\"result\"] if isinstance(result, dict) else str(result)\n",
|
| 599 |
+
"\n",
|
| 600 |
+
" print(f\"Query: {query}\")\n",
|
| 601 |
+
" print(f\"Answer: {answer}\")\n",
|
| 602 |
+
" print(\"-\" * 90)"
|
| 603 |
+
]
|
| 604 |
+
},
|
| 605 |
+
{
|
| 606 |
+
"cell_type": "code",
|
| 607 |
+
"execution_count": 97,
|
| 608 |
+
"id": "e676144f",
|
| 609 |
+
"metadata": {},
|
| 610 |
+
"outputs": [
|
| 611 |
+
{
|
| 612 |
+
"name": "stdout",
|
| 613 |
+
"output_type": "stream",
|
| 614 |
+
"text": [
|
| 615 |
+
"==============================================================================================================\n",
|
| 616 |
+
"Step 6 Evaluation Results\n",
|
| 617 |
+
"==============================================================================================================\n",
|
| 618 |
+
"\n",
|
| 619 |
+
"Q1: What is concept A?\n",
|
| 620 |
+
"Retrieved relevant chunks: Yes\n",
|
| 621 |
+
"Answer grounded in context: No\n",
|
| 622 |
+
"Answer correct: No\n",
|
| 623 |
+
"Generated answer: I don't know based on the provided context.\n",
|
| 624 |
+
"--------------------------------------------------------------------------------------------------------------\n",
|
| 625 |
+
"\n",
|
| 626 |
+
"Q2: How does method B work?\n",
|
| 627 |
+
"Retrieved relevant chunks: Yes\n",
|
| 628 |
+
"Answer grounded in context: Yes\n",
|
| 629 |
+
"Answer correct: No\n",
|
| 630 |
+
"Generated answer: I don't know based on the provided context.\n",
|
| 631 |
+
"--------------------------------------------------------------------------------------------------------------\n",
|
| 632 |
+
"\n",
|
| 633 |
+
"Q3: Define term C.\n",
|
| 634 |
+
"Retrieved relevant chunks: Yes\n",
|
| 635 |
+
"Answer grounded in context: Yes\n",
|
| 636 |
+
"Answer correct: No\n",
|
| 637 |
+
"Generated answer: The term C in the given context refers to a parameter that controls how aggressively a model fits to the training data in machine learning algorithms.\n",
|
| 638 |
+
"--------------------------------------------------------------------------------------------------------------\n",
|
| 639 |
+
"\n",
|
| 640 |
+
"Q4: What is the purpose of D?\n",
|
| 641 |
+
"Retrieved relevant chunks: Yes\n",
|
| 642 |
+
"Answer grounded in context: No\n",
|
| 643 |
+
"Answer correct: No\n",
|
| 644 |
+
"Generated answer: I don't know based on the provided context.\n",
|
| 645 |
+
"--------------------------------------------------------------------------------------------------------------\n",
|
| 646 |
+
"\n",
|
| 647 |
+
"Q5: Explain relationship between E and F.\n",
|
| 648 |
+
"Retrieved relevant chunks: Yes\n",
|
| 649 |
+
"Answer grounded in context: No\n",
|
| 650 |
+
"Answer correct: No\n",
|
| 651 |
+
"Generated answer: I don't know based on the provided context.\n",
|
| 652 |
+
"--------------------------------------------------------------------------------------------------------------\n",
|
| 653 |
+
"Retrieval accuracy: 5/5\n",
|
| 654 |
+
"Faithfulness accuracy: 2/5\n",
|
| 655 |
+
"Correctness accuracy: 0/5\n"
|
| 656 |
+
]
|
| 657 |
+
}
|
| 658 |
+
],
|
| 659 |
+
"source": [
|
| 660 |
+
"# Step 6 (Evaluation): Evaluate retrieval relevance, grounding, and answer correctness\n",
|
| 661 |
+
"\n",
|
| 662 |
+
"# Ensure Step 5 objects exist\n",
|
| 663 |
+
"if \"retriever\" not in globals() or \"qa_chain\" not in globals():\n",
|
| 664 |
+
" raise ValueError(\"Run Step 5 first so `retriever` and `qa_chain` are available.\")\n",
|
| 665 |
+
"\n",
|
| 666 |
+
"# Small evaluation set (replace placeholders with your real questions/answers)\n",
|
| 667 |
+
"eval_set = [\n",
|
| 668 |
+
" {\n",
|
| 669 |
+
" \"question\": \"What is concept A?\",\n",
|
| 670 |
+
" \"gold_answer\": \"[Replace with known correct answer for concept A]\",\n",
|
| 671 |
+
" \"reference_keywords\": [\"concept\", \"a\"],\n",
|
| 672 |
+
" },\n",
|
| 673 |
+
" {\n",
|
| 674 |
+
" \"question\": \"How does method B work?\",\n",
|
| 675 |
+
" \"gold_answer\": \"[Replace with known correct answer for method B]\",\n",
|
| 676 |
+
" \"reference_keywords\": [\"method\", \"b\"],\n",
|
| 677 |
+
" },\n",
|
| 678 |
+
" {\n",
|
| 679 |
+
" \"question\": \"Define term C.\",\n",
|
| 680 |
+
" \"gold_answer\": \"[Replace with known correct definition for term C]\",\n",
|
| 681 |
+
" \"reference_keywords\": [\"term\", \"c\", \"define\"],\n",
|
| 682 |
+
" },\n",
|
| 683 |
+
" {\n",
|
| 684 |
+
" \"question\": \"What is the purpose of D?\",\n",
|
| 685 |
+
" \"gold_answer\": \"[Replace with known purpose of D]\",\n",
|
| 686 |
+
" \"reference_keywords\": [\"purpose\", \"d\"],\n",
|
| 687 |
+
" },\n",
|
| 688 |
+
" {\n",
|
| 689 |
+
" \"question\": \"Explain relationship between E and F.\",\n",
|
| 690 |
+
" \"gold_answer\": \"[Replace with known relationship between E and F]\",\n",
|
| 691 |
+
" \"reference_keywords\": [\"relationship\", \"e\", \"f\"],\n",
|
| 692 |
+
" },\n",
|
| 693 |
+
"]\n",
|
| 694 |
+
"\n",
|
| 695 |
+
"# Lightweight helper to normalize text for simple heuristic checks\n",
|
| 696 |
+
"def normalize(text):\n",
|
| 697 |
+
" return \" \".join(text.lower().split())\n",
|
| 698 |
+
"\n",
|
| 699 |
+
"results = []\n",
|
| 700 |
+
"retrieval_hits = 0\n",
|
| 701 |
+
"faithfulness_hits = 0\n",
|
| 702 |
+
"correctness_hits = 0\n",
|
| 703 |
+
"\n",
|
| 704 |
+
"# Evaluate each question: retriever-only first, then full RAG chain\n",
|
| 705 |
+
"for item in eval_set:\n",
|
| 706 |
+
" question = item[\"question\"]\n",
|
| 707 |
+
" gold_answer = item[\"gold_answer\"]\n",
|
| 708 |
+
" keywords = [k.lower() for k in item[\"reference_keywords\"]]\n",
|
| 709 |
+
"\n",
|
| 710 |
+
" # 1) Retriever-only pass\n",
|
| 711 |
+
" retrieved_docs = retriever.invoke(question)\n",
|
| 712 |
+
" retrieved_text = \"\\n\\n\".join(doc.page_content for doc in retrieved_docs)\n",
|
| 713 |
+
" retrieved_text_norm = normalize(retrieved_text)\n",
|
| 714 |
+
"\n",
|
| 715 |
+
" retrieval_relevant = any(k in retrieved_text_norm for k in keywords)\n",
|
| 716 |
+
" retrieval_hits += int(retrieval_relevant)\n",
|
| 717 |
+
"\n",
|
| 718 |
+
" # 2) Full RAG chain pass\n",
|
| 719 |
+
" rag_output = qa_chain.invoke({\"query\": question})\n",
|
| 720 |
+
" answer = rag_output[\"result\"] if isinstance(rag_output, dict) else str(rag_output)\n",
|
| 721 |
+
" answer_norm = normalize(answer)\n",
|
| 722 |
+
"\n",
|
| 723 |
+
" # 3a) Faithfulness (grounded): answer terms should appear in retrieved context\n",
|
| 724 |
+
" answer_tokens = [t for t in answer_norm.replace(\".\", \" \").replace(\",\", \" \").split() if len(t) > 3]\n",
|
| 725 |
+
" overlap_count = sum(1 for t in set(answer_tokens) if t in retrieved_text_norm)\n",
|
| 726 |
+
" grounded_in_context = overlap_count >= max(1, min(3, len(set(answer_tokens)) // 5 + 1))\n",
|
| 727 |
+
" faithfulness_hits += int(grounded_in_context)\n",
|
| 728 |
+
"\n",
|
| 729 |
+
" # 3b) Correctness: heuristic check against user-known answer placeholder\n",
|
| 730 |
+
" # Replace this logic later with your own strict grading based on real expected answers.\n",
|
| 731 |
+
" if gold_answer.startswith(\"[Replace with\"):\n",
|
| 732 |
+
" answer_correct = False\n",
|
| 733 |
+
" else:\n",
|
| 734 |
+
" gold_norm = normalize(gold_answer)\n",
|
| 735 |
+
" answer_correct = gold_norm in answer_norm or answer_norm in gold_norm\n",
|
| 736 |
+
" correctness_hits += int(answer_correct)\n",
|
| 737 |
+
"\n",
|
| 738 |
+
" results.append(\n",
|
| 739 |
+
" {\n",
|
| 740 |
+
" \"question\": question,\n",
|
| 741 |
+
" \"retrieval_relevant\": retrieval_relevant,\n",
|
| 742 |
+
" \"grounded_in_context\": grounded_in_context,\n",
|
| 743 |
+
" \"answer_correct\": answer_correct,\n",
|
| 744 |
+
" \"answer\": answer,\n",
|
| 745 |
+
" }\n",
|
| 746 |
+
" )\n",
|
| 747 |
+
"\n",
|
| 748 |
+
"# Print structured evaluation output\n",
|
| 749 |
+
"print(\"=\" * 110)\n",
|
| 750 |
+
"print(\"Step 6 Evaluation Results\")\n",
|
| 751 |
+
"print(\"=\" * 110)\n",
|
| 752 |
+
"for idx, row in enumerate(results, start=1):\n",
|
| 753 |
+
" print(f\"\\nQ{idx}: {row['question']}\")\n",
|
| 754 |
+
" print(f\"Retrieved relevant chunks: {'Yes' if row['retrieval_relevant'] else 'No'}\")\n",
|
| 755 |
+
" print(f\"Answer grounded in context: {'Yes' if row['grounded_in_context'] else 'No'}\")\n",
|
| 756 |
+
" print(f\"Answer correct: {'Yes' if row['answer_correct'] else 'No'}\")\n",
|
| 757 |
+
" print(f\"Generated answer: {row['answer']}\")\n",
|
| 758 |
+
" print(\"-\" * 110)\n",
|
| 759 |
+
"\n",
|
| 760 |
+
"# Compute and print assignment-required metrics\n",
|
| 761 |
+
"n = len(eval_set)\n",
|
| 762 |
+
"print(f\"Retrieval accuracy: {retrieval_hits}/{n}\")\n",
|
| 763 |
+
"print(f\"Faithfulness accuracy: {faithfulness_hits}/{n}\")\n",
|
| 764 |
+
"print(f\"Correctness accuracy: {correctness_hits}/{n}\")"
|
| 765 |
+
]
|
| 766 |
+
},
|
| 767 |
+
{
|
| 768 |
+
"cell_type": "code",
|
| 769 |
+
"execution_count": 98,
|
| 770 |
+
"id": "56c3e91d",
|
| 771 |
+
"metadata": {},
|
| 772 |
+
"outputs": [
|
| 773 |
+
{
|
| 774 |
+
"name": "stdout",
|
| 775 |
+
"output_type": "stream",
|
| 776 |
+
"text": [
|
| 777 |
+
"* Running on local URL: http://127.0.0.1:7868\n",
|
| 778 |
+
"* To create a public link, set `share=True` in `launch()`.\n"
|
| 779 |
+
]
|
| 780 |
+
},
|
| 781 |
+
{
|
| 782 |
+
"data": {
|
| 783 |
+
"text/html": [
|
| 784 |
+
"<div><iframe src=\"http://127.0.0.1:7868/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
|
| 785 |
+
],
|
| 786 |
+
"text/plain": [
|
| 787 |
+
"<IPython.core.display.HTML object>"
|
| 788 |
+
]
|
| 789 |
+
},
|
| 790 |
+
"metadata": {},
|
| 791 |
+
"output_type": "display_data"
|
| 792 |
+
},
|
| 793 |
+
{
|
| 794 |
+
"data": {
|
| 795 |
+
"text/plain": []
|
| 796 |
+
},
|
| 797 |
+
"execution_count": null,
|
| 798 |
+
"metadata": {},
|
| 799 |
+
"output_type": "execute_result"
|
| 800 |
+
}
|
| 801 |
+
],
|
| 802 |
+
"source": [
|
| 803 |
+
"# Optional UI: Test the RAG chain with vector vs hybrid retrieval debug in Gradio\n",
|
| 804 |
+
"import gradio as gr\n",
|
| 805 |
+
"\n",
|
| 806 |
+
"# Ensure Step 5 has been executed so `qa_chain`, `retriever`, and `retriever_vector` exist\n",
|
| 807 |
+
"if \"qa_chain\" not in globals() or \"retriever\" not in globals() or \"retriever_vector\" not in globals():\n",
|
| 808 |
+
" raise ValueError(\"Run Step 5 first so `qa_chain`, `retriever`, and `retriever_vector` are available.\")\n",
|
| 809 |
+
"\n",
|
| 810 |
+
"# Function used by the UI to query the RAG chain and inspect retrieved context\n",
|
| 811 |
+
"def ask_rag(question):\n",
|
| 812 |
+
" question = (question or \"\").strip()\n",
|
| 813 |
+
" if not question:\n",
|
| 814 |
+
" return \"Please enter a question.\", \"\", \"\"\n",
|
| 815 |
+
"\n",
|
| 816 |
+
" # Handle greetings directly for a friendlier chat experience\n",
|
| 817 |
+
" normalized = question.lower().strip(\".!? \")\n",
|
| 818 |
+
" greetings = {\"hi\", \"hey\", \"hello\", \"hiya\", \"yo\"}\n",
|
| 819 |
+
" if normalized in greetings:\n",
|
| 820 |
+
" return \"Hi! What can I help you with today?\", \"\", \"\"\n",
|
| 821 |
+
"\n",
|
| 822 |
+
" vector_docs = retriever_vector.invoke(question)\n",
|
| 823 |
+
" hybrid_docs = retriever.invoke(question)\n",
|
| 824 |
+
"\n",
|
| 825 |
+
" result = qa_chain.invoke({\"query\": question})\n",
|
| 826 |
+
" answer = result[\"result\"] if isinstance(result, dict) else str(result)\n",
|
| 827 |
+
"\n",
|
| 828 |
+
" def format_docs(docs, label):\n",
|
| 829 |
+
" parts = [f\"{label} (top {len(docs)})\"]\n",
|
| 830 |
+
" for i, doc in enumerate(docs, start=1):\n",
|
| 831 |
+
" text = doc.page_content.strip()\n",
|
| 832 |
+
" preview = (text[:300] + \"...\") if len(text) > 300 else text\n",
|
| 833 |
+
" meta = {\n",
|
| 834 |
+
" \"source\": doc.metadata.get(\"source\"),\n",
|
| 835 |
+
" \"date\": doc.metadata.get(\"date\"),\n",
|
| 836 |
+
" \"section\": doc.metadata.get(\"section\"),\n",
|
| 837 |
+
" }\n",
|
| 838 |
+
" parts.append(f\"Chunk {i} | metadata={meta}:\\n{preview}\")\n",
|
| 839 |
+
" return \"\\n\\n\".join(parts)\n",
|
| 840 |
+
"\n",
|
| 841 |
+
" return (\n",
|
| 842 |
+
" answer,\n",
|
| 843 |
+
" format_docs(vector_docs, \"Vector only\"),\n",
|
| 844 |
+
" format_docs(hybrid_docs, \"Hybrid (vector + BM25)\"),\n",
|
| 845 |
+
" )\n",
|
| 846 |
+
"\n",
|
| 847 |
+
"# Build and launch a minimal interface (question -> answer + retrieved chunks)\n",
|
| 848 |
+
"demo = gr.Interface(\n",
|
| 849 |
+
" fn=ask_rag,\n",
|
| 850 |
+
" inputs=gr.Textbox(lines=3, label=\"Ask a question\"),\n",
|
| 851 |
+
" outputs=[\n",
|
| 852 |
+
" gr.Textbox(lines=8, label=\"RAG Answer\"),\n",
|
| 853 |
+
" gr.Textbox(lines=14, label=\"Retrieved Chunks: Vector only\"),\n",
|
| 854 |
+
" gr.Textbox(lines=14, label=\"Retrieved Chunks: Hybrid\"),\n",
|
| 855 |
+
" ],\n",
|
| 856 |
+
" title=\"Textbook RAG Assistant\",\n",
|
| 857 |
+
" description=\"Ask questions about textbook_1.pdf and textbook_2.pdf using your RetrievalQA chain.\",\n",
|
| 858 |
+
")\n",
|
| 859 |
+
"\n",
|
| 860 |
+
"demo.launch(share=False)"
|
| 861 |
+
]
|
| 862 |
+
}
|
| 863 |
+
],
|
| 864 |
+
"metadata": {
|
| 865 |
+
"kernelspec": {
|
| 866 |
+
"display_name": "Python 3",
|
| 867 |
+
"language": "python",
|
| 868 |
+
"name": "python3"
|
| 869 |
+
},
|
| 870 |
+
"language_info": {
|
| 871 |
+
"codemirror_mode": {
|
| 872 |
+
"name": "ipython",
|
| 873 |
+
"version": 3
|
| 874 |
+
},
|
| 875 |
+
"file_extension": ".py",
|
| 876 |
+
"mimetype": "text/x-python",
|
| 877 |
+
"name": "python",
|
| 878 |
+
"nbconvert_exporter": "python",
|
| 879 |
+
"pygments_lexer": "ipython3",
|
| 880 |
+
"version": "3.14.4"
|
| 881 |
+
}
|
| 882 |
+
},
|
| 883 |
+
"nbformat": 4,
|
| 884 |
+
"nbformat_minor": 5
|
| 885 |
+
}
|