Instructions to use Navaneeth-14/rag-hackathon-app with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- llama.cpp
How to use Navaneeth-14/rag-hackathon-app with llama.cpp:
Install (macOS, Linux)
curl -LsSf https://llama.app/install.sh | sh # Start a local OpenAI-compatible server with a web UI: llama serve -hf Navaneeth-14/rag-hackathon-app:Q4_K_M # Run inference directly in the terminal: llama cli -hf Navaneeth-14/rag-hackathon-app:Q4_K_M
Install from WinGet (Windows)
winget install llama.cpp # Start a local OpenAI-compatible server with a web UI: llama serve -hf Navaneeth-14/rag-hackathon-app:Q4_K_M # Run inference directly in the terminal: llama cli -hf Navaneeth-14/rag-hackathon-app:Q4_K_M
Use pre-built binary
# Download pre-built binary from: # https://github.com/ggerganov/llama.cpp/releases # Start a local OpenAI-compatible server with a web UI: ./llama-server -hf Navaneeth-14/rag-hackathon-app:Q4_K_M # Run inference directly in the terminal: ./llama-cli -hf Navaneeth-14/rag-hackathon-app:Q4_K_M
Build from source code
git clone https://github.com/ggerganov/llama.cpp.git cd llama.cpp cmake -B build cmake --build build -j --target llama-server llama-cli # Start a local OpenAI-compatible server with a web UI: ./build/bin/llama-server -hf Navaneeth-14/rag-hackathon-app:Q4_K_M # Run inference directly in the terminal: ./build/bin/llama-cli -hf Navaneeth-14/rag-hackathon-app:Q4_K_M
Use Docker
docker model run hf.co/Navaneeth-14/rag-hackathon-app:Q4_K_M
- LM Studio
- Jan
- Ollama
How to use Navaneeth-14/rag-hackathon-app with Ollama:
ollama run hf.co/Navaneeth-14/rag-hackathon-app:Q4_K_M
- Unsloth Studio
How to use Navaneeth-14/rag-hackathon-app with Unsloth Studio:
Install Unsloth Studio (macOS, Linux, WSL)
curl -fsSL https://unsloth.ai/install.sh | sh # Run unsloth studio unsloth studio -H 0.0.0.0 -p 8888 # Then open http://localhost:8888 in your browser # Search for Navaneeth-14/rag-hackathon-app to start chatting
Install Unsloth Studio (Windows)
irm https://unsloth.ai/install.ps1 | iex # Run unsloth studio unsloth studio -H 0.0.0.0 -p 8888 # Then open http://localhost:8888 in your browser # Search for Navaneeth-14/rag-hackathon-app to start chatting
Using HuggingFace Spaces for Unsloth
# No setup required # Open https://huggingface.co/spaces/unsloth/studio in your browser # Search for Navaneeth-14/rag-hackathon-app to start chatting
- Docker Model Runner
How to use Navaneeth-14/rag-hackathon-app with Docker Model Runner:
docker model run hf.co/Navaneeth-14/rag-hackathon-app:Q4_K_M
- Lemonade
How to use Navaneeth-14/rag-hackathon-app with Lemonade:
Pull the model
# Download Lemonade from https://lemonade-server.ai/ lemonade pull Navaneeth-14/rag-hackathon-app:Q4_K_M
Run and chat with the model
lemonade run user.rag-hackathon-app-Q4_K_M
List all available models
lemonade list
- Atomic Chat
File size: 16,765 Bytes
09281fe | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 | """
Comprehensive RAG System Demo
Demonstrates all features of the RAG system including document ingestion, query processing, and audit trail
"""
import os
import json
import time
from pathlib import Path
from rag_system_gpu import RAGSystem
def print_section(title):
"""Print a formatted section header"""
print("\n" + "="*60)
print(f" {title}")
print("="*60)
def print_subsection(title):
"""Print a formatted subsection header"""
print(f"\n--- {title} ---")
def demo_document_ingestion():
"""Interactive document ingestion with file upload from anywhere"""
print_section("DOCUMENT INGESTION")
try:
rag_system = RAGSystem(use_gpu=True) # Use GPU for better performance
print("β
GPU-optimized RAG system initialized successfully")
except Exception as e:
print(f"β Failed to initialize RAG system: {e}")
print("π‘ This might be due to missing model file or dependencies")
return None
print_subsection("PDF Document Upload")
print("π‘ Please provide the path to your PDF document from anywhere on your system.")
print("π‘ Supported formats: PDF files")
print("π‘ Type 'sample' to use the default sample.pdf (if available)")
print("π‘ Type 'browse' to open file browser (if available)")
print("π‘ Type 'quit' to exit")
print()
while True:
try:
# Get user input for file path
file_path = input("π Enter PDF file path (or 'browse'/'sample'): ").strip()
# Check for exit commands
if file_path.lower() in ['quit', 'exit', 'q']:
print("π Goodbye!")
return None
# Check for browse command
if file_path.lower() == 'browse':
try:
import tkinter as tk
from tkinter import filedialog
# Create a hidden root window
root = tk.Tk()
root.withdraw() # Hide the main window
# Open file dialog
file_path = filedialog.askopenfilename(
title="Select PDF File",
filetypes=[("PDF files", "*.pdf"), ("All files", "*.*")]
)
root.destroy() # Close the hidden window
if not file_path:
print("β No file selected.")
continue
print(f"β
Selected file: {file_path}")
except ImportError:
print("β File browser not available. Please enter the file path manually.")
continue
except Exception as e:
print(f"β Error opening file browser: {e}")
print("π‘ Please enter the file path manually.")
continue
# Check for sample command
elif file_path.lower() == 'sample':
if os.path.exists("sample.pdf"):
file_path = "sample.pdf"
print("π Using sample.pdf...")
else:
print("β sample.pdf not found. Please provide a different file path.")
continue
# Skip empty input
elif not file_path:
print("β οΈ Please enter a file path.")
continue
# Check if file exists
if not os.path.exists(file_path):
print(f"β File not found: {file_path}")
print("π‘ Please check the file path and try again.")
continue
# Check if it's a PDF file
if not file_path.lower().endswith('.pdf'):
print("β Only PDF files are supported.")
print("π‘ Please provide a PDF file.")
continue
print_subsection(f"Processing PDF Document")
print(f"π File: {os.path.basename(file_path)}")
print(f"π Path: {file_path}")
# Ask about OCR
use_ocr_input = input("π Use OCR for scanned documents? (y/n, default: n): ").strip().lower()
use_ocr = use_ocr_input in ['y', 'yes']
if use_ocr:
print("π OCR enabled - processing scanned document...")
else:
print("π Processing as text-based PDF...")
# Ingest the document
print("β³ Processing document...")
start_time = time.time()
chunks = rag_system.ingest_document(file_path, use_ocr=use_ocr)
processing_time = time.time() - start_time
print(f"β
Successfully processed {len(chunks)} chunks in {processing_time:.2f} seconds")
print(f"π Document chunks created:")
for i, chunk in enumerate(chunks[:5]): # Show first 5 chunks
print(f" Chunk {i+1}: {chunk.chunk_id}")
print(f" Content preview: {chunk.content[:100]}...")
print()
if len(chunks) > 5:
print(f" ... and {len(chunks) - 5} more chunks")
print("π Document processing completed successfully!")
return rag_system
except KeyboardInterrupt:
print("\nπ Interrupted by user. Goodbye!")
return None
except Exception as e:
print(f"β Error during document ingestion: {e}")
print("π‘ Please check if the file is a valid PDF and try again.")
print("π‘ For scanned documents, try enabling OCR.")
continue
print_subsection(f"Processing PDF Document")
print(f"π File: {selected_file.name}")
# Ask about OCR
use_ocr_input = input("π Use OCR for scanned documents? (y/n, default: n): ").strip().lower()
use_ocr = use_ocr_input in ['y', 'yes']
if use_ocr:
print("π OCR enabled - processing scanned document...")
else:
print("π Processing as text-based PDF...")
# Ingest the document
print("β³ Processing document...")
start_time = time.time()
chunks = rag_system.ingest_document(str(selected_file), use_ocr=use_ocr)
processing_time = time.time() - start_time
print(f"β
Successfully processed {len(chunks)} chunks in {processing_time:.2f} seconds")
print(f"π Document chunks created:")
for i, chunk in enumerate(chunks[:5]): # Show first 5 chunks
print(f" Chunk {i+1}: {chunk.chunk_id}")
print(f" Content preview: {chunk.content[:100]}...")
print()
if len(chunks) > 5:
print(f" ... and {len(chunks) - 5} more chunks")
print("π Document processing completed successfully!")
return rag_system
except KeyboardInterrupt:
print("\nπ Interrupted by user. Goodbye!")
return None
except Exception as e:
print(f"β Error during document ingestion: {e}")
print("π‘ Please check if the file is a valid PDF and try again.")
print("π‘ For scanned documents, try enabling OCR.")
continue
def demo_query_processing(rag_system):
"""Interactive query processing with user input"""
print_section("INTERACTIVE QUERY PROCESSING")
print("π‘ Enter your insurance policy questions below.")
print("π‘ Type 'quit' or 'exit' to stop asking questions.")
print("π‘ Type 'help' for example questions.")
print()
results = []
query_count = 0
while True:
try:
# Get user input
user_query = input("π€ Enter your question: ").strip()
# Check for exit commands
if user_query.lower() in ['quit', 'exit', 'q']:
print("π Goodbye!")
break
# Check for help command
if user_query.lower() == 'help':
print("\nπ Example questions you can ask:")
print(" β’ Is heart surgery covered under this policy?")
print(" β’ What is the waiting period for pre-existing diseases?")
print(" β’ Can I claim for dental treatment?")
print(" β’ What is the maximum coverage amount?")
print(" β’ Are there any exclusions for chronic diseases?")
print(" β’ What documents are required for claim submission?")
print(" β’ Is cancer treatment covered?")
print(" β’ What is the claim process?")
print()
continue
# Skip empty queries
if not user_query:
print("β οΈ Please enter a question.")
continue
query_count += 1
print_subsection(f"Processing Query #{query_count}")
print(f"π€ Query: {user_query}")
# Process the query
start_time = time.time()
result = rag_system.process_query(user_query)
processing_time = time.time() - start_time
# Display results
print(f"β±οΈ Processing time: {processing_time:.2f} seconds")
print(f"π Decision: {result.decision.upper()}")
print(f"π― Confidence: {result.confidence_score:.2%}")
if result.amount:
print(f"π° Amount: βΉ{result.amount:,.2f}")
print(f"π Justification: {result.justification}")
if result.relevant_clauses:
print(f"π Relevant Clauses: {', '.join(result.relevant_clauses)}")
results.append({
"query": user_query,
"result": result,
"processing_time": processing_time
})
print()
# Ask if user wants to continue
if query_count % 3 == 0: # Ask every 3 queries
continue_choice = input("β Continue asking questions? (y/n): ").strip().lower()
if continue_choice not in ['y', 'yes', '']:
print("π Thanks for using the RAG system!")
break
except KeyboardInterrupt:
print("\nπ Interrupted by user. Goodbye!")
break
except Exception as e:
print(f"β Error processing query: {e}")
print("π‘ Try asking a different question or type 'help' for examples.")
print()
return results
def demo_audit_trail(rag_system):
"""Demo audit trail functionality"""
print_section("AUDIT TRAIL DEMO")
try:
# Get audit trail
audit_log = rag_system.get_audit_trail()
print_subsection("Audit Trail Overview")
print(f"π Total queries processed: {len(audit_log)}")
if audit_log:
print("\nπ Recent audit entries:")
for i, entry in enumerate(audit_log[-3:], 1): # Show last 3 entries
print(f" Entry {i}:")
print(f" Timestamp: {entry.get('timestamp', 'N/A')}")
print(f" Query: {entry.get('query', 'N/A')}")
print(f" Relevant chunks: {entry.get('relevant_chunks_count', 0)}")
if 'error' in entry:
print(f" Error: {entry['error']}")
print()
# Save audit trail
print_subsection("Saving Audit Trail")
audit_file = "demo_audit_trail.json"
rag_system.save_audit_trail(audit_file)
print(f"β
Audit trail saved to: {audit_file}")
# Show audit file size
if os.path.exists(audit_file):
file_size = os.path.getsize(audit_file)
print(f"π File size: {file_size:,} bytes")
except Exception as e:
print(f"β Error with audit trail: {e}")
def demo_system_analysis(rag_system, query_results):
"""Demo system performance and analysis"""
print_section("SYSTEM ANALYSIS DEMO")
if not query_results:
print("β No query results to analyze")
return
print_subsection("Performance Statistics")
# Calculate statistics
total_queries = len(query_results)
avg_processing_time = sum(r['processing_time'] for r in query_results) / total_queries
avg_confidence = sum(r['result'].confidence_score for r in query_results) / total_queries
decisions = [r['result'].decision for r in query_results]
decision_counts = {}
for decision in decisions:
decision_counts[decision] = decision_counts.get(decision, 0) + 1
print(f"π Total queries processed: {total_queries}")
print(f"β±οΈ Average processing time: {avg_processing_time:.2f} seconds")
print(f"π― Average confidence score: {avg_confidence:.2%}")
print("\nπ Decision Distribution:")
for decision, count in decision_counts.items():
percentage = (count / total_queries) * 100
print(f" {decision.upper()}: {count} ({percentage:.1f}%)")
print_subsection("Query Analysis")
# Find best and worst performing queries
best_query = max(query_results, key=lambda x: x['result'].confidence_score)
worst_query = min(query_results, key=lambda x: x['result'].confidence_score)
print(f"π Best performing query:")
print(f" Query: {best_query['query']}")
print(f" Confidence: {best_query['result'].confidence_score:.2%}")
print(f"\nβ οΈ Worst performing query:")
print(f" Query: {worst_query['query']}")
print(f" Confidence: {worst_query['result'].confidence_score:.2%}")
def demo_advanced_features():
"""Demo advanced features like hybrid search and contextual compression"""
print_section("ADVANCED FEATURES DEMO")
print_subsection("Vector Database Features")
print("π Semantic search with contextual compression")
print("π Document chunking with metadata preservation")
print("π― Similarity scoring and ranking")
print_subsection("LLM Integration")
print("π§ Query parsing with entity extraction")
print("π Reasoning with policy clause mapping")
print("π Structured JSON response generation")
print_subsection("Audit and Compliance")
print("π Complete audit trail with timestamps")
print("π Decision justification with clause references")
print("πΎ Exportable audit logs for compliance")
def main():
"""Main demo function"""
print("π RAG Insurance Policy Analyzer - Interactive GPU Demo")
print("This demo allows you to upload PDF documents from anywhere on your system")
print("and ask questions interactively. Powered by GPU-accelerated RAG system")
# Step 1: Document Ingestion
rag_system = demo_document_ingestion()
if not rag_system:
print("β Demo cannot continue without successful document ingestion")
return
# Step 2: Query Processing
query_results = demo_query_processing(rag_system)
# Step 3: Audit Trail
demo_audit_trail(rag_system)
# Step 4: System Analysis
demo_system_analysis(rag_system, query_results)
# Step 5: Advanced Features
demo_advanced_features()
print_section("INTERACTIVE DEMO COMPLETED")
print("β
You've successfully used the interactive RAG system!")
print("π Check the following files for outputs:")
print(" - demo_audit_trail.json (audit trail)")
print(" - vector_db/ (vector database)")
print(" - uploads/ (uploaded documents)")
print("\nπ― Next Steps:")
print(" 1. Start the web interface: python api_server.py")
print(" 2. Open http://localhost:8000 in your browser")
print(" 3. Upload documents and process queries interactively")
print(" 4. Or run this demo again: python demo.py")
print(" 5. Try different PDF files from anywhere on your system")
if __name__ == "__main__":
main() |