Update app.py
Browse filesinit st.session_state
app.py
CHANGED
@@ -1,200 +1,210 @@
|
|
1 |
-
import os
|
2 |
-
import time
|
3 |
-
import
|
4 |
-
import
|
5 |
-
from
|
6 |
-
|
7 |
-
from
|
8 |
-
from
|
9 |
-
from
|
10 |
-
from
|
11 |
-
from
|
12 |
-
from
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
# Initialize environment variables
|
17 |
-
load_dotenv()
|
18 |
-
|
19 |
-
# ---------------
|
20 |
-
def
|
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 |
main()
|
|
|
1 |
+
import os
|
2 |
+
import time
|
3 |
+
import streamlit as st
|
4 |
+
from dotenv import load_dotenv
|
5 |
+
from langchain_groq import ChatGroq
|
6 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
7 |
+
from langchain_community.vectorstores import FAISS
|
8 |
+
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
9 |
+
from langchain_community.document_loaders import WebBaseLoader
|
10 |
+
from langchain_core.prompts import PromptTemplate
|
11 |
+
from langchain_core.output_parsers import StrOutputParser
|
12 |
+
from datetime import datetime
|
13 |
+
import json
|
14 |
+
import traceback
|
15 |
+
|
16 |
+
# Initialize environment variables
|
17 |
+
load_dotenv()
|
18 |
+
|
19 |
+
# --------------- Session State Initialization ---------------
|
20 |
+
def init_session_state():
|
21 |
+
"""Initialize all required session state variables"""
|
22 |
+
defaults = {
|
23 |
+
'kb_info': {
|
24 |
+
'build_time': None,
|
25 |
+
'size': None,
|
26 |
+
'version': '1.1'
|
27 |
+
},
|
28 |
+
'messages': [],
|
29 |
+
'vector_store': None,
|
30 |
+
'models_initialized': False
|
31 |
+
}
|
32 |
+
|
33 |
+
for key, value in defaults.items():
|
34 |
+
if key not in st.session_state:
|
35 |
+
st.session_state[key] = value
|
36 |
+
|
37 |
+
# --------------- Enhanced Logging ---------------
|
38 |
+
def log_interaction(user_input: str, bot_response: str, context: str):
|
39 |
+
"""Log interactions with error handling"""
|
40 |
+
try:
|
41 |
+
log_entry = {
|
42 |
+
"timestamp": datetime.now().isoformat(),
|
43 |
+
"user_input": user_input,
|
44 |
+
"bot_response": bot_response,
|
45 |
+
"context": context[:500], # Store first 500 chars of context
|
46 |
+
"kb_version": st.session_state.kb_info['version']
|
47 |
+
}
|
48 |
+
|
49 |
+
os.makedirs("chat_history", exist_ok=True)
|
50 |
+
log_path = os.path.join("chat_history", "chat_logs.json")
|
51 |
+
|
52 |
+
with open(log_path, "a", encoding="utf-8") as f:
|
53 |
+
f.write(json.dumps(log_entry, ensure_ascii=False) + "\n")
|
54 |
+
|
55 |
+
except Exception as e:
|
56 |
+
st.error(f"Logging error: {str(e)}")
|
57 |
+
print(traceback.format_exc())
|
58 |
+
|
59 |
+
# --------------- Model Initialization ---------------
|
60 |
+
@st.cache_resource
|
61 |
+
def init_models():
|
62 |
+
"""Initialize AI models with caching"""
|
63 |
+
try:
|
64 |
+
llm = ChatGroq(
|
65 |
+
model_name="llama-3.3-70b-versatile",
|
66 |
+
temperature=0.6,
|
67 |
+
api_key=os.getenv("GROQ_API_KEY")
|
68 |
+
)
|
69 |
+
embeddings = HuggingFaceEmbeddings(
|
70 |
+
model_name="intfloat/multilingual-e5-large-instruct"
|
71 |
+
)
|
72 |
+
st.session_state.models_initialized = True
|
73 |
+
return llm, embeddings
|
74 |
+
except Exception as e:
|
75 |
+
st.error(f"Model initialization failed: {str(e)}")
|
76 |
+
st.stop()
|
77 |
+
|
78 |
+
# --------------- Knowledge Base Management ---------------
|
79 |
+
VECTOR_STORE_PATH = "vector_store"
|
80 |
+
URLS = [
|
81 |
+
"https://status.law",
|
82 |
+
"https://status.law/about",
|
83 |
+
# ... other URLs ...
|
84 |
+
]
|
85 |
+
|
86 |
+
def build_knowledge_base(_embeddings):
|
87 |
+
"""Build or update the knowledge base"""
|
88 |
+
try:
|
89 |
+
start_time = time.time()
|
90 |
+
documents = []
|
91 |
+
|
92 |
+
with st.status("Building knowledge base..."):
|
93 |
+
for url in URLS:
|
94 |
+
try:
|
95 |
+
loader = WebBaseLoader(url)
|
96 |
+
docs = loader.load()
|
97 |
+
documents.extend(docs)
|
98 |
+
st.write(f"✓ Loaded {url}")
|
99 |
+
except Exception as e:
|
100 |
+
st.error(f"Failed to load {url}: {str(e)}")
|
101 |
+
|
102 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
103 |
+
chunk_size=500,
|
104 |
+
chunk_overlap=100
|
105 |
+
)
|
106 |
+
chunks = text_splitter.split_documents(documents)
|
107 |
+
|
108 |
+
vector_store = FAISS.from_documents(chunks, _embeddings)
|
109 |
+
vector_store.save_local(VECTOR_STORE_PATH)
|
110 |
+
|
111 |
+
# Update knowledge base info
|
112 |
+
st.session_state.kb_info.update({
|
113 |
+
'build_time': time.time() - start_time,
|
114 |
+
'size': sum(os.path.getsize(f) for f in os.listdir(VECTOR_STORE_PATH)) / (1024 ** 2),
|
115 |
+
'version': datetime.now().strftime("%Y%m%d-%H%M%S")
|
116 |
+
})
|
117 |
+
|
118 |
+
return vector_store
|
119 |
+
except Exception as e:
|
120 |
+
st.error(f"Knowledge base creation failed: {str(e)}")
|
121 |
+
st.stop()
|
122 |
+
|
123 |
+
# --------------- Main Application ---------------
|
124 |
+
def main():
|
125 |
+
# Initialize session state first
|
126 |
+
init_session_state()
|
127 |
+
|
128 |
+
# Page configuration
|
129 |
+
st.set_page_config(
|
130 |
+
page_title="Status Law Assistant",
|
131 |
+
page_icon="⚖️",
|
132 |
+
layout="wide"
|
133 |
+
)
|
134 |
+
|
135 |
+
# Display header
|
136 |
+
st.markdown('''
|
137 |
+
<h1 style="border-bottom: 2px solid #444; padding-bottom: 10px;">
|
138 |
+
⚖️ <a href="https://status.law/" style="text-decoration: none; color: #2B5876;">Status.Law</a> Legal Assistant
|
139 |
+
</h1>
|
140 |
+
''', unsafe_allow_html=True)
|
141 |
+
|
142 |
+
# Initialize models
|
143 |
+
llm, embeddings = init_models()
|
144 |
+
|
145 |
+
# Knowledge base initialization
|
146 |
+
if not os.path.exists(VECTOR_STORE_PATH):
|
147 |
+
st.warning("Knowledge base not initialized")
|
148 |
+
if st.button("Create Knowledge Base"):
|
149 |
+
st.session_state.vector_store = build_knowledge_base(embeddings)
|
150 |
+
st.rerun()
|
151 |
+
return
|
152 |
+
|
153 |
+
if not st.session_state.vector_store:
|
154 |
+
try:
|
155 |
+
st.session_state.vector_store = FAISS.load_local(
|
156 |
+
VECTOR_STORE_PATH,
|
157 |
+
embeddings,
|
158 |
+
allow_dangerous_deserialization=True
|
159 |
+
)
|
160 |
+
except Exception as e:
|
161 |
+
st.error(f"Failed to load knowledge base: {str(e)}")
|
162 |
+
st.stop()
|
163 |
+
|
164 |
+
# Chat interface
|
165 |
+
for message in st.session_state.messages:
|
166 |
+
with st.chat_message(message["role"]):
|
167 |
+
st.markdown(message["content"])
|
168 |
+
|
169 |
+
if prompt := st.chat_input("Ask your legal question"):
|
170 |
+
# Add user message to chat history
|
171 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
172 |
+
with st.chat_message("user"):
|
173 |
+
st.markdown(prompt)
|
174 |
+
|
175 |
+
# Generate response
|
176 |
+
with st.chat_message("assistant"):
|
177 |
+
try:
|
178 |
+
# Retrieve context
|
179 |
+
context_docs = st.session_state.vector_store.similarity_search(prompt)
|
180 |
+
context_text = "\n".join([d.page_content for d in context_docs])
|
181 |
+
|
182 |
+
# Generate response
|
183 |
+
prompt_template = PromptTemplate.from_template('''
|
184 |
+
You are a helpful and polite legal assistant at Status.Law.
|
185 |
+
Answer in the language in which the question was asked.
|
186 |
+
Answer the question based on the context provided.
|
187 |
+
|
188 |
+
Context: {context}
|
189 |
+
Question: {question}
|
190 |
+
''')
|
191 |
+
|
192 |
+
chain = prompt_template | llm | StrOutputParser()
|
193 |
+
response = chain.invoke({
|
194 |
+
"context": context_text,
|
195 |
+
"question": prompt
|
196 |
+
})
|
197 |
+
|
198 |
+
# Display and log
|
199 |
+
st.markdown(response)
|
200 |
+
log_interaction(prompt, response, context_text)
|
201 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
202 |
+
|
203 |
+
except Exception as e:
|
204 |
+
error_msg = f"Error generating response: {str(e)}"
|
205 |
+
st.error(error_msg)
|
206 |
+
log_interaction(prompt, error_msg, "")
|
207 |
+
print(traceback.format_exc())
|
208 |
+
|
209 |
+
if __name__ == "__main__":
|
210 |
main()
|