Akshayram1 commited on
Commit
1beb2b7
β€’
1 Parent(s): e4d4b3b

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +356 -0
app.py ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from phi.agent import Agent
3
+ from phi.knowledge.pdf import PDFKnowledgeBase, PDFReader
4
+ from phi.vectordb.qdrant import Qdrant
5
+ from phi.tools.duckduckgo import DuckDuckGo
6
+ from phi.model.openai import OpenAIChat
7
+ from phi.embedder.openai import OpenAIEmbedder
8
+ import tempfile
9
+ import os
10
+
11
+ #initializing the session state variables
12
+ def init_session_state():
13
+ """Initialize session state variables"""
14
+ if 'openai_api_key' not in st.session_state:
15
+ st.session_state.openai_api_key = None
16
+ if 'qdrant_api_key' not in st.session_state:
17
+ st.session_state.qdrant_api_key = None
18
+ if 'qdrant_url' not in st.session_state:
19
+ st.session_state.qdrant_url = None
20
+ if 'vector_db' not in st.session_state:
21
+ st.session_state.vector_db = None
22
+ if 'legal_team' not in st.session_state:
23
+ st.session_state.legal_team = None
24
+ if 'knowledge_base' not in st.session_state:
25
+ st.session_state.knowledge_base = None
26
+
27
+ def init_qdrant():
28
+ """Initialize Qdrant vector database"""
29
+ if not st.session_state.qdrant_api_key:
30
+ raise ValueError("Qdrant API key not provided")
31
+ if not st.session_state.qdrant_url:
32
+ raise ValueError("Qdrant URL not provided")
33
+
34
+ return Qdrant(
35
+ collection="legal_knowledge",
36
+ url=st.session_state.qdrant_url,
37
+ api_key=st.session_state.qdrant_api_key,
38
+ https=True,
39
+ timeout=None,
40
+ distance="cosine"
41
+ )
42
+
43
+ def process_document(uploaded_file, vector_db: Qdrant):
44
+ """Process document, create embeddings and store in Qdrant vector database"""
45
+ if not st.session_state.openai_api_key:
46
+ raise ValueError("OpenAI API key not provided")
47
+
48
+ os.environ['OPENAI_API_KEY'] = st.session_state.openai_api_key
49
+
50
+ with tempfile.TemporaryDirectory() as temp_dir:
51
+
52
+ temp_file_path = os.path.join(temp_dir, uploaded_file.name)
53
+ with open(temp_file_path, "wb") as f:
54
+ f.write(uploaded_file.getbuffer())
55
+
56
+ try:
57
+
58
+ embedder = OpenAIEmbedder(
59
+ model="text-embedding-3-small",
60
+ api_key=st.session_state.openai_api_key
61
+ )
62
+
63
+ # Creating knowledge base with explicit Qdrant configuration
64
+ knowledge_base = PDFKnowledgeBase(
65
+ path=temp_dir,
66
+ vector_db=vector_db,
67
+ reader=PDFReader(chunk=True),
68
+ embedder=embedder,
69
+ recreate_vector_db=True
70
+ )
71
+ knowledge_base.load()
72
+ return knowledge_base
73
+ except Exception as e:
74
+ raise Exception(f"Error processing document: {str(e)}")
75
+
76
+ def main():
77
+ st.set_page_config(page_title="Legal Document Analyzer", layout="wide")
78
+ init_session_state()
79
+
80
+ st.title("AI Legal Agent Team πŸ‘¨β€βš–οΈ")
81
+
82
+ with st.sidebar:
83
+ st.header("πŸ”‘ API Configuration")
84
+
85
+ openai_key = st.text_input(
86
+ "OpenAI API Key",
87
+ type="password",
88
+ value=st.session_state.openai_api_key if st.session_state.openai_api_key else "",
89
+ help="Enter your OpenAI API key"
90
+ )
91
+ if openai_key:
92
+ st.session_state.openai_api_key = openai_key
93
+
94
+ qdrant_key = st.text_input(
95
+ "Qdrant API Key",
96
+ type="password",
97
+ value=st.session_state.qdrant_api_key if st.session_state.qdrant_api_key else "",
98
+ help="Enter your Qdrant API key"
99
+ )
100
+ if qdrant_key:
101
+ st.session_state.qdrant_api_key = qdrant_key
102
+
103
+ qdrant_url = st.text_input(
104
+ "Qdrant URL",
105
+ value=st.session_state.qdrant_url if st.session_state.qdrant_url else "https://f499085c-b4bf-4bda-a9a5-227f62a9ca20.us-west-2-0.aws.cloud.qdrant.io:6333",
106
+ help="Enter your Qdrant instance URL"
107
+ )
108
+ if qdrant_url:
109
+ st.session_state.qdrant_url = qdrant_url
110
+
111
+ if all([st.session_state.qdrant_api_key, st.session_state.qdrant_url]):
112
+ try:
113
+ if not st.session_state.vector_db:
114
+ st.session_state.vector_db = init_qdrant()
115
+ st.success("Successfully connected to Qdrant!")
116
+ except Exception as e:
117
+ st.error(f"Failed to connect to Qdrant: {str(e)}")
118
+
119
+ st.divider()
120
+
121
+ if all([st.session_state.openai_api_key, st.session_state.vector_db]):
122
+ st.header("πŸ“„ Document Upload")
123
+ uploaded_file = st.file_uploader("Upload Legal Document", type=['pdf'])
124
+
125
+ if uploaded_file:
126
+ with st.spinner("Processing document..."):
127
+ try:
128
+ knowledge_base = process_document(uploaded_file, st.session_state.vector_db)
129
+ st.session_state.knowledge_base = knowledge_base
130
+
131
+ # Initialize agents
132
+ legal_researcher = Agent(
133
+ name="Legal Researcher",
134
+ role="Legal research specialist",
135
+ model=OpenAIChat(model="gpt-4o"),
136
+ tools=[DuckDuckGo()],
137
+ knowledge=st.session_state.knowledge_base,
138
+ search_knowledge=True,
139
+ instructions=[
140
+ "Find and cite relevant legal cases and precedents",
141
+ "Provide detailed research summaries with sources",
142
+ "Reference specific sections from the uploaded document",
143
+ "Always search the knowledge base for relevant information"
144
+ ],
145
+ show_tool_calls=True,
146
+ markdown=True
147
+ )
148
+
149
+ contract_analyst = Agent(
150
+ name="Contract Analyst",
151
+ role="Contract analysis specialist",
152
+ model=OpenAIChat(model="gpt-4o"),
153
+ knowledge=knowledge_base,
154
+ search_knowledge=True,
155
+ instructions=[
156
+ "Review contracts thoroughly",
157
+ "Identify key terms and potential issues",
158
+ "Reference specific clauses from the document"
159
+ ],
160
+ markdown=True
161
+ )
162
+
163
+ legal_strategist = Agent(
164
+ name="Legal Strategist",
165
+ role="Legal strategy specialist",
166
+ model=OpenAIChat(model="gpt-4o"),
167
+ knowledge=knowledge_base,
168
+ search_knowledge=True,
169
+ instructions=[
170
+ "Develop comprehensive legal strategies",
171
+ "Provide actionable recommendations",
172
+ "Consider both risks and opportunities"
173
+ ],
174
+ markdown=True
175
+ )
176
+
177
+ # Legal Agent Team
178
+ st.session_state.legal_team = Agent(
179
+ name="Legal Team Lead",
180
+ role="Legal team coordinator",
181
+ model=OpenAIChat(model="gpt-4o"),
182
+ team=[legal_researcher, contract_analyst, legal_strategist],
183
+ knowledge=st.session_state.knowledge_base,
184
+ search_knowledge=True,
185
+ instructions=[
186
+ "Coordinate analysis between team members",
187
+ "Provide comprehensive responses",
188
+ "Ensure all recommendations are properly sourced",
189
+ "Reference specific parts of the uploaded document",
190
+ "Always search the knowledge base before delegating tasks"
191
+ ],
192
+ show_tool_calls=True,
193
+ markdown=True
194
+ )
195
+
196
+ st.success("βœ… Document processed and team initialized!")
197
+
198
+ except Exception as e:
199
+ st.error(f"Error processing document: {str(e)}")
200
+
201
+ st.divider()
202
+ st.header("πŸ” Analysis Options")
203
+ analysis_type = st.selectbox(
204
+ "Select Analysis Type",
205
+ [
206
+ "Contract Review",
207
+ "Legal Research",
208
+ "Risk Assessment",
209
+ "Compliance Check",
210
+ "Custom Query"
211
+ ]
212
+ )
213
+ else:
214
+ st.warning("Please configure all API credentials to proceed")
215
+
216
+ # Main content area
217
+ if not all([st.session_state.openai_api_key, st.session_state.vector_db]):
218
+ st.info("πŸ‘ˆ Please configure your API credentials in the sidebar to begin")
219
+ elif not uploaded_file:
220
+ st.info("πŸ‘ˆ Please upload a legal document to begin analysis")
221
+ elif st.session_state.legal_team:
222
+ # Create a dictionary for analysis type icons
223
+ analysis_icons = {
224
+ "Contract Review": "πŸ“‘",
225
+ "Legal Research": "πŸ”",
226
+ "Risk Assessment": "⚠️",
227
+ "Compliance Check": "βœ…",
228
+ "Custom Query": "πŸ’­"
229
+ }
230
+
231
+ # Dynamic header with icon
232
+ st.header(f"{analysis_icons[analysis_type]} {analysis_type} Analysis")
233
+
234
+ analysis_configs = {
235
+ "Contract Review": {
236
+ "query": "Review this contract and identify key terms, obligations, and potential issues.",
237
+ "agents": ["Contract Analyst"],
238
+ "description": "Detailed contract analysis focusing on terms and obligations"
239
+ },
240
+ "Legal Research": {
241
+ "query": "Research relevant cases and precedents related to this document.",
242
+ "agents": ["Legal Researcher"],
243
+ "description": "Research on relevant legal cases and precedents"
244
+ },
245
+ "Risk Assessment": {
246
+ "query": "Analyze potential legal risks and liabilities in this document.",
247
+ "agents": ["Contract Analyst", "Legal Strategist"],
248
+ "description": "Combined risk analysis and strategic assessment"
249
+ },
250
+ "Compliance Check": {
251
+ "query": "Check this document for regulatory compliance issues.",
252
+ "agents": ["Legal Researcher", "Contract Analyst", "Legal Strategist"],
253
+ "description": "Comprehensive compliance analysis"
254
+ },
255
+ "Custom Query": {
256
+ "query": None,
257
+ "agents": ["Legal Researcher", "Contract Analyst", "Legal Strategist"],
258
+ "description": "Custom analysis using all available agents"
259
+ }
260
+ }
261
+
262
+ st.info(f"πŸ“‹ {analysis_configs[analysis_type]['description']}")
263
+ st.write(f"πŸ€– Active Legal AI Agents: {', '.join(analysis_configs[analysis_type]['agents'])}") #dictionary!!
264
+
265
+ # Replace the existing user_query section with this:
266
+ if analysis_type == "Custom Query":
267
+ user_query = st.text_area(
268
+ "Enter your specific query:",
269
+ help="Add any specific questions or points you want to analyze"
270
+ )
271
+ else:
272
+ user_query = None # Set to None for non-custom queries
273
+
274
+
275
+ if st.button("Analyze"):
276
+ if analysis_type == "Custom Query" and not user_query:
277
+ st.warning("Please enter a query")
278
+ else:
279
+ with st.spinner("Analyzing document..."):
280
+ try:
281
+ # Ensure OpenAI API key is set
282
+ os.environ['OPENAI_API_KEY'] = st.session_state.openai_api_key
283
+
284
+ # Combine predefined and user queries
285
+ if analysis_type != "Custom Query":
286
+ combined_query = f"""
287
+ Using the uploaded document as reference:
288
+
289
+ Primary Analysis Task: {analysis_configs[analysis_type]['query']}
290
+ Focus Areas: {', '.join(analysis_configs[analysis_type]['agents'])}
291
+
292
+ Please search the knowledge base and provide specific references from the document.
293
+ """
294
+ else:
295
+ combined_query = f"""
296
+ Using the uploaded document as reference:
297
+
298
+ {user_query}
299
+
300
+ Please search the knowledge base and provide specific references from the document.
301
+ Focus Areas: {', '.join(analysis_configs[analysis_type]['agents'])}
302
+ """
303
+
304
+ response = st.session_state.legal_team.run(combined_query)
305
+
306
+ # Display results in tabs
307
+ tabs = st.tabs(["Analysis", "Key Points", "Recommendations"])
308
+
309
+ with tabs[0]:
310
+ st.markdown("### Detailed Analysis")
311
+ if response.content:
312
+ st.markdown(response.content)
313
+ else:
314
+ for message in response.messages:
315
+ if message.role == 'assistant' and message.content:
316
+ st.markdown(message.content)
317
+
318
+ with tabs[1]:
319
+ st.markdown("### Key Points")
320
+ key_points_response = st.session_state.legal_team.run(
321
+ f"""Based on this previous analysis:
322
+ {response.content}
323
+
324
+ Please summarize the key points in bullet points.
325
+ Focus on insights from: {', '.join(analysis_configs[analysis_type]['agents'])}"""
326
+ )
327
+ if key_points_response.content:
328
+ st.markdown(key_points_response.content)
329
+ else:
330
+ for message in key_points_response.messages:
331
+ if message.role == 'assistant' and message.content:
332
+ st.markdown(message.content)
333
+
334
+ with tabs[2]:
335
+ st.markdown("### Recommendations")
336
+ recommendations_response = st.session_state.legal_team.run(
337
+ f"""Based on this previous analysis:
338
+ {response.content}
339
+
340
+ What are your key recommendations based on the analysis, the best course of action?
341
+ Provide specific recommendations from: {', '.join(analysis_configs[analysis_type]['agents'])}"""
342
+ )
343
+ if recommendations_response.content:
344
+ st.markdown(recommendations_response.content)
345
+ else:
346
+ for message in recommendations_response.messages:
347
+ if message.role == 'assistant' and message.content:
348
+ st.markdown(message.content)
349
+
350
+ except Exception as e:
351
+ st.error(f"Error during analysis: {str(e)}")
352
+ else:
353
+ st.info("Please upload a legal document to begin analysis")
354
+
355
+ if __name__ == "__main__":
356
+ main()