Mjlehtim commited on
Commit
05cdb5c
1 Parent(s): dedb865

New version

Browse files
Files changed (1) hide show
  1. LocalT_ESG_RAG_1.32.py +664 -0
LocalT_ESG_RAG_1.32.py ADDED
@@ -0,0 +1,664 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import streamlit as st
4
+ from fpdf import FPDF
5
+ from chromadb import Client
6
+ from chromadb.config import Settings
7
+ import chromadb
8
+ from langchain_community.utilities import SerpAPIWrapper
9
+ from llama_index.core import VectorStoreIndex
10
+ from langchain_core.output_parsers import StrOutputParser
11
+ from langchain_core.runnables import RunnablePassthrough
12
+ from langchain_groq import ChatGroq
13
+ from langchain.chains import LLMChain
14
+ from langchain.agents import AgentType, Tool, initialize_agent, AgentExecutor
15
+ from llama_parse import LlamaParse
16
+ from langchain_community.document_loaders import UnstructuredMarkdownLoader
17
+ from langchain_huggingface import HuggingFaceEmbeddings
18
+ from llama_index.core import SimpleDirectoryReader
19
+ from dotenv import load_dotenv, find_dotenv
20
+ import pandas as pd
21
+ from streamlit_chat import message
22
+ from langchain_community.vectorstores import Chroma
23
+ from langchain_community.utilities import SerpAPIWrapper
24
+ from langchain.chains import RetrievalQA
25
+ from langchain_community.document_loaders import DirectoryLoader
26
+ from langchain_community.document_loaders import PyMuPDFLoader
27
+ from langchain_community.document_loaders import UnstructuredXMLLoader
28
+ from langchain_community.document_loaders import CSVLoader
29
+ from langchain.prompts import PromptTemplate
30
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
31
+ from langchain.memory import ConversationBufferMemory
32
+ from langchain.prompts import PromptTemplate
33
+ import joblib
34
+ import nltk
35
+
36
+ import nest_asyncio # noqa: E402
37
+ nest_asyncio.apply()
38
+
39
+ load_dotenv()
40
+ load_dotenv(find_dotenv())
41
+
42
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
43
+ SERPAPI_API_KEY = os.environ["SERPAPI_API_KEY"]
44
+ GOOGLE_CSE_ID = os.environ["GOOGLE_CSE_ID"]
45
+ GOOGLE_API_KEY = os.environ["GOOGLE_API_KEY"]
46
+ LLAMA_PARSE_API_KEY = os.environ["LLAMA_PARSE_API_KEY"]
47
+ HUGGINGFACEHUB_API_TOKEN = os.environ["HUGGINGFACEHUB_API_TOKEN"]
48
+ groq_api_key=os.getenv('GROQ_API_KEY')
49
+
50
+ st.set_page_config(layout="wide")
51
+
52
+ css = """
53
+ <style>
54
+ [data-testid="stAppViewContainer"] {
55
+ background-color: #f8f9fa; /* Very light grey */
56
+ }
57
+ [data-testid="stSidebar"] {
58
+ background-color: white;
59
+ color: black;
60
+ }
61
+ [data-testid="stAppViewContainer"] * {
62
+ color: black; /* Ensure all text is black */
63
+ }
64
+ button {
65
+ background-color: #add8e6; /* Light blue for primary buttons */
66
+ color: black;
67
+ border: 2px solid green; /* Green border */
68
+ }
69
+ button:hover {
70
+ background-color: #87ceeb; /* Slightly darker blue on hover */
71
+ }
72
+
73
+ button:active {
74
+ outline: 2px solid green; /* Green outline when the button is pressed */
75
+ outline-offset: 2px; /* Space between button and outline */
76
+ }
77
+
78
+ .stButton>button:first-child {
79
+ background-color: #add8e6; /* Light blue for primary buttons */
80
+ color: black;
81
+ }
82
+ .stButton>button:first-child:hover {
83
+ background-color: #87ceeb; /* Slightly darker blue on hover */
84
+ }
85
+ .stButton>button:nth-child(2) {
86
+ background-color: #b0e0e6; /* Even lighter blue for secondary buttons */
87
+ color: black;
88
+ }
89
+ .stButton>button:nth-child(2):hover {
90
+ background-color: #add8e6; /* Slightly darker blue on hover */
91
+ }
92
+ [data-testid="stFileUploadDropzone"] {
93
+ background-color: white; /* White background for file upload */
94
+ }
95
+ [data-testid="stFileUploadDropzone"] .stDropzone, [data-testid="stFileUploadDropzone"] .stDropzone input {
96
+ color: black; /* Ensure file upload text is black */
97
+ }
98
+
99
+ .stButton>button:active {
100
+ outline: 2px solid green; /* Green outline when the button is pressed */
101
+ outline-offset: 2px;
102
+ }
103
+ </style>
104
+ """
105
+
106
+ st.write(css, unsafe_allow_html=True)
107
+ #st.sidebar.image('lt.png', width=250)
108
+ #-------------
109
+ llm=ChatGroq(groq_api_key=groq_api_key,
110
+ model_name="Llama-3.1-70b-Versatile", temperature = 0.0, streaming=True)
111
+ #--------------
112
+ doc_retriever_ESG = None
113
+ doc_retriever_financials = None
114
+ #--------------
115
+
116
+ #@st.cache_data
117
+ def load_or_parse_data_ESG():
118
+ data_file = "./data/parsed_data_ESG.pkl"
119
+
120
+ parsingInstructionUber10k = """The provided document contain detailed information about the company's environmental, social and governance matters.
121
+ It contains several tables, figures and statistical information about CO2 emissions and energy consumption.
122
+ Give only precide CO2 and energy consumotion levels inly from the context documents.
123
+ You must never provide false numeric or statistical data that is not included in the context document.
124
+ Include tables and numeric data always when possible. Only refer to other sources if the context document refers to them or if necessary to provide additional understanding to company's own data."""
125
+
126
+ parser = LlamaParse(api_key=LLAMA_PARSE_API_KEY,
127
+ result_type="markdown",
128
+ parsing_instruction=parsingInstructionUber10k,
129
+ max_timeout=5000,
130
+ gpt4o_mode=True,
131
+ )
132
+
133
+ file_extractor = {".pdf": parser}
134
+ reader = SimpleDirectoryReader("./ESG_Documents", file_extractor=file_extractor)
135
+ documents = reader.load_data()
136
+
137
+ print("Saving the parse results in .pkl format ..........")
138
+ joblib.dump(documents, data_file)
139
+
140
+ # Set the parsed data to the variable
141
+ parsed_data_ESG = documents
142
+
143
+ return parsed_data_ESG
144
+
145
+ #@st.cache_data
146
+ def load_or_parse_data_financials():
147
+ data_file = "./data/parsed_data_financials.pkl"
148
+
149
+ parsingInstructionUber10k = """The provided document is the company's annual reports and includes financial statement, balance sheet, cash flow sheet and description of the company's business and operations.
150
+ It contains several tabless, figures and statistical information. You must be precise while answering the questions and never provide false numeric or statistical data."""
151
+
152
+ parser = LlamaParse(api_key=LLAMA_PARSE_API_KEY,
153
+ result_type="markdown",
154
+ parsing_instruction=parsingInstructionUber10k,
155
+ max_timeout=5000,
156
+ gpt4o_mode=True,
157
+ )
158
+
159
+ file_extractor = {".pdf": parser}
160
+ reader = SimpleDirectoryReader("./Financial_Documents", file_extractor=file_extractor)
161
+ documents = reader.load_data()
162
+
163
+ print("Saving the parse results in .pkl format ..........")
164
+ joblib.dump(documents, data_file)
165
+
166
+ # Set the parsed data to the variable
167
+ parsed_data_financials = documents
168
+
169
+ return parsed_data_financials
170
+
171
+ #--------------
172
+ # Create vector database
173
+
174
+ @st.cache_resource
175
+ def create_vector_database_ESG():
176
+ # Call the function to either load or parse the data
177
+ llama_parse_documents = load_or_parse_data_ESG()
178
+
179
+ with open('data/output_ESG.md', 'a') as f: # Open the file in append mode ('a')
180
+ for doc in llama_parse_documents:
181
+ f.write(doc.text + '\n')
182
+
183
+ markdown_path = "data/output_ESG.md"
184
+ loader = UnstructuredMarkdownLoader(markdown_path)
185
+ documents = loader.load()
186
+ # Split loaded documents into chunks
187
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=400, chunk_overlap=30)
188
+ docs = text_splitter.split_documents(documents)
189
+
190
+ #len(docs)
191
+ print(f"length of documents loaded: {len(documents)}")
192
+ print(f"total number of document chunks generated :{len(docs)}")
193
+ embed_model = HuggingFaceEmbeddings()
194
+
195
+ vs = Chroma.from_documents(
196
+ documents=docs,
197
+ embedding=embed_model,
198
+ collection_name="rag",
199
+ )
200
+ doc_retriever_ESG = vs.as_retriever()
201
+
202
+ index = VectorStoreIndex.from_documents(llama_parse_documents)
203
+ query_engine = index.as_query_engine()
204
+
205
+ return doc_retriever_ESG, query_engine
206
+
207
+ @st.cache_resource
208
+ def create_vector_database_financials():
209
+ # Call the function to either load or parse the data
210
+ llama_parse_documents = load_or_parse_data_financials()
211
+
212
+ with open('data/output_financials.md', 'a') as f: # Open the file in append mode ('a')
213
+ for doc in llama_parse_documents:
214
+ f.write(doc.text + '\n')
215
+
216
+ markdown_path = "data/output_financials.md"
217
+ loader = UnstructuredMarkdownLoader(markdown_path)
218
+ documents = loader.load()
219
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=100, chunk_overlap=15)
220
+ docs = text_splitter.split_documents(documents)
221
+
222
+ embed_model = HuggingFaceEmbeddings()
223
+
224
+ vs = Chroma.from_documents(
225
+ documents=docs,
226
+ embedding=embed_model,
227
+ collection_name="rag"
228
+ )
229
+ doc_retriever_financials = vs.as_retriever()
230
+
231
+ index = VectorStoreIndex.from_documents(llama_parse_documents)
232
+ query_engine_financials = index.as_query_engine()
233
+
234
+ print('Vector DB created successfully !')
235
+ return doc_retriever_financials, query_engine_financials
236
+
237
+ #--------------
238
+ ESG_analysis_button_key = "ESG_strategy_button"
239
+ portfolio_analysis_button_key = "portfolio_strategy_button"
240
+
241
+ #---------------
242
+ def delete_files_and_folders(folder_path):
243
+ for root, dirs, files in os.walk(folder_path, topdown=False):
244
+ for file in files:
245
+ try:
246
+ os.unlink(os.path.join(root, file))
247
+ except Exception as e:
248
+ st.error(f"Error deleting {os.path.join(root, file)}: {e}")
249
+ for dir in dirs:
250
+ try:
251
+ os.rmdir(os.path.join(root, dir))
252
+ except Exception as e:
253
+ st.error(f"Error deleting directory {os.path.join(root, dir)}: {e}")
254
+ #---------------
255
+
256
+ uploaded_files_ESG = st.sidebar.file_uploader("Choose a Sustainability Report", accept_multiple_files=True, key="ESG_files")
257
+ for uploaded_file in uploaded_files_ESG:
258
+ st.write("filename:", uploaded_file.name)
259
+ def save_uploadedfile(uploadedfile):
260
+ with open(os.path.join("ESG_Documents",uploadedfile.name),"wb") as f:
261
+ f.write(uploadedfile.getbuffer())
262
+ return st.success("Saved File:{} to ESG_Documents".format(uploadedfile.name))
263
+ save_uploadedfile(uploaded_file)
264
+
265
+ uploaded_files_financials = st.sidebar.file_uploader("Choose an Annual Report", accept_multiple_files=True, key="financial_files")
266
+ for uploaded_file in uploaded_files_financials:
267
+ st.write("filename:", uploaded_file.name)
268
+ def save_uploadedfile(uploadedfile):
269
+ with open(os.path.join("Financial_Documents",uploadedfile.name),"wb") as f:
270
+ f.write(uploadedfile.getbuffer())
271
+ return st.success("Saved File:{} to Financial_Documents".format(uploadedfile.name))
272
+ save_uploadedfile(uploaded_file)
273
+
274
+ #---------------
275
+ def ESG_strategy():
276
+ doc_retriever_ESG, _ = create_vector_database_ESG()
277
+ prompt_template = """<|system|>
278
+ You are a seasoned specialist in environmental, social and governance matters. You write expert analyses for institutional investors. Always use figures, nemerical and statistical data when possible. Output must have sub-headings in bold font and be fluent.<|end|>
279
+ <|user|>
280
+ Answer the {question} based on the information you find in context: {context} <|end|>
281
+ <|assistant|>"""
282
+
283
+ prompt = PromptTemplate(template=prompt_template, input_variables=["question", "context"])
284
+
285
+ qa = (
286
+ {
287
+ "context": doc_retriever_ESG,
288
+ "question": RunnablePassthrough(),
289
+ }
290
+ | prompt
291
+ | llm
292
+ | StrOutputParser()
293
+ )
294
+
295
+ ESG_answer_1 = qa.invoke("Give a summary what specific ESG measures the company has taken recently and compare these to the best practices.")
296
+ ESG_answer_2 = qa.invoke("Does the company's main business fall under the European Union's taxonomy regulation? Is the company taxonomy compliant under European Union Taxonomy Regulation?")
297
+ ESG_answer_3 = qa.invoke("Explain what items of ESG information the company publishes. Describe what ESG transparency commitments the company has given. Does the company follow the Paris Treaty's obligation to limit globabl warming to 1.5 celcius degrees?")
298
+ ESG_answer_4 = qa.invoke("Does the company have carbon emissions reduction plan and has the company reached its carbod dioxide reduction objectives? Set out in a table the company's carbon footprint by location and its development from the context. Set out carbon dioxide emissions in relation to turnover.")
299
+ ESG_answer_5 = qa.invoke("Describe and set out in a table the following carbon emissions figures: (i) Scope 1 CO2 emissions, (ii) Scope 2 CO2, and (iii) Scope 3 CO2 emissions. Set out the material changes relating to these figures.")
300
+ ESG_answer_6 = qa.invoke("Set out in a table the company's energy and renewable energy usage for each material activity coverning the available years. Explain the energy efficiency measures taken by the company.")
301
+ ESG_answer_7 = qa.invoke("Does the company follow UN Guiding Principles on Business and Human Rights, ILO Declaration on Fundamental Principles and Rights at Work or OECD Guidelines for Multinational Enterprises that involve affected communities? Set out the measures taken to have the gender balance on the upper management of the company.")
302
+ ESG_answer_8 = qa.invoke("List the environmental permits and certifications held by the company. Set out and explain any environmental procedures and investigations and decisions taken against the company. Answer whether the company's locations or operations are connected to areas sensitive in relation to biodiversity.")
303
+ ESG_answer_9 = qa.invoke("Set out waste produces by the company and possible waste into the soil by real estate. Describe if the company's real estates have hazardous waste.")
304
+ ESG_answer_10 = qa.invoke("What percentage of women are represented in the (i) board, (ii) executive directors and (iii) upper management?")
305
+ ESG_answer_11 = qa.invoke("What policies has the company implemented to counter money laundering and corruption?")
306
+
307
+ ESG_output = f"**__Summary of ESG reporting and obligations:__** {ESG_answer_1} \n\n **__Compliance with taxonomy:__** \n\n {ESG_answer_2} \n\n **__Disclosure transparency:__** \n\n {ESG_answer_3} \n\n **__Carbon footprint:__** \n\n {ESG_answer_4} \n\n **__Carbon dioxide emissions:__** \n\n {ESG_answer_5} \n\n **__Renewable energy:__** \n\n {ESG_answer_6} \n\n **__Human rights compliance:__** \n\n {ESG_answer_7} \n\n **__Management and gender balance:__** \n\n {ESG_answer_8} \n\n **__Waste and other emissions:__** {ESG_answer_9} \n\n **__Gender equality:__** {ESG_answer_10} \n\n **__Anti-money laundering:__** {ESG_answer_11}"
308
+ financial_output = ESG_output
309
+
310
+ with open("ESG_analysis.txt", 'w') as file:
311
+ file.write(financial_output)
312
+
313
+ return financial_output
314
+
315
+ #-------------
316
+ @st.cache_data
317
+ def generate_ESG_strategy() -> str:
318
+ ESG_output = ESG_strategy()
319
+ st.session_state.results["ESG_analysis_button_key"] = ESG_output
320
+ return ESG_output
321
+
322
+ #---------------
323
+ #@st.cache_data
324
+ def create_pdf():
325
+ text_file = "ESG_analysis.txt"
326
+ pdf = FPDF('P', 'mm', 'A4')
327
+ pdf.add_page()
328
+ pdf.set_margins(10, 10, 10)
329
+ pdf.set_font("Arial", size=15)
330
+ #image = "lt.png"
331
+ #pdf.image(image, w = 40)
332
+ # Add introductory lines
333
+ #pdf.cell(0, 10, txt="Company name", ln=1, align='C')
334
+ pdf.cell(0, 10, txt="Structured ESG Analysis", ln=2, align='C')
335
+ pdf.ln(5)
336
+
337
+ pdf.set_font("Arial", size=11)
338
+ try:
339
+ with open(text_file, 'r', encoding='utf-8') as f:
340
+ for line in f:
341
+ # Replace '\u2019' with a different character or string
342
+ #line = line.replace('\u2019', "'") # For example, replace with apostrophe
343
+ #line = line.replace('\u2265', "'") # For example, replace with apostrophe
344
+ #pdf.multi_cell(0, 6, txt=line, align='L')
345
+ pdf.multi_cell(0, 6, txt=line.encode('latin-1', 'replace').decode('latin-1'), align='L')
346
+ pdf.ln(5)
347
+ except UnicodeEncodeError:
348
+ print("UnicodeEncodeError: Some characters could not be encoded in Latin-1. Skipping...")
349
+ pass # Skip the lines causing UnicodeEncodeError
350
+
351
+ output_pdf_path = "ESG_analysis.pdf"
352
+ pdf.output(output_pdf_path)
353
+
354
+ #----------------
355
+ #llm = build_llm()
356
+
357
+ if 'results' not in st.session_state:
358
+ st.session_state.results = {
359
+ "ESG_analysis_button_key": {}
360
+ }
361
+
362
+ loaders = {'.pdf': PyMuPDFLoader,
363
+ '.xml': UnstructuredXMLLoader,
364
+ '.csv': CSVLoader,
365
+ }
366
+
367
+ def create_directory_loader(file_type, directory_path):
368
+ return DirectoryLoader(
369
+ path=directory_path,
370
+ glob=f"**/*{file_type}",
371
+ loader_cls=loaders[file_type],
372
+ )
373
+
374
+ strategies_container = st.container()
375
+ with strategies_container:
376
+ mrow1_col1, mrow1_col2 = st.columns(2)
377
+
378
+ st.sidebar.info("To get started, please upload the documents from the company you would like to analyze.")
379
+ button_container = st.sidebar.container()
380
+ if os.path.exists("ESG_analysis.txt"):
381
+ create_pdf()
382
+ with open("ESG_analysis.pdf", "rb") as pdf_file:
383
+ PDFbyte = pdf_file.read()
384
+
385
+ st.sidebar.download_button(label="Download Analyses",
386
+ data=PDFbyte,
387
+ file_name="strategy_sheet.pdf",
388
+ mime='application/octet-stream',
389
+ )
390
+
391
+ if button_container.button("Clear All"):
392
+
393
+ st.session_state.button_states = {
394
+ "ESG_analysis_button_key": False,
395
+ }
396
+ st.session_state.button_states = {
397
+ "portfolio_analysis_button_key": False,
398
+ }
399
+ st.session_state.results = {}
400
+
401
+ st.session_state['history'] = []
402
+ st.session_state['generated'] = ["Let's discuss the ESG issues of the company 🤗"]
403
+ st.session_state['past'] = ["Hey ! 👋"]
404
+ st.cache_data.clear()
405
+ st.cache_resource.clear()
406
+
407
+ # Check if the subfolder exists
408
+ if os.path.exists("ESG_Documents"):
409
+ for filename in os.listdir("ESG_Documents"):
410
+ file_path = os.path.join("ESG_Documents", filename)
411
+ try:
412
+ if os.path.isfile(file_path):
413
+ os.unlink(file_path)
414
+ except Exception as e:
415
+ st.error(f"Error deleting {file_path}: {e}")
416
+ else:
417
+ pass
418
+
419
+ if os.path.exists("Financial_Documents"):
420
+ # Iterate through files in the subfolder and delete them
421
+ for filename in os.listdir("Financial_Documents"):
422
+ file_path = os.path.join("Financial_Documents", filename)
423
+ try:
424
+ if os.path.isfile(file_path):
425
+ os.unlink(file_path)
426
+ except Exception as e:
427
+ st.error(f"Error deleting {file_path}: {e}")
428
+ else:
429
+ pass
430
+ # st.warning("No 'data' subfolder found.")
431
+
432
+ if os.path.exists("ESG_Documents_Portfolio"):
433
+ # Iterate through files in the subfolder and delete them
434
+ for filename in os.listdir("ESG_Documents_Portfolio"):
435
+ file_path = os.path.join("ESG_Documents_Portfolio", filename)
436
+ try:
437
+ if os.path.isfile(file_path):
438
+ os.unlink(file_path)
439
+ except Exception as e:
440
+ st.error(f"Error deleting {file_path}: {e}")
441
+ else:
442
+ pass
443
+ # st.warning("No 'data' subfolder found.")
444
+
445
+ folders_to_clean = ["data", "chroma_db_portfolio", "chroma_db_LT", "chroma_db_fin"]
446
+
447
+ for folder_path in folders_to_clean:
448
+ if os.path.exists(folder_path):
449
+ for item in os.listdir(folder_path):
450
+ item_path = os.path.join(folder_path, item)
451
+ try:
452
+ if os.path.isfile(item_path) or os.path.islink(item_path):
453
+ os.unlink(item_path) # Remove files or symbolic links
454
+ elif os.path.isdir(item_path):
455
+ shutil.rmtree(item_path) # Remove subfolders and all their contents
456
+ except Exception as e:
457
+ st.error(f"Error deleting {item_path}: {e}")
458
+ else:
459
+ pass
460
+ # st.warning(f"No '{folder_path}' folder found.")
461
+
462
+ with mrow1_col1:
463
+ st.subheader("Summary of the ESG Analysis")
464
+ st.info("This tool is designed to provide a comprehensive ESG risk analysis for institutional investors.")
465
+ button_container2 = st.container()
466
+ if "button_states" not in st.session_state:
467
+ st.session_state.button_states = {
468
+ "ESG_analysis_button_key": False,
469
+ }
470
+
471
+ if "results" not in st.session_state:
472
+ st.session_state.results = {}
473
+
474
+ if button_container2.button("ESG Analysis", key=ESG_analysis_button_key):
475
+ st.session_state.button_states[ESG_analysis_button_key] = True
476
+ result_generator = generate_ESG_strategy() # Call the generator function
477
+ st.session_state.results["ESG_analysis_output"] = result_generator
478
+
479
+ if "ESG_analysis_output" in st.session_state.results:
480
+ st.write(st.session_state.results["ESG_analysis_output"])
481
+ st.divider()
482
+
483
+ with mrow1_col2:
484
+ if "ESG_analysis_button_key" in st.session_state.results and st.session_state.results["ESG_analysis_button_key"]:
485
+
486
+ doc_retriever_ESG, query_engine = create_vector_database_ESG()
487
+ doc_retriever_financials, query_engine_financials = create_vector_database_financials()
488
+ memory = ConversationBufferMemory(memory_key="chat_history", k=3, return_messages=True)
489
+ search = SerpAPIWrapper()
490
+
491
+ # Updated prompt templates to include chat history
492
+ def format_chat_history(chat_history):
493
+ """Format chat history as a single string for input to the chain."""
494
+ formatted_history = "\n".join([f"User: {entry['input']}\nAI: {entry['output']}" for entry in chat_history])
495
+ return formatted_history
496
+
497
+ prompt_financials = PromptTemplate.from_template(
498
+ template="""
499
+ You are a seasoned corporate finance specialist.
500
+ Use figures, numerical, and statistical data when possible. Never give false information, numbers or data.
501
+
502
+ Conversation history:
503
+ {chat_history}
504
+
505
+ Based on the context: {context}, answer the following question: {question}.
506
+ """
507
+ )
508
+
509
+ prompt_ESG = PromptTemplate.from_template(
510
+ template="""
511
+ You are a seasoned finance specialist and a specialist in environmental, social, and governance matters.
512
+ Use figures, numerical, and statistical data when possible. Never give false information, numbers or data.
513
+
514
+ Conversation history:
515
+ {chat_history}
516
+
517
+ Based on the context: answer the following question: {question}.
518
+ """
519
+ )
520
+
521
+ # LCEL Chains with memory integration
522
+ financials_chain = (
523
+ {
524
+ "context": doc_retriever_financials,
525
+ # Lambda function now accepts one argument (even if unused)
526
+ "chat_history": lambda _: format_chat_history(memory.load_memory_variables({})["chat_history"]),
527
+ "question": RunnablePassthrough(),
528
+ }
529
+ | prompt_financials
530
+ | llm
531
+ | StrOutputParser()
532
+ )
533
+
534
+ ESG_chain = (
535
+ {
536
+ "context": doc_retriever_ESG,
537
+ "chat_history": lambda _: format_chat_history(memory.load_memory_variables({})["chat_history"]),
538
+ "question": RunnablePassthrough(),
539
+ }
540
+ | prompt_ESG
541
+ | llm
542
+ | StrOutputParser()
543
+ )
544
+
545
+ # Define the tools with LCEL expressions
546
+ # Define the vector query engine tool
547
+ vector_query_tool_ESG = Tool(
548
+ name="Vector Query Engine ESG",
549
+ func=lambda query: query_engine.query(query), # Use query_engine to query the vector database
550
+ description="Useful for answering questions that require ESG figures, data and statistics.",
551
+ )
552
+
553
+ vector_query_tool_financials = Tool(
554
+ name="Vector Query Engine Financials",
555
+ func=lambda query: query_engine_financials.query(query), # Use query_engine to query the vector database
556
+ description="Useful for answering questions that require financial figures, data and statistics.",
557
+ )
558
+
559
+ # Create a function to validate responses
560
+ def validate_esg_response(query):
561
+ esg_response = vector_query_tool_ESG.func(query)
562
+ esg_validation = ESG_chain.invoke({
563
+ "context": doc_retriever_ESG,
564
+ "chat_history": format_chat_history(memory.load_memory_variables({})["chat_history"]),
565
+ "question": esg_response
566
+ })
567
+ return esg_validation
568
+
569
+ def validate_financials_response(query):
570
+ financials_response = vector_query_tool_financials.func(query)
571
+ financials_validation = financials_chain.invoke({
572
+ "context": doc_retriever_financials,
573
+ "chat_history": format_chat_history(memory.load_memory_variables({})["chat_history"]),
574
+ "question": financials_response
575
+ })
576
+ return financials_validation
577
+
578
+ # Update the tools list to include validation
579
+ tools = [
580
+ Tool(
581
+ name="Search Tool",
582
+ func=search.run,
583
+ description="Useful when other tools do not provide the answer.",
584
+ ),
585
+ Tool(
586
+ name="Validate ESG Response",
587
+ func=validate_esg_response,
588
+ description="Validates the response of the Vector Query Engine ESG tool.",
589
+ ),
590
+ Tool(
591
+ name="Validate Financials Response",
592
+ func=validate_financials_response,
593
+ description="Validates the response of the Vector Query Engine Financials tool.",
594
+ ),
595
+ vector_query_tool_ESG,
596
+ vector_query_tool_financials,
597
+ ]
598
+
599
+ # Initialize the agent with LCEL tools and memory
600
+ agent = initialize_agent(
601
+ tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True, memory=memory, handle_parsing_errors=True)
602
+ def conversational_chat(query):
603
+ # Get the result from the agent
604
+ result = agent.invoke({"input": query, "chat_history": st.session_state['history']})
605
+
606
+ # Handle different response types
607
+ if isinstance(result, dict):
608
+ # Extract the main content if the result is a dictionary
609
+ result = result.get("output", "") # Adjust the key as needed based on your agent's output
610
+ elif isinstance(result, list):
611
+ # If the result is a list, join it into a single string
612
+ result = "\n".join(result)
613
+ elif not isinstance(result, str):
614
+ # Convert the result to a string if it is not already one
615
+ result = str(result)
616
+
617
+ # Add the query and the result to the session state
618
+ st.session_state['history'].append((query, result))
619
+
620
+ # Update memory with the conversation
621
+ memory.save_context({"input": query}, {"output": result})
622
+
623
+ # Return the result
624
+ return result
625
+
626
+ # Ensure session states are initialized
627
+ if 'history' not in st.session_state:
628
+ st.session_state['history'] = []
629
+
630
+ if 'generated' not in st.session_state:
631
+ st.session_state['generated'] = ["Let's discuss the ESG matters and financial matters 🤗"]
632
+
633
+ if 'past' not in st.session_state:
634
+ st.session_state['past'] = ["Hey ! 👋"]
635
+
636
+ if 'input' not in st.session_state:
637
+ st.session_state['input'] = ""
638
+
639
+ # Streamlit layout
640
+ st.subheader("Discuss the ESG and financial matters")
641
+ st.info("This tool is designed to enable discussion about the ESG and financial matters concerning the company.")
642
+ response_container = st.container()
643
+ container = st.container()
644
+
645
+ with container:
646
+ with st.form(key='my_form'):
647
+ user_input = st.text_input("Query:", placeholder="What would you like to know about ESG and financial matters", key='input')
648
+ submit_button = st.form_submit_button(label='Send')
649
+ if submit_button and user_input:
650
+ output = conversational_chat(user_input)
651
+ st.session_state['past'].append(user_input)
652
+ st.session_state['generated'].append(output)
653
+ user_input = "Query:"
654
+ #st.session_state['input'] = ""
655
+ # Display generated responses
656
+ if st.session_state['generated']:
657
+ with response_container:
658
+ for i in range(len(st.session_state['generated'])):
659
+ message(st.session_state["past"][i], is_user=True, key=str(i) + '_user', avatar_style="shapes")
660
+ message(st.session_state["generated"][i], key=str(i), avatar_style="icons")
661
+
662
+
663
+
664
+