Nischal Subedi
Add Tenant-Rights-Bot files
b9756ef
raw
history blame
12 kB
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.
- Do not include a "Sources" section in the answer.
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.",
"sources": [],
"context_used": "N/A",
"statutes_found": "N/A"
}
if not openai_api_key:
return {
"answer": "Please provide an OpenAI API key to proceed.",
"sources": [],
"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)}",
"sources": [],
"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)}")
return {
"answer": "An error occurred while querying the database. Please try again.",
"sources": [],
"context_used": "N/A",
"statutes_found": "N/A"
}
context_parts = []
sources = []
if results["document_results"]["documents"]:
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}")
sources.append({
"text": doc[:100] + "..." if len(doc) > 100 else doc,
"state": metadata["state"],
"chunk_id": str(metadata.get("chunk_id", "N/A")),
"source_file": metadata.get("source", "Unknown")
})
if results["state_results"]["documents"]:
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}")
sources.append({
"text": doc[:100] + "..." if len(doc) > 100 else doc,
"state": metadata["state"],
"type": metadata.get("type", "summary"),
"source_file": "state_summary"
})
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.",
"sources": [],
"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.",
"sources": sources,
"context_used": context,
"statutes_found": statutes
}
return {
"answer": answer['text'].strip(),
"sources": sources,
"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 "Please provide an OpenAI API key to proceed."
if not state:
return "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 = [
["sk-abc123", "What is the rent due date law?", "California"],
["sk-abc123", "What are the rules for security deposit returns?", "New York"],
["sk-abc123", "Can a landlord enter without notice?", "Texas"],
["sk-abc123", "What are the eviction notice requirements?", "Florida"],
["sk-abc123", "Are there rent control laws?", "Oregon"]
]
interface = gr.Interface(
fn=query_interface,
inputs=[
gr.Textbox(
label="Enter your OpenAI API Key",
type="password",
placeholder="e.g., sk-abc123"
),
gr.Textbox(
label="Enter your question about Landlord-Tenant laws",
placeholder="e.g., What are the eviction rules?",
lines=2
),
gr.Dropdown(
label="Select a state (required)",
choices=states,
value=None,
allow_custom_value=False
)
],
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.Soft(),
css="""
.output-markdown {
background-color: #f8f9fa;
padding: 20px;
border-radius: 10px;
border: 1px solid #e0e0e0;
font-size: 16px;
line-height: 1.6;
}
.gr-button-primary {
background-color: #4a90e2;
border: none;
padding: 10px 20px;
font-weight: bold;
}
.gr-button-primary:hover {
background-color: #357abd;
}
.gr-form {
max-width: 800px;
margin: 0 auto;
}
"""
)
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