{ "cells": [ { "cell_type": "markdown", "id": "12a9fcb2", "metadata": {}, "source": [ "### Step 1: Load 2 text PDFs" ] }, { "cell_type": "code", "execution_count": 91, "id": "e322de88", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Note: you may need to restart the kernel to use updated packages.\n" ] } ], "source": [ "# Step 0 (Setup): Install required packages (run once per environment)\n", "%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" ] }, { "cell_type": "code", "execution_count": 92, "id": "24647d78", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Number of documents loaded: 1201\n", "\n", "Sample of first document content:\n", "\n", "Chip Huyen\n", " AI Engineering\n", "Building Applications \n", "with Foundation Models\n" ] } ], "source": [ "# Step 1 (Load): Load two text-based PDFs into LangChain Documents\n", "\n", "from langchain_community.document_loaders import PyPDFLoader\n", "\n", "# Define the PDF file paths (assumed to be in the current working directory)\n", "pdf_paths = [\"textbook_1.pdf\", \"textbook_2.pdf\"]\n", "\n", "# Load each PDF into a list of Document objects (typically one Document per page)\n", "all_documents = []\n", "for path in pdf_paths:\n", " loader = PyPDFLoader(path)\n", " docs = loader.load()\n", " all_documents.extend(docs)\n", "\n", "# Print assignment-required outputs\n", "print(f\"Number of documents loaded: {len(all_documents)}\")\n", "\n", "# Print a sample from the first loaded document (first 700 characters)\n", "if all_documents:\n", " sample_text = all_documents[0].page_content[:700]\n", " print(\"\\nSample of first document content:\\n\")\n", " print(sample_text)\n", "else:\n", " print(\"\\nNo documents were loaded.\")" ] }, { "cell_type": "code", "execution_count": 93, "id": "490ed688", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Configuration: chunk_size=500, chunk_overlap=100\n", "Total number of chunks created: 4979\n", "Character count of the smallest chunk: 2\n", "Character count of the largest chunk: 500\n", "Sample metadata from first chunk: {'source': 'textbook_1.pdf', 'date': '2023-01-01', 'section': 'pages_1_20'}\n", "------------------------------------------------------------\n", "Configuration: chunk_size=1000, chunk_overlap=150\n", "Total number of chunks created: 2571\n", "Character count of the smallest chunk: 2\n", "Character count of the largest chunk: 1000\n", "Sample metadata from first chunk: {'source': 'textbook_1.pdf', 'date': '2023-01-01', 'section': 'pages_1_20'}\n", "------------------------------------------------------------\n" ] } ], "source": [ "# Step 2 (Chunk): Split loaded documents into chunks with two configurations + metadata\n", "import os\n", "from langchain_text_splitters import RecursiveCharacterTextSplitter\n", "\n", "# Prefer the full Step 1 output, but support `docs` if that's your loaded list name\n", "if \"all_documents\" in globals() and all_documents:\n", " source_docs = all_documents\n", "elif \"docs\" in globals() and docs:\n", " source_docs = docs\n", "else:\n", " source_docs = []\n", "\n", "# Map each textbook to a date tag (adjust these to your real document dates if available)\n", "source_date_map = {\n", " \"textbook_1.pdf\": \"2023-01-01\",\n", " \"textbook_2.pdf\": \"2024-01-01\",\n", "}\n", "\n", "# Add metadata fields requested for filtered retrieval\n", "# - source: source file name\n", "# - date: date tag per source document\n", "# - section: derived from page number bucket (chapter/section proxy)\n", "def enrich_chunk_metadata(chunks):\n", " for chunk in chunks:\n", " src_path = chunk.metadata.get(\"source\", \"\")\n", " source_file = os.path.basename(src_path) if src_path else \"unknown_source\"\n", " page_num = int(chunk.metadata.get(\"page\", -1)) + 1\n", "\n", " if page_num <= 0:\n", " section = \"unknown_section\"\n", " else:\n", " section_start = ((page_num - 1) // 20) * 20 + 1\n", " section_end = section_start + 19\n", " section = f\"pages_{section_start}_{section_end}\"\n", "\n", " chunk.metadata[\"source\"] = source_file\n", " chunk.metadata[\"date\"] = source_date_map.get(source_file, \"unknown_date\")\n", " chunk.metadata[\"section\"] = section\n", " return chunks\n", "\n", "# Helper to split documents and print assignment-required chunk statistics\n", "def chunk_and_report(documents, chunk_size, chunk_overlap):\n", " splitter = RecursiveCharacterTextSplitter(\n", " chunk_size=chunk_size,\n", " chunk_overlap=chunk_overlap,\n", " )\n", " chunks = splitter.split_documents(documents)\n", " chunks = enrich_chunk_metadata(chunks)\n", "\n", " chunk_lengths = [len(chunk.page_content) for chunk in chunks]\n", " min_len = min(chunk_lengths) if chunk_lengths else 0\n", " max_len = max(chunk_lengths) if chunk_lengths else 0\n", "\n", " print(f\"Configuration: chunk_size={chunk_size}, chunk_overlap={chunk_overlap}\")\n", " print(f\"Total number of chunks created: {len(chunks)}\")\n", " print(f\"Character count of the smallest chunk: {min_len}\")\n", " print(f\"Character count of the largest chunk: {max_len}\")\n", "\n", " if chunks:\n", " sample_meta = {k: chunks[0].metadata.get(k) for k in [\"source\", \"date\", \"section\"]}\n", " print(f\"Sample metadata from first chunk: {sample_meta}\")\n", "\n", " print(\"-\" * 60)\n", " return chunks\n", "\n", "# First required configuration\n", "chunks_500_100 = chunk_and_report(source_docs, chunk_size=500, chunk_overlap=100)\n", "\n", "# Second required configuration\n", "chunks_1000_150 = chunk_and_report(source_docs, chunk_size=1000, chunk_overlap=150)" ] }, { "cell_type": "code", "execution_count": 94, "id": "bdc95c2f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Loading weights: 100%|██████████| 103/103 [00:00<00:00, 6986.89it/s]\n", "\u001b[1mBertModel LOAD REPORT\u001b[0m from: sentence-transformers/all-MiniLM-L6-v2\n", "Key | Status | | \n", "------------------------+------------+--+-\n", "embeddings.position_ids | UNEXPECTED | | \n", "\n", "Notes:\n", "- UNEXPECTED:\tcan be ignored when loading from different task/architecture; not ok if you expect identical arch.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Number of vectors stored: 4979\n", "Sample embedding shape: 384\n" ] } ], "source": [ "# Step 3 (Embed + Store): Embed 500-size chunks and persist them in ChromaDB\n", "import os\n", "from langchain_community.embeddings import HuggingFaceEmbeddings\n", "from langchain_community.vectorstores import Chroma\n", "\n", "# Use the smaller chunk set from Step 2\n", "if \"chunks_500_100\" not in globals() or not chunks_500_100:\n", " raise ValueError(\"`chunks_500_100` is missing. Run Step 2 first.\")\n", "\n", "# Initialize embedding model\n", "embedding_model = HuggingFaceEmbeddings(\n", " model_name=\"sentence-transformers/all-MiniLM-L6-v2\"\n", ")\n", "\n", "# Create persistent ChromaDB directory\n", "persist_dir = \"./chroma_db\"\n", "os.makedirs(persist_dir, exist_ok=True)\n", "\n", "# Recreate the collection each run to avoid duplicate vectors from repeated executions\n", "try:\n", " existing_store = Chroma(\n", " collection_name=\"textbook_rag\",\n", " embedding_function=embedding_model,\n", " persist_directory=persist_dir,\n", " )\n", " existing_store.delete_collection()\n", "except Exception:\n", " pass\n", "\n", "vectorstore = Chroma.from_documents(\n", " documents=chunks_500_100,\n", " embedding=embedding_model,\n", " collection_name=\"textbook_rag\",\n", " persist_directory=persist_dir,\n", ")\n", "\n", "# Print assignment-required stats\n", "num_vectors = vectorstore._collection.count()\n", "sample_embedding = embedding_model.embed_query(\"sample text\")\n", "\n", "print(f\"Number of vectors stored: {num_vectors}\")\n", "print(f\"Sample embedding shape: {len(sample_embedding)}\")" ] }, { "cell_type": "code", "execution_count": 95, "id": "d659b193", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Loading weights: 100%|██████████| 103/103 [00:00<00:00, 7916.97it/s]\n", "\u001b[1mBertModel LOAD REPORT\u001b[0m from: sentence-transformers/all-MiniLM-L6-v2\n", "Key | Status | | \n", "------------------------+------------+--+-\n", "embeddings.position_ids | UNEXPECTED | | \n", "\n", "Notes:\n", "- UNEXPECTED:\tcan be ignored when loading from different task/architecture; not ok if you expect identical arch.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "==========================================================================================\n", "Query: What is the definition of X?\n", "\n", "Result 1 (trimmed):\n", "3 While I love writing, one of the things I absolutely do not enjoy is trying to condense everyone’s opinions into\n", "one single definition. IBM defined data quality along seven dimensions: completeness, uniqueness, validity,\n", "timeliness, accuracy, consistency, and fitness for purpose. Wikipedia added a...\n", "Relevant: No — because there is no clear keyword overlap with the query.\n", "\n", "Result 2 (trimmed):\n", "Your goal is to predict what someone with 10 years of\n", "experience should earn. In this example, x = 10, and you want\n", "to predict what y should be.\n", "Relevant: No — because there is no clear keyword overlap with the query.\n", "\n", "Result 3 (trimmed):\n", "a 5% chance that the point corresponds to class 1. But if x =\n", "10, there is about a 76% chance that it’s class 1. If asked\n", "to classify that point as a red or a blue, you would conclude\n", "that it’s a red because it’s much more likely to be red\n", "than blue.\n", "Relevant: No — because there is no clear keyword overlap with the query.\n", "==========================================================================================\n", "Query: Explain concept Y.\n", "\n", "Result 1 (trimmed):\n", "Another instance of the model (Bob) asks Alice a series of questions to try to identify\n", "this concept. Alice can only answer yes or no. The score is based on whether Bob suc‐\n", "cessfully guesses the concept, and how many questions it takes for Bob to guess it.\n", "Here’s an example of a plausible conversat...\n", "Relevant: No — because there is no clear keyword overlap with the query.\n", "\n", "Result 2 (trimmed):\n", "neural network layers to tease more meaning from it before\n", "subjecting it to further processing.\n", "Relevant: No — because there is no clear keyword overlap with the query.\n", "\n", "Result 3 (trimmed):\n", "finding patterns in numbers and exploiting those patterns to\n", "make predictions. ML makes it possible to train a model with\n", "rows or sequences of 1s and 0s, and to learn from the data so\n", "that, given a new sequence, the model can predict what the\n", "result will be. Learning is the process by which ML fin...\n", "Relevant: No — because there is no clear keyword overlap with the query.\n", "==========================================================================================\n", "Query: How does Z work?\n", "\n", "Result 1 (trimmed):\n", "separable in n dimensions. Here’s a quick example.\n", "The classes in the two-dimensional dataset on the left in\n", "Figure 2-10 can’t be separated with a line. But if you add\n", "a third dimension so that points closer to the center have\n", "higher z values and points farther from the center have lower\n", "z values, a...\n", "Relevant: No — because there is no clear keyword overlap with the query.\n", "\n", "Result 2 (trimmed):\n", "Figure 10-9. The yellow arrow allows the generated response to be fed back into the sys‐\n", "tem, allowing more complex application patterns.\n", "A model’s outputs also can be used to invoke write actions, such as composing an\n", "email, placing an order, or initializing a bank transfer. Write actions allow a s...\n", "Relevant: No — because there is no clear keyword overlap with the query.\n", "\n", "Result 3 (trimmed):\n", "mechanism. Understanding this mechanism is necessary to understand how trans‐\n", "former models work. Under the hood, the attention mechanism leverages key, value,\n", "and query vectors:\n", "• The query vector (Q) represents the current state of the decoder at each decoding\n", "step. Using the same book summary exa...\n", "Relevant: No — because there is no clear keyword overlap with the query.\n", "\n", "Retrieval test complete. (No LLM calls, no RAG chain built.)\n" ] } ], "source": [ "# Step 4 (Test Retrieval): Query existing ChromaDB before building a RAG chain\n", "from langchain_community.embeddings import HuggingFaceEmbeddings\n", "from langchain_community.vectorstores import Chroma\n", "\n", "# Reconnect to the same embedding model and persisted Chroma collection\n", "embedding_model = HuggingFaceEmbeddings(\n", " model_name=\"sentence-transformers/all-MiniLM-L6-v2\"\n", ")\n", "\n", "vectorstore = Chroma(\n", " collection_name=\"textbook_rag\",\n", " embedding_function=embedding_model,\n", " persist_directory=\"./chroma_db\",\n", ")\n", "\n", "# Placeholder test queries (replace with your assignment-specific questions later)\n", "test_queries = [\n", " \"What is the definition of X?\",\n", " \"Explain concept Y.\",\n", " \"How does Z work?\",\n", "]\n", "\n", "# Helper for a simple relevance note based on keyword overlap\n", "stop_words = {\"what\", \"is\", \"the\", \"of\", \"explain\", \"how\", \"does\", \"work\", \"concept\", \"definition\"}\n", "\n", "def relevance_note(query, chunk_text):\n", " query_terms = {w.lower().strip(\".,?!:;()[]{}\\\"'\") for w in query.split()}\n", " query_terms = {w for w in query_terms if w and w not in stop_words and len(w) > 1}\n", " chunk_lower = chunk_text.lower()\n", "\n", " matches = [term for term in query_terms if term in chunk_lower]\n", " if matches:\n", " return f\"Relevant: Yes — because it contains query term(s): {', '.join(matches)}\"\n", " return \"Relevant: No — because there is no clear keyword overlap with the query.\"\n", "\n", "# Run top-3 similarity retrieval for each query and print readable output\n", "for query in test_queries:\n", " print(\"=\" * 90)\n", " print(f\"Query: {query}\")\n", "\n", " results = vectorstore.similarity_search(query, k=3)\n", " for i, doc in enumerate(results, start=1):\n", " chunk_text = doc.page_content.strip()\n", " preview = (chunk_text[:300] + \"...\") if len(chunk_text) > 300 else chunk_text\n", "\n", " print(f\"\\nResult {i} (trimmed):\")\n", " print(preview)\n", " print(relevance_note(query, chunk_text))\n", "\n", "print(\"\\nRetrieval test complete. (No LLM calls, no RAG chain built.)\")" ] }, { "cell_type": "code", "execution_count": 96, "id": "fe1ef0a6", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Loading weights: 100%|██████████| 103/103 [00:00<00:00, 2939.85it/s]\n", "\u001b[1mBertModel LOAD REPORT\u001b[0m from: sentence-transformers/all-MiniLM-L6-v2\n", "Key | Status | | \n", "------------------------+------------+--+-\n", "embeddings.position_ids | UNEXPECTED | | \n", "\n", "Notes:\n", "- UNEXPECTED:\tcan be ignored when loading from different task/architecture; not ok if you expect identical arch.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Active metadata filter: None\n", "BM25 candidate docs after filtering: 4979\n", "Hybrid retrieval check (vector vs ensemble top-3 overlap):\n", "- Query: 'What is the definition of X?' | overlap=3/3\n", "- Query: 'Explain concept Y.' | overlap=3/3\n", "- Query: 'How does Z work?' | overlap=3/3\n", "------------------------------------------------------------------------------------------\n", "Query: What is the definition of X?\n", "Answer: I don't know based on the provided context.\n", "------------------------------------------------------------------------------------------\n", "Query: Explain concept Y.\n", "Answer: I don't know based on the provided context.\n", "------------------------------------------------------------------------------------------\n", "Query: How does Z work?\n", "Answer: I don't know based on the provided context.\n", "------------------------------------------------------------------------------------------\n" ] } ], "source": [ "# Step 5 (Build RAG Chain): Hybrid retrieval + metadata-filtered retrieval + RetrievalQA\n", "import os\n", "from pathlib import Path\n", "from dotenv import load_dotenv\n", "from langchain_community.embeddings import HuggingFaceEmbeddings\n", "from langchain_community.vectorstores import Chroma\n", "from langchain_community.retrievers import BM25Retriever\n", "from langchain_openai import ChatOpenAI\n", "\n", "# EnsembleRetriever location differs across LangChain packaging layouts\n", "try:\n", " from langchain.retrievers import EnsembleRetriever\n", "except ModuleNotFoundError:\n", " from langchain_classic.retrievers import EnsembleRetriever\n", "\n", "# Compatibility imports for different LangChain package layouts\n", "try:\n", " from langchain.chains import RetrievalQA\n", " from langchain.prompts import ChatPromptTemplate\n", "except ModuleNotFoundError:\n", " from langchain_classic.chains import RetrievalQA\n", " from langchain_core.prompts import ChatPromptTemplate\n", "\n", "# Load environment variables from .env (works in notebooks even when cwd differs)\n", "load_dotenv()\n", "project_env = Path.cwd() / \".env\"\n", "if project_env.exists():\n", " load_dotenv(project_env, override=False)\n", "\n", "# Reconnect to the same embedding model and persisted Chroma collection from Step 3\n", "embedding_model = HuggingFaceEmbeddings(\n", " model_name=\"sentence-transformers/all-MiniLM-L6-v2\"\n", ")\n", "vectorstore = Chroma(\n", " collection_name=\"textbook_rag\",\n", " embedding_function=embedding_model,\n", " persist_directory=\"./chroma_db\",\n", ")\n", "\n", "# Use Step 2 chunks for BM25 and metadata filtering\n", "if \"chunks_500_100\" not in globals() or not chunks_500_100:\n", " raise ValueError(\"Run Step 2 first so `chunks_500_100` exists.\")\n", "\n", "# Optional metadata filters for retrieval. Set to None to disable a filter.\n", "active_filters = {\n", " \"source\": None, # Example: \"textbook_1.pdf\"\n", " \"section\": None, # Example: \"pages_1_20\"\n", " \"date\": None, # Example: \"2023-01-01\"\n", "}\n", "\n", "# Build a Chroma filter dict from enabled filters\n", "def build_chroma_filter(filters):\n", " return {k: v for k, v in filters.items() if v is not None}\n", "\n", "# Apply filters to in-memory chunks (used by BM25)\n", "def filter_documents_by_metadata(documents, filters):\n", " filtered = []\n", " for d in documents:\n", " keep = True\n", " for k, v in filters.items():\n", " if v is not None and d.metadata.get(k) != v:\n", " keep = False\n", " break\n", " if keep:\n", " filtered.append(d)\n", " return filtered\n", "\n", "active_filter_dict = build_chroma_filter(active_filters)\n", "filtered_docs_for_bm25 = filter_documents_by_metadata(chunks_500_100, active_filters)\n", "\n", "if not filtered_docs_for_bm25:\n", " raise ValueError(\"Metadata filters returned 0 docs. Relax `active_filters` and rerun Step 5.\")\n", "\n", "# Vector retriever with metadata filtering\n", "vector_search_kwargs = {\"k\": 3}\n", "if active_filter_dict:\n", " vector_search_kwargs[\"filter\"] = active_filter_dict\n", "\n", "retriever_vector = vectorstore.as_retriever(\n", " search_type=\"similarity\",\n", " search_kwargs=vector_search_kwargs,\n", ")\n", "\n", "# BM25 retriever on the same filtered subset\n", "retriever_bm25 = BM25Retriever.from_documents(filtered_docs_for_bm25)\n", "retriever_bm25.k = 3\n", "\n", "# Combine retrievers: tune weights for more keyword vs semantic influence\n", "retriever = EnsembleRetriever(\n", " retrievers=[retriever_vector, retriever_bm25],\n", " weights=[0.5, 0.5],\n", ")\n", "\n", "# Quick retrieval comparison on Step 4 queries\n", "queries_compare = test_queries if \"test_queries\" in globals() else [\n", " \"What is the definition of X?\",\n", " \"Explain concept Y.\",\n", " \"How does Z work?\",\n", "]\n", "\n", "def _doc_fingerprint(doc):\n", " return hash((doc.page_content or \"\").strip())\n", "\n", "print(f\"Active metadata filter: {active_filter_dict if active_filter_dict else 'None'}\")\n", "print(f\"BM25 candidate docs after filtering: {len(filtered_docs_for_bm25)}\")\n", "print(\"Hybrid retrieval check (vector vs ensemble top-3 overlap):\")\n", "for q in queries_compare:\n", " v_docs = retriever_vector.invoke(q)\n", " h_docs = retriever.invoke(q)\n", " v_fps = {_doc_fingerprint(d) for d in v_docs}\n", " h_fps = {_doc_fingerprint(d) for d in h_docs}\n", " overlap = len(v_fps & h_fps)\n", " print(f\"- Query: {q!r} | overlap={overlap}/3\")\n", "print(\"-\" * 90)\n", "\n", "# Define a chat prompt with an explicit system message\n", "custom_prompt = ChatPromptTemplate.from_messages([\n", " (\n", " \"system\",\n", " \"You are a warm, friendly, and helpful assistant. \"\n", " \"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", " \"For non-greeting questions, use ONLY the provided context. \"\n", " \"If the answer is not in the context, say: 'I don't know based on the provided context.'\",\n", " ),\n", " (\n", " \"human\",\n", " \"CONTEXT:\\nThe information in the two PDF documents textbook_1.pdf and textbook_2.pdf.\\n{context}\\n\\n\"\n", " \"QUESTION:\\n{question}\\n\\nANSWER:\",\n", " ),\n", "])\n", "\n", "# Initialize LLM after loading .env\n", "if not os.getenv(\"OPENAI_API_KEY\"):\n", " raise EnvironmentError(\"OPENAI_API_KEY is not set. Confirm .env is in the notebook working directory and restart/re-run this cell.\")\n", "\n", "llm = ChatOpenAI(model=\"gpt-3.5-turbo\", temperature=0.7)\n", "\n", "# Build RetrievalQA chain using 'stuff' strategy and custom prompt\n", "qa_chain = RetrievalQA.from_chain_type(\n", " llm=llm,\n", " chain_type=\"stuff\",\n", " retriever=retriever,\n", " return_source_documents=False,\n", " chain_type_kwargs={\"prompt\": custom_prompt},\n", ")\n", "\n", "# Reuse Step 4 queries when available; otherwise default placeholders\n", "queries = queries_compare\n", "\n", "# Run the same 3 queries and print answers cleanly\n", "for query in queries:\n", " result = qa_chain.invoke({\"query\": query})\n", " answer = result[\"result\"] if isinstance(result, dict) else str(result)\n", "\n", " print(f\"Query: {query}\")\n", " print(f\"Answer: {answer}\")\n", " print(\"-\" * 90)" ] }, { "cell_type": "code", "execution_count": 97, "id": "e676144f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "==============================================================================================================\n", "Step 6 Evaluation Results\n", "==============================================================================================================\n", "\n", "Q1: What is concept A?\n", "Retrieved relevant chunks: Yes\n", "Answer grounded in context: No\n", "Answer correct: No\n", "Generated answer: I don't know based on the provided context.\n", "--------------------------------------------------------------------------------------------------------------\n", "\n", "Q2: How does method B work?\n", "Retrieved relevant chunks: Yes\n", "Answer grounded in context: Yes\n", "Answer correct: No\n", "Generated answer: I don't know based on the provided context.\n", "--------------------------------------------------------------------------------------------------------------\n", "\n", "Q3: Define term C.\n", "Retrieved relevant chunks: Yes\n", "Answer grounded in context: Yes\n", "Answer correct: No\n", "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", "--------------------------------------------------------------------------------------------------------------\n", "\n", "Q4: What is the purpose of D?\n", "Retrieved relevant chunks: Yes\n", "Answer grounded in context: No\n", "Answer correct: No\n", "Generated answer: I don't know based on the provided context.\n", "--------------------------------------------------------------------------------------------------------------\n", "\n", "Q5: Explain relationship between E and F.\n", "Retrieved relevant chunks: Yes\n", "Answer grounded in context: No\n", "Answer correct: No\n", "Generated answer: I don't know based on the provided context.\n", "--------------------------------------------------------------------------------------------------------------\n", "Retrieval accuracy: 5/5\n", "Faithfulness accuracy: 2/5\n", "Correctness accuracy: 0/5\n" ] } ], "source": [ "# Step 6 (Evaluation): Evaluate retrieval relevance, grounding, and answer correctness\n", "\n", "# Ensure Step 5 objects exist\n", "if \"retriever\" not in globals() or \"qa_chain\" not in globals():\n", " raise ValueError(\"Run Step 5 first so `retriever` and `qa_chain` are available.\")\n", "\n", "# Small evaluation set (replace placeholders with your real questions/answers)\n", "eval_set = [\n", " {\n", " \"question\": \"What is concept A?\",\n", " \"gold_answer\": \"[Replace with known correct answer for concept A]\",\n", " \"reference_keywords\": [\"concept\", \"a\"],\n", " },\n", " {\n", " \"question\": \"How does method B work?\",\n", " \"gold_answer\": \"[Replace with known correct answer for method B]\",\n", " \"reference_keywords\": [\"method\", \"b\"],\n", " },\n", " {\n", " \"question\": \"Define term C.\",\n", " \"gold_answer\": \"[Replace with known correct definition for term C]\",\n", " \"reference_keywords\": [\"term\", \"c\", \"define\"],\n", " },\n", " {\n", " \"question\": \"What is the purpose of D?\",\n", " \"gold_answer\": \"[Replace with known purpose of D]\",\n", " \"reference_keywords\": [\"purpose\", \"d\"],\n", " },\n", " {\n", " \"question\": \"Explain relationship between E and F.\",\n", " \"gold_answer\": \"[Replace with known relationship between E and F]\",\n", " \"reference_keywords\": [\"relationship\", \"e\", \"f\"],\n", " },\n", "]\n", "\n", "# Lightweight helper to normalize text for simple heuristic checks\n", "def normalize(text):\n", " return \" \".join(text.lower().split())\n", "\n", "results = []\n", "retrieval_hits = 0\n", "faithfulness_hits = 0\n", "correctness_hits = 0\n", "\n", "# Evaluate each question: retriever-only first, then full RAG chain\n", "for item in eval_set:\n", " question = item[\"question\"]\n", " gold_answer = item[\"gold_answer\"]\n", " keywords = [k.lower() for k in item[\"reference_keywords\"]]\n", "\n", " # 1) Retriever-only pass\n", " retrieved_docs = retriever.invoke(question)\n", " retrieved_text = \"\\n\\n\".join(doc.page_content for doc in retrieved_docs)\n", " retrieved_text_norm = normalize(retrieved_text)\n", "\n", " retrieval_relevant = any(k in retrieved_text_norm for k in keywords)\n", " retrieval_hits += int(retrieval_relevant)\n", "\n", " # 2) Full RAG chain pass\n", " rag_output = qa_chain.invoke({\"query\": question})\n", " answer = rag_output[\"result\"] if isinstance(rag_output, dict) else str(rag_output)\n", " answer_norm = normalize(answer)\n", "\n", " # 3a) Faithfulness (grounded): answer terms should appear in retrieved context\n", " answer_tokens = [t for t in answer_norm.replace(\".\", \" \").replace(\",\", \" \").split() if len(t) > 3]\n", " overlap_count = sum(1 for t in set(answer_tokens) if t in retrieved_text_norm)\n", " grounded_in_context = overlap_count >= max(1, min(3, len(set(answer_tokens)) // 5 + 1))\n", " faithfulness_hits += int(grounded_in_context)\n", "\n", " # 3b) Correctness: heuristic check against user-known answer placeholder\n", " # Replace this logic later with your own strict grading based on real expected answers.\n", " if gold_answer.startswith(\"[Replace with\"):\n", " answer_correct = False\n", " else:\n", " gold_norm = normalize(gold_answer)\n", " answer_correct = gold_norm in answer_norm or answer_norm in gold_norm\n", " correctness_hits += int(answer_correct)\n", "\n", " results.append(\n", " {\n", " \"question\": question,\n", " \"retrieval_relevant\": retrieval_relevant,\n", " \"grounded_in_context\": grounded_in_context,\n", " \"answer_correct\": answer_correct,\n", " \"answer\": answer,\n", " }\n", " )\n", "\n", "# Print structured evaluation output\n", "print(\"=\" * 110)\n", "print(\"Step 6 Evaluation Results\")\n", "print(\"=\" * 110)\n", "for idx, row in enumerate(results, start=1):\n", " print(f\"\\nQ{idx}: {row['question']}\")\n", " print(f\"Retrieved relevant chunks: {'Yes' if row['retrieval_relevant'] else 'No'}\")\n", " print(f\"Answer grounded in context: {'Yes' if row['grounded_in_context'] else 'No'}\")\n", " print(f\"Answer correct: {'Yes' if row['answer_correct'] else 'No'}\")\n", " print(f\"Generated answer: {row['answer']}\")\n", " print(\"-\" * 110)\n", "\n", "# Compute and print assignment-required metrics\n", "n = len(eval_set)\n", "print(f\"Retrieval accuracy: {retrieval_hits}/{n}\")\n", "print(f\"Faithfulness accuracy: {faithfulness_hits}/{n}\")\n", "print(f\"Correctness accuracy: {correctness_hits}/{n}\")" ] }, { "cell_type": "code", "execution_count": 98, "id": "56c3e91d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "* Running on local URL: http://127.0.0.1:7868\n", "* To create a public link, set `share=True` in `launch()`.\n" ] }, { "data": { "text/html": [ "
" ], "text/plain": [ "