File size: 11,984 Bytes
b9756ef
 
 
 
 
ea0c3e1
b9756ef
 
 
 
 
ea0c3e1
b9756ef
ea0c3e1
b9756ef
 
 
 
 
 
 
 
 
 
 
 
 
 
ea0c3e1
b9756ef
 
 
 
 
 
 
 
 
ea0c3e1
b9756ef
 
ea0c3e1
b9756ef
 
ea0c3e1
b9756ef
 
ea0c3e1
b9756ef
 
ea0c3e1
b9756ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea0c3e1
b9756ef
 
 
 
 
 
 
 
 
 
ea0c3e1
b9756ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea0c3e1
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
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