File size: 15,951 Bytes
b9756ef ea0c3e1 b9756ef ea0c3e1 b9756ef ea0c3e1 b9756ef ea0c3e1 b9756ef ea0c3e1 b9756ef ea0c3e1 b9756ef 4c5479b b9756ef 4c5479b b9756ef 4c5479b b9756ef 4c5479b b9756ef ea0c3e1 b9756ef 4c5479b b9756ef 4c5479b b9756ef 4c5479b b9756ef 4c5479b b9756ef 4c5479b b9756ef 4c5479b b9756ef 4c5479b b9756ef 4c5479b b9756ef 4c5479b b9756ef ea0c3e1 b9756ef |
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 |
import os
import json
from typing import Dict, List, Optional
import logging
from functools import lru_cache
import gradio as gr
from langchain_openai import ChatOpenAI
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
from vector_db import VectorDatabase
import re
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
class RAGSystem:
def __init__(self, vector_db: Optional[VectorDatabase] = None):
logging.info("Initializing RAGSystem")
self.vector_db = vector_db if vector_db else VectorDatabase()
# LLM and chain will be initialized later with user-provided API key
self.llm = None
self.chain = None
# Prompt template for statute-grounded answers
self.prompt_template = PromptTemplate(
input_variables=["query", "context", "state", "statutes"],
template="""You are a legal assistant specializing in tenant rights and landlord-tenant laws. Your goal is to provide accurate, detailed, and helpful answers that are explicitly grounded in the statutes provided in the context. Only use general knowledge to supplement the answer if the context lacks sufficient detail to fully answer the question, and clearly indicate when you are doing so.
Instructions:
- Use the context information and the provided statutes as the primary source to answer the question.
- Explicitly cite the relevant statute(s) (e.g., (AS § 34.03.220(a)(2))) in your answer to ground your response in the legal text.
- If multiple statutes are relevant, cite all that apply.
- If the context does not contain a relevant statute to answer the question, state that no specific statute was found and provide a general answer, clearly marking it as general knowledge.
- Provide detailed answers with practical examples or scenarios when possible.
- Use bullet points or numbered lists for clarity when applicable.
- Maintain a professional and neutral tone.
Question: {query}
State: {state}
Statutes found in context:
{statutes}
Context information:
{context}
Answer:"""
)
def initialize_llm(self, openai_api_key: str):
"""Initialize the LLM and chain with the provided API key."""
if not openai_api_key:
raise ValueError("OpenAI API key is required.")
try:
self.llm = ChatOpenAI(
temperature=0.2,
openai_api_key=openai_api_key,
model_name="gpt-3.5-turbo",
max_tokens=1500,
request_timeout=30
)
logging.info("OpenAI LLM initialized successfully")
self.chain = LLMChain(llm=self.llm, prompt=self.prompt_template)
logging.info("LLMChain created successfully")
except Exception as e:
logging.error(f"Failed to initialize OpenAI LLM: {str(e)}")
raise
def extract_statutes(self, context: str) -> str:
"""
Extract statute citations from the context using a regex pattern.
Returns a string of statutes, one per line, or a message if none are found.
"""
statute_pattern = r'\([A-Za-z0-9§\.\s-]+\)'
statutes = re.findall(statute_pattern, context)
if statutes:
return "\n".join(statutes)
return "No statutes found in the context."
@lru_cache(maxsize=100)
def process_query(self, query: str, state: str, openai_api_key: str, n_results: int = 5) -> Dict[str, any]:
logging.info(f"Processing query: '{query}' for state: {state}")
if not state:
return {
"answer": "Please select a state to proceed with your query.",
"context_used": "N/A",
"statutes_found": "N/A"
}
if not openai_api_key:
return {
"answer": "Please provide an OpenAI API key to proceed.",
"context_used": "N/A",
"statutes_found": "N/A"
}
# Initialize LLM with the provided API key if not already initialized
if not self.llm or not self.chain:
try:
self.initialize_llm(openai_api_key)
except Exception as e:
return {
"answer": f"Failed to initialize LLM with the provided API key: {str(e)}",
"context_used": "N/A",
"statutes_found": "N/A"
}
try:
results = self.vector_db.query(query, state=state, n_results=n_results)
logging.info("Vector database query successful")
except Exception as e:
logging.error(f"Vector database query failed: {str(e)}")
# Safeguard: Fallback to empty results if vector DB query fails
results = {
"document_results": {"documents": [[]], "metadatas": [[]]},
"state_results": {"documents": [[]], "metadatas": [[]]}
}
logging.info("Applied safeguard: Using empty results due to vector DB failure")
context_parts = []
if results["document_results"]["documents"] and results["document_results"]["documents"][0]:
for i, doc in enumerate(results["document_results"]["documents"][0]):
metadata = results["document_results"]["metadatas"][0][i]
context_parts.append(f"[{metadata['state']} - Chunk {metadata.get('chunk_id', 'N/A')}] {doc}")
if results["state_results"]["documents"] and results["state_results"]["documents"][0]:
for i, doc in enumerate(results["state_results"]["documents"][0]):
metadata = results["state_results"]["metadatas"][0][i]
context_parts.append(f"[{metadata['state']} - Summary] {doc}")
context = "\n\n---\n\n".join(context_parts) if context_parts else "No relevant context found."
if not context_parts:
logging.info("No relevant context found for query")
return {
"answer": "I don't have sufficient information in my database to answer this question accurately. However, I can provide some general information about tenant rights.",
"context_used": context,
"statutes_found": "N/A"
}
# Extract statutes from the context
statutes = self.extract_statutes(context)
try:
answer = self.chain.invoke({
"query": query,
"context": context,
"state": state,
"statutes": statutes
})
logging.info("LLM generated answer successfully")
except Exception as e:
logging.error(f"LLM processing failed: {str(e)}")
return {
"answer": "An error occurred while generating the answer. Please try again.",
"context_used": context,
"statutes_found": statutes
}
return {
"answer": answer['text'].strip(),
"context_used": context,
"statutes_found": statutes
}
def get_states(self) -> List[str]:
try:
states = self.vector_db.get_states()
logging.info(f"Retrieved {len(states)} states from database")
return states
except Exception as e:
logging.error(f"Failed to get states: {str(e)}")
return []
def load_pdf(self, pdf_path: str) -> int:
try:
num_states = self.vector_db.process_and_load_pdf(pdf_path)
logging.info(f"Loaded PDF with {num_states} states")
return num_states
except Exception as e:
logging.error(f"Failed to load PDF: {str(e)}")
return 0
def gradio_interface(self) -> gr.Interface:
def query_interface(api_key: str, query: str, state: str) -> str:
if not api_key:
return "⚠️ **Error:** Please provide an OpenAI API key to proceed."
if not state:
return "⚠️ **Error:** Please select a state to proceed with your query."
result = self.process_query(query, state=state, openai_api_key=api_key)
return f"### Answer:\n{result['answer']}\n\n### Statutes Found:\n{result['statutes_found']}"
states = self.get_states()
example_queries = [
["What is the rent due date law?", "California"],
["What are the rules for security deposit returns?", "New York"],
["Can a landlord enter without notice?", "Texas"],
["What are the eviction notice requirements?", "Florida"],
["Are there rent control laws?", "Oregon"]
]
# Custom CSS for a modern, readable, and responsive UI
custom_css = """
/* General container styling */
.gr-form {
max-width: 900px;
margin: 0 auto;
padding: 20px;
background-color: #ffffff;
border-radius: 15px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}
/* Title and description */
.gr-title {
font-size: 2.2em;
font-weight: bold;
color: #2c3e50;
text-align: center;
margin-bottom: 10px;
}
.gr-description {
font-size: 1.1em;
color: #7f8c8d;
text-align: center;
margin-bottom: 30px;
}
/* Input fields */
.gr-textbox, .gr-dropdown {
border: 1px solid #dcdcdc !important;
border-radius: 8px !important;
padding: 12px !important;
font-size: 1em !important;
transition: border-color 0.3s ease;
}
.gr-textbox:focus, .gr-dropdown:focus {
border-color: #3498db !important;
box-shadow: 0 0 5px rgba(52, 152, 219, 0.3) !important;
}
.gr-textbox label, .gr-dropdown label {
font-weight: 600;
color: #34495e;
margin-bottom: 8px;
}
/* Buttons */
.gr-button-primary {
background-color: #3498db !important;
border: none !important;
padding: 12px 30px !important;
font-weight: bold !important;
font-size: 1em !important;
border-radius: 8px !important;
transition: background-color 0.3s ease, transform 0.1s ease;
}
.gr-button-primary:hover {
background-color: #2980b9 !important;
transform: translateY(-2px);
}
.gr-button-secondary {
background-color: #95a5a6 !important;
border: none !important;
padding: 12px 30px !important;
font-weight: bold !important;
font-size: 1em !important;
border-radius: 8px !important;
transition: background-color 0.3s ease;
}
.gr-button-secondary:hover {
background-color: #7f8c8d !important;
}
/* Output area */
.output-markdown {
background-color: #f9f9f9 !important;
color: #2c3e50 !important; /* Dark text for readability */
padding: 25px !important;
border-radius: 10px !important;
border: 1px solid #e0e0e0 !important;
font-size: 1.1em !important;
line-height: 1.8 !important;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}
/* Examples section */
.gr-examples {
background-color: #ecf0f1;
padding: 15px;
border-radius: 10px;
margin-top: 20px;
}
.gr-examples table {
background-color: transparent !important;
}
/* Dark mode */
@media (prefers-color-scheme: dark) {
.gr-form {
background-color: #2c3e50;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
}
.gr-title {
color: #ecf0f1;
}
.gr-description {
color: #bdc3c7;
}
.gr-textbox, .gr-dropdown {
background-color: #34495e !important;
color: #ecf0f1 !important;
border-color: #7f8c8d !important;
}
.gr-textbox label, .gr-dropdown label {
color: #ecf0f1;
}
.output-markdown {
background-color: #34495e !important;
color: #ecf0f1 !important;
border-color: #7f8c8d !important;
}
.gr-examples {
background-color: #3e5367;
}
}
/* Responsive design */
@media (max-width: 600px) {
.gr-form {
padding: 15px;
}
.gr-title {
font-size: 1.8em;
}
.gr-description {
font-size: 1em;
}
.gr-textbox, .gr-dropdown {
font-size: 0.9em !important;
}
.gr-button-primary, .gr-button-secondary {
padding: 10px 20px !important;
font-size: 0.9em !important;
}
.output-markdown {
font-size: 1em !important;
padding: 15px !important;
}
}
"""
interface = gr.Interface(
fn=query_interface,
inputs=[
gr.Textbox(
label="Enter your OpenAI API Key",
type="password",
placeholder="e.g., sk-abc123",
elem_classes="input-field"
),
gr.Textbox(
label="Enter your question about Landlord-Tenant laws",
placeholder="e.g., What are the eviction rules?",
lines=3,
elem_classes="input-field"
),
gr.Dropdown(
label="Select a state (required)",
choices=states,
value=None,
allow_custom_value=False,
elem_classes="input-field"
)
],
outputs=gr.Markdown(
label="Response",
elem_classes="output-markdown"
),
title="🏠 Landlord-Tenant Rights Bot",
description="Ask questions about tenant rights and landlord-tenant laws based on state-specific legal documents. Provide your OpenAI API key, select a state, and enter your question below. You can get an API key from [OpenAI](https://platform.openai.com/api-keys).",
examples=example_queries,
theme=gr.themes.Default(),
css=custom_css
)
return interface
if __name__ == "__main__":
try:
rag = RAGSystem()
pdf_path = "data/tenant-landlord.pdf"
rag.load_pdf(pdf_path)
interface = rag.gradio_interface()
interface.launch(share=True)
except Exception as e:
logging.error(f"Main execution failed: {str(e)}")
raise |