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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": 13,
|
| 6 |
+
"metadata": {
|
| 7 |
+
"execution": {
|
| 8 |
+
"iopub.execute_input": "2025-04-20T01:23:19.646469Z",
|
| 9 |
+
"iopub.status.busy": "2025-04-20T01:23:19.645910Z",
|
| 10 |
+
"iopub.status.idle": "2025-04-20T01:23:24.610737Z",
|
| 11 |
+
"shell.execute_reply": "2025-04-20T01:23:24.609596Z",
|
| 12 |
+
"shell.execute_reply.started": "2025-04-20T01:23:19.646437Z"
|
| 13 |
+
},
|
| 14 |
+
"trusted": true
|
| 15 |
+
},
|
| 16 |
+
"outputs": [],
|
| 17 |
+
"source": [
|
| 18 |
+
"!pip install -q langchain_community langchain langchain-google-genai faiss-cpu pypdf python-dotenv pandas scikit-learn sentence-transformers mlflow\n"
|
| 19 |
+
]
|
| 20 |
+
},
|
| 21 |
+
{
|
| 22 |
+
"cell_type": "markdown",
|
| 23 |
+
"metadata": {},
|
| 24 |
+
"source": [
|
| 25 |
+
"## Problem Statement\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"“How do I build an AI assistant that can reliably answer questions over my own private documents (PDFs, manuals, reports, etc.)—without exposing that content publicly?”\n",
|
| 28 |
+
"\n",
|
| 29 |
+
"- Pain Point: Traditional keyword search or “copy‑paste into ChatGPT” is brittle, unindexed, often leaks context, and doesn’t trace back to your source.\n",
|
| 30 |
+
"- GenAI Solution: Combine an embedding‑based vector store (for retrieval) with a generative LLM (for fluent answers). This let’s you:\n",
|
| 31 |
+
"1. Index your docs into a FAISS vector database via embeddings\n",
|
| 32 |
+
"2. Retrieve the top‑k most relevant passages at query time\n",
|
| 33 |
+
"3. Generate a concise, grounded answer that cites its source chunks"
|
| 34 |
+
]
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
"cell_type": "markdown",
|
| 38 |
+
"metadata": {},
|
| 39 |
+
"source": [
|
| 40 |
+
"## How to Solves It (Step‑by‑Step)\n",
|
| 41 |
+
"\n",
|
| 42 |
+
"1. Environment & MLflow Setup\n",
|
| 43 |
+
"- Installs/initializes all required libraries (LangChain, Gemini SDK, FAISS, MLflow).\n",
|
| 44 |
+
"- Starts an MLflow experiment to track chunk‑size, overlap, query results, and future feedback.\n",
|
| 45 |
+
"\n",
|
| 46 |
+
"2. Document Ingestion & Chunking\n",
|
| 47 |
+
"- Loads PDFs/TXT/DOCX/CSV with LangChain’s loaders.\n",
|
| 48 |
+
"- Splits them into ~1 000‑token overlapping “chunks” for granular retrieval.\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"3. Embedding & Vector Store\n",
|
| 51 |
+
"- Uses GoogleGenerativeAIEmbeddings to turn each chunk into a vector.\n",
|
| 52 |
+
"- Builds a FAISS index for sub‑second similarity search.\n",
|
| 53 |
+
"\n",
|
| 54 |
+
"4. Retrieval‑QA Chain Construction\n",
|
| 55 |
+
"- Wires a RetrievalQA chain:\n",
|
| 56 |
+
" - Retriever: FAISS top‑k lookup\n",
|
| 57 |
+
" - LLM: Gemini chat model with a prompt that “Use ONLY this context”\n",
|
| 58 |
+
"- Ensures the answer is always grounded in the retrieved snippets.\n",
|
| 59 |
+
"\n",
|
| 60 |
+
"5. Interactive Q&A Loop\n",
|
| 61 |
+
"- Drops you into a REPL: type any question (or exit) and get back:\n",
|
| 62 |
+
" - A generative answer\n",
|
| 63 |
+
" - The exact source snippets that informed the answer"
|
| 64 |
+
]
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
"cell_type": "code",
|
| 68 |
+
"execution_count": 15,
|
| 69 |
+
"metadata": {
|
| 70 |
+
"execution": {
|
| 71 |
+
"iopub.execute_input": "2025-04-20T01:23:32.378002Z",
|
| 72 |
+
"iopub.status.busy": "2025-04-20T01:23:32.377672Z",
|
| 73 |
+
"iopub.status.idle": "2025-04-20T01:23:32.386346Z",
|
| 74 |
+
"shell.execute_reply": "2025-04-20T01:23:32.384681Z",
|
| 75 |
+
"shell.execute_reply.started": "2025-04-20T01:23:32.377980Z"
|
| 76 |
+
},
|
| 77 |
+
"trusted": true
|
| 78 |
+
},
|
| 79 |
+
"outputs": [],
|
| 80 |
+
"source": [
|
| 81 |
+
"# Install required packages\n",
|
| 82 |
+
"\n",
|
| 83 |
+
"import os\n",
|
| 84 |
+
"import tempfile\n",
|
| 85 |
+
"import pandas as pd\n",
|
| 86 |
+
"import numpy as np\n",
|
| 87 |
+
"import uuid\n",
|
| 88 |
+
"import mlflow\n",
|
| 89 |
+
"from datetime import datetime\n",
|
| 90 |
+
"from typing import List, Dict, Any\n",
|
| 91 |
+
"\n",
|
| 92 |
+
"# Document processing\n",
|
| 93 |
+
"from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
|
| 94 |
+
"from langchain_community.document_loaders import (\n",
|
| 95 |
+
" PyPDFLoader, \n",
|
| 96 |
+
" TextLoader, \n",
|
| 97 |
+
" CSVLoader,\n",
|
| 98 |
+
" UnstructuredWordDocumentLoader\n",
|
| 99 |
+
")\n",
|
| 100 |
+
"\n",
|
| 101 |
+
"# Gemini and embeddings\n",
|
| 102 |
+
"import google.generativeai as genai\n",
|
| 103 |
+
"from langchain_google_genai import ChatGoogleGenerativeAI, GoogleGenerativeAIEmbeddings\n",
|
| 104 |
+
"from langchain_community.vectorstores import FAISS\n",
|
| 105 |
+
"from langchain.prompts import PromptTemplate\n",
|
| 106 |
+
"from langchain.chains import RetrievalQA\n",
|
| 107 |
+
"from IPython.display import display, Markdown"
|
| 108 |
+
]
|
| 109 |
+
},
|
| 110 |
+
{
|
| 111 |
+
"cell_type": "markdown",
|
| 112 |
+
"metadata": {},
|
| 113 |
+
"source": [
|
| 114 |
+
"### 1. Initialize MLflow & Define Core RAG Utilities\n",
|
| 115 |
+
"\n",
|
| 116 |
+
"In this section:\n",
|
| 117 |
+
"\n",
|
| 118 |
+
"- **Set up MLflow** for experiment and run tracking (`mlflow.set_experiment`).\n",
|
| 119 |
+
"- **Load documents** of various formats (`.pdf`, `.txt`, `.docx`, `.csv`) into LangChain.\n",
|
| 120 |
+
"- **Chunk** each document into overlapping text segments for better retrieval.\n",
|
| 121 |
+
"- **Embed** these chunks with Gemini embeddings and build a FAISS vector store.\n",
|
| 122 |
+
"- **Instantiate** a RetrievalQA chain using the Gemini LLM, wired to our vector store, so we can ask context‑grounded questions.\n"
|
| 123 |
+
]
|
| 124 |
+
},
|
| 125 |
+
{
|
| 126 |
+
"cell_type": "code",
|
| 127 |
+
"execution_count": 16,
|
| 128 |
+
"metadata": {
|
| 129 |
+
"execution": {
|
| 130 |
+
"iopub.execute_input": "2025-04-20T01:24:14.611400Z",
|
| 131 |
+
"iopub.status.busy": "2025-04-20T01:24:14.611037Z",
|
| 132 |
+
"iopub.status.idle": "2025-04-20T01:24:14.631546Z",
|
| 133 |
+
"shell.execute_reply": "2025-04-20T01:24:14.630426Z",
|
| 134 |
+
"shell.execute_reply.started": "2025-04-20T01:24:14.611377Z"
|
| 135 |
+
},
|
| 136 |
+
"trusted": true
|
| 137 |
+
},
|
| 138 |
+
"outputs": [],
|
| 139 |
+
"source": [
|
| 140 |
+
"# Set up MLflow\n",
|
| 141 |
+
"mlflow.set_experiment(\"document-qa-gemini\")\n",
|
| 142 |
+
"\n",
|
| 143 |
+
"# Document processing functions\n",
|
| 144 |
+
"def load_document(file_path):\n",
|
| 145 |
+
" \"\"\"Load document based on file extension\"\"\"\n",
|
| 146 |
+
" _, file_extension = os.path.splitext(file_path)\n",
|
| 147 |
+
" \n",
|
| 148 |
+
" if file_extension.lower() == '.pdf':\n",
|
| 149 |
+
" loader = PyPDFLoader(file_path)\n",
|
| 150 |
+
" elif file_extension.lower() == '.txt':\n",
|
| 151 |
+
" loader = TextLoader(file_path)\n",
|
| 152 |
+
" elif file_extension.lower() == '.docx':\n",
|
| 153 |
+
" loader = UnstructuredWordDocumentLoader(file_path)\n",
|
| 154 |
+
" elif file_extension.lower() == '.csv':\n",
|
| 155 |
+
" loader = CSVLoader(file_path)\n",
|
| 156 |
+
" else:\n",
|
| 157 |
+
" raise ValueError(f\"Unsupported file format: {file_extension}\")\n",
|
| 158 |
+
" \n",
|
| 159 |
+
" return loader.load()\n",
|
| 160 |
+
"\n",
|
| 161 |
+
"def chunk_documents(documents, chunk_size=1000, chunk_overlap=200):\n",
|
| 162 |
+
" \"\"\"Split documents into chunks\"\"\"\n",
|
| 163 |
+
" text_splitter = RecursiveCharacterTextSplitter(\n",
|
| 164 |
+
" chunk_size=chunk_size,\n",
|
| 165 |
+
" chunk_overlap=chunk_overlap,\n",
|
| 166 |
+
" length_function=len\n",
|
| 167 |
+
" )\n",
|
| 168 |
+
" chunks = text_splitter.split_documents(documents)\n",
|
| 169 |
+
" return chunks\n",
|
| 170 |
+
"\n",
|
| 171 |
+
"def create_vector_store(chunks, api_key):\n",
|
| 172 |
+
" \"\"\"Create a vector store from document chunks\"\"\"\n",
|
| 173 |
+
" os.environ[\"GOOGLE_API_KEY\"] = api_key\n",
|
| 174 |
+
" embeddings = GoogleGenerativeAIEmbeddings(model=\"models/embedding-001\")\n",
|
| 175 |
+
" vector_store = FAISS.from_documents(chunks, embeddings)\n",
|
| 176 |
+
" return vector_store\n",
|
| 177 |
+
"\n",
|
| 178 |
+
"def get_qa_chain(vector_store, api_key, model_name=\"gemini-1.5-pro\"):\n",
|
| 179 |
+
" \"\"\"Create a question-answering chain with Gemini model\"\"\"\n",
|
| 180 |
+
" os.environ[\"GOOGLE_API_KEY\"] = api_key\n",
|
| 181 |
+
" \n",
|
| 182 |
+
" llm = ChatGoogleGenerativeAI(model=model_name, temperature=0.2)\n",
|
| 183 |
+
" \n",
|
| 184 |
+
" template = \"\"\"\n",
|
| 185 |
+
" You are a helpful AI assistant trained to answer questions based on provided context.\n",
|
| 186 |
+
" Use only the following context to answer the question. If you don't know the answer based on \n",
|
| 187 |
+
" the context, say \"I don't have enough information to answer this question\" - don't make up information.\n",
|
| 188 |
+
" \n",
|
| 189 |
+
" Context:\n",
|
| 190 |
+
" {context}\n",
|
| 191 |
+
" \n",
|
| 192 |
+
" Question: {question}\n",
|
| 193 |
+
" \n",
|
| 194 |
+
" Answer:\n",
|
| 195 |
+
" \"\"\"\n",
|
| 196 |
+
" \n",
|
| 197 |
+
" QA_CHAIN_PROMPT = PromptTemplate(\n",
|
| 198 |
+
" input_variables=[\"context\", \"question\"],\n",
|
| 199 |
+
" template=template\n",
|
| 200 |
+
" )\n",
|
| 201 |
+
" \n",
|
| 202 |
+
" qa_chain = RetrievalQA.from_chain_type(\n",
|
| 203 |
+
" llm=llm,\n",
|
| 204 |
+
" chain_type=\"stuff\",\n",
|
| 205 |
+
" retriever=vector_store.as_retriever(search_kwargs={\"k\": 4}),\n",
|
| 206 |
+
" chain_type_kwargs={\"prompt\": QA_CHAIN_PROMPT},\n",
|
| 207 |
+
" return_source_documents=True\n",
|
| 208 |
+
" )\n",
|
| 209 |
+
" \n",
|
| 210 |
+
" return qa_chain"
|
| 211 |
+
]
|
| 212 |
+
},
|
| 213 |
+
{
|
| 214 |
+
"cell_type": "markdown",
|
| 215 |
+
"metadata": {},
|
| 216 |
+
"source": [
|
| 217 |
+
"### 2. Define the DocumentQASystem Class\n",
|
| 218 |
+
"\n",
|
| 219 |
+
"Encapsulate the entire RAG workflow into a single, reusable class:\n",
|
| 220 |
+
"\n",
|
| 221 |
+
"- **`__init__`** \n",
|
| 222 |
+
" - Configures the Gemini API key and MLflow experiment session \n",
|
| 223 |
+
" - Initializes internal state (vector store, QA chain, session ID, chunk settings, history)\n",
|
| 224 |
+
"\n",
|
| 225 |
+
"- **`process_documents(file_paths, chunk_size, chunk_overlap)`** \n",
|
| 226 |
+
" 1. Loads each file (PDF, TXT, DOCX, CSV) \n",
|
| 227 |
+
" 2. Splits text into overlapping chunks for retrieval \n",
|
| 228 |
+
" 3. Creates embeddings & builds a FAISS vector store \n",
|
| 229 |
+
" 4. Instantiates a RetrievalQA chain with Gemini \n",
|
| 230 |
+
" 5. Logs processing parameters (chunk size, file count, etc.) to MLflow \n",
|
| 231 |
+
" 6. Returns the total number of chunks indexed \n",
|
| 232 |
+
"\n",
|
| 233 |
+
"- **`ask_question(question, track_metrics=True)`** \n",
|
| 234 |
+
" 1. Records the user question in `conversation_history` \n",
|
| 235 |
+
" 2. Retrieves the top‐k chunks and generates an answer via the QA chain \n",
|
| 236 |
+
" 3. Formats and saves source snippets \n",
|
| 237 |
+
" 4. Appends the assistant’s response to history \n",
|
| 238 |
+
" 5. Optionally logs the question, answer, and source metadata to MLflow \n",
|
| 239 |
+
" 6. Returns a dict containing `answer` and `sources`\n",
|
| 240 |
+
"\n",
|
| 241 |
+
"Finally, create an instance of `DocumentQASystem`, point it at the law‑book PDF, and kick off document processing. \n"
|
| 242 |
+
]
|
| 243 |
+
},
|
| 244 |
+
{
|
| 245 |
+
"cell_type": "code",
|
| 246 |
+
"execution_count": 17,
|
| 247 |
+
"metadata": {
|
| 248 |
+
"execution": {
|
| 249 |
+
"iopub.execute_input": "2025-04-20T01:24:21.390309Z",
|
| 250 |
+
"iopub.status.busy": "2025-04-20T01:24:21.389935Z",
|
| 251 |
+
"iopub.status.idle": "2025-04-20T01:25:33.055563Z",
|
| 252 |
+
"shell.execute_reply": "2025-04-20T01:25:33.054367Z",
|
| 253 |
+
"shell.execute_reply.started": "2025-04-20T01:24:21.390260Z"
|
| 254 |
+
},
|
| 255 |
+
"trusted": true
|
| 256 |
+
},
|
| 257 |
+
"outputs": [
|
| 258 |
+
{
|
| 259 |
+
"name": "stdout",
|
| 260 |
+
"output_type": "stream",
|
| 261 |
+
"text": [
|
| 262 |
+
"Processed 2833 chunks from 1 documents\n"
|
| 263 |
+
]
|
| 264 |
+
}
|
| 265 |
+
],
|
| 266 |
+
"source": [
|
| 267 |
+
"\n",
|
| 268 |
+
"class DocumentQASystem:\n",
|
| 269 |
+
" \"\"\"Main class to handle document Q&A with evaluation tracking\"\"\"\n",
|
| 270 |
+
" \n",
|
| 271 |
+
" def __init__(self, api_key):\n",
|
| 272 |
+
" self.api_key = api_key\n",
|
| 273 |
+
" self.vector_store = None\n",
|
| 274 |
+
" self.qa_chain = None\n",
|
| 275 |
+
" self.session_id = str(uuid.uuid4())\n",
|
| 276 |
+
" self.chunk_size = 1000\n",
|
| 277 |
+
" self.chunk_overlap = 200\n",
|
| 278 |
+
" self.conversation_history = []\n",
|
| 279 |
+
" os.environ[\"GOOGLE_API_KEY\"] = api_key\n",
|
| 280 |
+
" genai.configure(api_key=api_key)\n",
|
| 281 |
+
" \n",
|
| 282 |
+
" def process_documents(self, file_paths, chunk_size=1000, chunk_overlap=200):\n",
|
| 283 |
+
" \"\"\"Process multiple documents and create vector store\"\"\"\n",
|
| 284 |
+
" self.chunk_size = chunk_size\n",
|
| 285 |
+
" self.chunk_overlap = chunk_overlap\n",
|
| 286 |
+
" \n",
|
| 287 |
+
" all_chunks = []\n",
|
| 288 |
+
" for file_path in file_paths:\n",
|
| 289 |
+
" documents = load_document(file_path)\n",
|
| 290 |
+
" chunks = chunk_documents(documents, chunk_size, chunk_overlap)\n",
|
| 291 |
+
" all_chunks.extend(chunks)\n",
|
| 292 |
+
" \n",
|
| 293 |
+
" self.vector_store = create_vector_store(all_chunks, self.api_key)\n",
|
| 294 |
+
" self.qa_chain = get_qa_chain(self.vector_store, self.api_key)\n",
|
| 295 |
+
" \n",
|
| 296 |
+
" # Log document processing in MLflow\n",
|
| 297 |
+
" with mlflow.start_run():\n",
|
| 298 |
+
" mlflow.log_param(\"chunk_size\", chunk_size)\n",
|
| 299 |
+
" mlflow.log_param(\"chunk_overlap\", chunk_overlap)\n",
|
| 300 |
+
" mlflow.log_param(\"document_count\", len(file_paths))\n",
|
| 301 |
+
" mlflow.log_param(\"chunk_count\", len(all_chunks))\n",
|
| 302 |
+
" mlflow.log_param(\"session_id\", self.session_id)\n",
|
| 303 |
+
" \n",
|
| 304 |
+
" return len(all_chunks)\n",
|
| 305 |
+
" \n",
|
| 306 |
+
" def ask_question(self, question, track_metrics=True):\n",
|
| 307 |
+
" \"\"\"Ask a question about the loaded documents\"\"\"\n",
|
| 308 |
+
" if not self.vector_store or not self.qa_chain:\n",
|
| 309 |
+
" raise ValueError(\"Documents haven't been processed yet. Call process_documents first.\")\n",
|
| 310 |
+
" \n",
|
| 311 |
+
" # Add question to conversation history\n",
|
| 312 |
+
" self.conversation_history.append({\n",
|
| 313 |
+
" \"role\": \"user\",\n",
|
| 314 |
+
" \"content\": question,\n",
|
| 315 |
+
" \"timestamp\": datetime.now().isoformat()\n",
|
| 316 |
+
" })\n",
|
| 317 |
+
" \n",
|
| 318 |
+
" # Get answer from QA chain\n",
|
| 319 |
+
" response = self.qa_chain.invoke({\"query\": question})\n",
|
| 320 |
+
" answer = response[\"result\"]\n",
|
| 321 |
+
" source_docs = response[\"source_documents\"]\n",
|
| 322 |
+
" \n",
|
| 323 |
+
" # Format sources\n",
|
| 324 |
+
" sources = []\n",
|
| 325 |
+
" for i, doc in enumerate(source_docs):\n",
|
| 326 |
+
" source_text = doc.page_content[:200] + \"...\" if len(doc.page_content) > 200 else doc.page_content\n",
|
| 327 |
+
" sources.append(f\"Source {i+1}: {source_text}\")\n",
|
| 328 |
+
" \n",
|
| 329 |
+
" # Add response to conversation history\n",
|
| 330 |
+
" self.conversation_history.append({\n",
|
| 331 |
+
" \"role\": \"assistant\",\n",
|
| 332 |
+
" \"content\": answer,\n",
|
| 333 |
+
" \"sources\": sources,\n",
|
| 334 |
+
" \"timestamp\": datetime.now().isoformat()\n",
|
| 335 |
+
" })\n",
|
| 336 |
+
" \n",
|
| 337 |
+
" # Track metrics in MLflow\n",
|
| 338 |
+
" if track_metrics:\n",
|
| 339 |
+
" with mlflow.start_run():\n",
|
| 340 |
+
" mlflow.log_param(\"question\", question)\n",
|
| 341 |
+
" mlflow.log_param(\"session_id\", self.session_id)\n",
|
| 342 |
+
" mlflow.log_text(answer, \"answer.txt\")\n",
|
| 343 |
+
" mlflow.log_dict({\"sources\": [doc.page_content for doc in source_docs]}, \"sources.json\")\n",
|
| 344 |
+
" \n",
|
| 345 |
+
" return {\n",
|
| 346 |
+
" \"answer\": answer,\n",
|
| 347 |
+
" \"sources\": sources\n",
|
| 348 |
+
" }\n",
|
| 349 |
+
" \n",
|
| 350 |
+
"qa_system = DocumentQASystem(api_key)\n",
|
| 351 |
+
"\n",
|
| 352 |
+
"law_book_path = \"/kaggle/input/international-law-handbook/book_1.pdf\"\n",
|
| 353 |
+
"sample_files = [law_book_path]\n",
|
| 354 |
+
"\n",
|
| 355 |
+
"# Process documents\n",
|
| 356 |
+
"chunk_count = qa_system.process_documents(sample_files)\n",
|
| 357 |
+
"print(f\"Processed {chunk_count} chunks from {len(sample_files)} documents\")"
|
| 358 |
+
]
|
| 359 |
+
},
|
| 360 |
+
{
|
| 361 |
+
"cell_type": "markdown",
|
| 362 |
+
"metadata": {},
|
| 363 |
+
"source": [
|
| 364 |
+
"### 3. Start the Interactive Q&A Session\n",
|
| 365 |
+
"\n",
|
| 366 |
+
"Enter a simple REPL loop that:\n",
|
| 367 |
+
"\n",
|
| 368 |
+
"1. **Prompts** user to type a question about the indexed documents (or `exit` to quit) \n",
|
| 369 |
+
"2. **Invokes** `qa_system.ask_question(...)` to retrieve an answer and source snippets \n",
|
| 370 |
+
"3. **Prints** the model’s answer under “----- Answer -----” \n",
|
| 371 |
+
"4. **Lists** each retrieved source under “----- Sources -----” for full transparency \n",
|
| 372 |
+
"\n",
|
| 373 |
+
"This lets user to explore the dataset law book in real time—just type a question and see instant, grounded responses! \n"
|
| 374 |
+
]
|
| 375 |
+
},
|
| 376 |
+
{
|
| 377 |
+
"cell_type": "code",
|
| 378 |
+
"execution_count": 19,
|
| 379 |
+
"metadata": {
|
| 380 |
+
"execution": {
|
| 381 |
+
"iopub.execute_input": "2025-04-20T01:27:27.037633Z",
|
| 382 |
+
"iopub.status.busy": "2025-04-20T01:27:27.037240Z",
|
| 383 |
+
"iopub.status.idle": "2025-04-20T01:27:47.310686Z",
|
| 384 |
+
"shell.execute_reply": "2025-04-20T01:27:47.309818Z",
|
| 385 |
+
"shell.execute_reply.started": "2025-04-20T01:27:27.037607Z"
|
| 386 |
+
},
|
| 387 |
+
"trusted": true
|
| 388 |
+
},
|
| 389 |
+
"outputs": [
|
| 390 |
+
{
|
| 391 |
+
"name": "stdout",
|
| 392 |
+
"output_type": "stream",
|
| 393 |
+
"text": [
|
| 394 |
+
"\n",
|
| 395 |
+
"Ask a question about law (or type 'exit' to quit): Under what conditions can a treaty be terminated?\n"
|
| 396 |
+
]
|
| 397 |
+
},
|
| 398 |
+
{
|
| 399 |
+
"name": "stdout",
|
| 400 |
+
"output_type": "stream",
|
| 401 |
+
"text": [
|
| 402 |
+
"\n",
|
| 403 |
+
" your Question is: Under what conditions can a treaty be terminated?\n",
|
| 404 |
+
"\n",
|
| 405 |
+
"--------------------------- Answer ---------------------------------\n",
|
| 406 |
+
"A treaty can be terminated or a party can withdraw in the following ways:\n",
|
| 407 |
+
"\n",
|
| 408 |
+
"1. In conformity with the treaty's provisions.\n",
|
| 409 |
+
"2. By consent of all parties after consultation with the contracting States and contracting organizations.\n",
|
| 410 |
+
"3. If it conflicts with a new peremptory norm of general international law.\n",
|
| 411 |
+
"4. Due to a fundamental change of circumstances.\n",
|
| 412 |
+
"5. If the parties intended to admit the possibility of denunciation or withdrawal, or if such a right can be implied by the nature of the treaty, provided twelve months' notice is given.\n",
|
| 413 |
+
"\n",
|
| 414 |
+
"----- Sources -----\n",
|
| 415 |
+
"Source 1: States and international organizations: treaties 87\n",
|
| 416 |
+
"Article 56. Denunciation of or withdrawal from a treaty containing \n",
|
| 417 |
+
"no provision regard ing termination, denunciation or withdrawal\n",
|
| 418 |
+
"1. A treaty whi...\n",
|
| 419 |
+
"---\n",
|
| 420 |
+
"Source 2: States and international organizations: treaties 89\n",
|
| 421 |
+
"4. If, under the foregoing paragraphs, a party may invoke a fundamental change of circum -\n",
|
| 422 |
+
"stances as a ground for terminating or withdrawing from ...\n",
|
| 423 |
+
"---\n",
|
| 424 |
+
"Source 3: Convention on the law of treaties 47\n",
|
| 425 |
+
"5. In cases falling under articles 51, 52 and 53, no separation of the provisions of the treaty is \n",
|
| 426 |
+
"permitted.\n",
|
| 427 |
+
"Article 45. Loss of a right to invoke a ground for i...\n",
|
| 428 |
+
"---\n",
|
| 429 |
+
"Source 4: A treaty is void if, at the time of its conclusion, it conflicts with a peremptory norm of general \n",
|
| 430 |
+
"international law. For the purposes of the present Convention, a peremptory norm of general inter -\n",
|
| 431 |
+
"...\n",
|
| 432 |
+
"---\n"
|
| 433 |
+
]
|
| 434 |
+
},
|
| 435 |
+
{
|
| 436 |
+
"name": "stdout",
|
| 437 |
+
"output_type": "stream",
|
| 438 |
+
"text": [
|
| 439 |
+
"\n",
|
| 440 |
+
"Ask a question about law (or type 'exit' to quit): what is python\n"
|
| 441 |
+
]
|
| 442 |
+
},
|
| 443 |
+
{
|
| 444 |
+
"name": "stdout",
|
| 445 |
+
"output_type": "stream",
|
| 446 |
+
"text": [
|
| 447 |
+
"\n",
|
| 448 |
+
" your Question is: what is python\n",
|
| 449 |
+
"\n",
|
| 450 |
+
"--------------------------- Answer ---------------------------------\n",
|
| 451 |
+
"I don't have enough information to answer this question\n",
|
| 452 |
+
"\n",
|
| 453 |
+
"----- Sources -----\n",
|
| 454 |
+
"Source 1: 1. For the purposes of this Convention, the term “torture” means any act by which severe pain \n",
|
| 455 |
+
"or suffering, whether physical or mental, is intentionally inflicted on a person for such purposes as \n",
|
| 456 |
+
"ob...\n",
|
| 457 |
+
"---\n",
|
| 458 |
+
"Source 2: tive and alternative modes, means and formats of communication, including accessible information \n",
|
| 459 |
+
"and communication technology;\n",
|
| 460 |
+
"“Language” includes spoken and signed languages and other forms of non-s...\n",
|
| 461 |
+
"---\n",
|
| 462 |
+
"Source 3: governed by international law, whether embodied in a single instrument or in two or more related \n",
|
| 463 |
+
"instruments and whatever its particular designation;\n",
|
| 464 |
+
"(b) “ratification,” “acceptance,” “approval” and ...\n",
|
| 465 |
+
"---\n",
|
| 466 |
+
"Source 4: offence was committed.\n",
|
| 467 |
+
"article 12\n",
|
| 468 |
+
"No one shall be subjected to arbitrary interference with his privacy, family, home or corre -\n",
|
| 469 |
+
"spondence, nor to attacks upon his honour and reputation. Everyone has t...\n",
|
| 470 |
+
"---\n"
|
| 471 |
+
]
|
| 472 |
+
},
|
| 473 |
+
{
|
| 474 |
+
"name": "stdout",
|
| 475 |
+
"output_type": "stream",
|
| 476 |
+
"text": [
|
| 477 |
+
"\n",
|
| 478 |
+
"Ask a question about law (or type 'exit' to quit): exit\n"
|
| 479 |
+
]
|
| 480 |
+
}
|
| 481 |
+
],
|
| 482 |
+
"source": [
|
| 483 |
+
"# Interactive Q&A loop\n",
|
| 484 |
+
"\n",
|
| 485 |
+
"while True:\n",
|
| 486 |
+
" question = input(\"\\nAsk a question about law (or type 'exit' to quit): \")\n",
|
| 487 |
+
" if question.lower() == 'exit':\n",
|
| 488 |
+
" break\n",
|
| 489 |
+
" \n",
|
| 490 |
+
" result = qa_system.ask_question(question)\n",
|
| 491 |
+
" print(\"\\n your Question is: \",question)\n",
|
| 492 |
+
" print(\"\\n--------------------------- Answer ---------------------------------\")\n",
|
| 493 |
+
" print(result[\"answer\"])\n",
|
| 494 |
+
" print(\"\\n----- Sources -----\")\n",
|
| 495 |
+
" for source in result[\"sources\"]:\n",
|
| 496 |
+
" print(source)\n",
|
| 497 |
+
" print(\"---\")\n",
|
| 498 |
+
" \n",
|
| 499 |
+
" "
|
| 500 |
+
]
|
| 501 |
+
},
|
| 502 |
+
{
|
| 503 |
+
"cell_type": "code",
|
| 504 |
+
"execution_count": null,
|
| 505 |
+
"metadata": {
|
| 506 |
+
"trusted": true
|
| 507 |
+
},
|
| 508 |
+
"outputs": [],
|
| 509 |
+
"source": []
|
| 510 |
+
}
|
| 511 |
+
],
|
| 512 |
+
"metadata": {
|
| 513 |
+
"kaggle": {
|
| 514 |
+
"accelerator": "none",
|
| 515 |
+
"dataSources": [
|
| 516 |
+
{
|
| 517 |
+
"datasetId": 7192735,
|
| 518 |
+
"sourceId": 11476474,
|
| 519 |
+
"sourceType": "datasetVersion"
|
| 520 |
+
}
|
| 521 |
+
],
|
| 522 |
+
"dockerImageVersionId": 31012,
|
| 523 |
+
"isGpuEnabled": false,
|
| 524 |
+
"isInternetEnabled": true,
|
| 525 |
+
"language": "python",
|
| 526 |
+
"sourceType": "notebook"
|
| 527 |
+
},
|
| 528 |
+
"kernelspec": {
|
| 529 |
+
"display_name": "Python 3",
|
| 530 |
+
"language": "python",
|
| 531 |
+
"name": "python3"
|
| 532 |
+
},
|
| 533 |
+
"language_info": {
|
| 534 |
+
"codemirror_mode": {
|
| 535 |
+
"name": "ipython",
|
| 536 |
+
"version": 3
|
| 537 |
+
},
|
| 538 |
+
"file_extension": ".py",
|
| 539 |
+
"mimetype": "text/x-python",
|
| 540 |
+
"name": "python",
|
| 541 |
+
"nbconvert_exporter": "python",
|
| 542 |
+
"pygments_lexer": "ipython3",
|
| 543 |
+
"version": "3.11.11"
|
| 544 |
+
}
|
| 545 |
+
},
|
| 546 |
+
"nbformat": 4,
|
| 547 |
+
"nbformat_minor": 4
|
| 548 |
+
}
|