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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
import json
|
9 |
+
from langchain_community.utilities import SerpAPIWrapper
|
10 |
+
from llama_index.core import VectorStoreIndex
|
11 |
+
from langchain_core.output_parsers import StrOutputParser
|
12 |
+
from langchain_core.runnables import RunnablePassthrough
|
13 |
+
from langchain_groq import ChatGroq
|
14 |
+
from langchain.chains import LLMChain
|
15 |
+
from langchain.agents import AgentType, Tool, initialize_agent, AgentExecutor
|
16 |
+
from llama_parse import LlamaParse
|
17 |
+
from langchain_community.document_loaders import UnstructuredMarkdownLoader
|
18 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
19 |
+
from llama_index.core import SimpleDirectoryReader
|
20 |
+
from dotenv import load_dotenv, find_dotenv
|
21 |
+
import pandas as pd
|
22 |
+
from streamlit_chat import message
|
23 |
+
from langchain_community.vectorstores import Chroma
|
24 |
+
from langchain_community.utilities import SerpAPIWrapper
|
25 |
+
from langchain.chains import RetrievalQA
|
26 |
+
from langchain_community.document_loaders import DirectoryLoader
|
27 |
+
from langchain_community.document_loaders import PyMuPDFLoader
|
28 |
+
from langchain_community.document_loaders import UnstructuredXMLLoader
|
29 |
+
from langchain_community.document_loaders import CSVLoader
|
30 |
+
from langchain.prompts import PromptTemplate
|
31 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
32 |
+
from langchain.memory import ConversationBufferMemory
|
33 |
+
from langchain.prompts import PromptTemplate
|
34 |
+
import joblib
|
35 |
+
import nltk
|
36 |
+
|
37 |
+
import nest_asyncio # noqa: E402
|
38 |
+
nest_asyncio.apply()
|
39 |
+
|
40 |
+
load_dotenv()
|
41 |
+
load_dotenv(find_dotenv())
|
42 |
+
|
43 |
+
nltk.download('averaged_perceptron_tagger_eng')
|
44 |
+
|
45 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
46 |
+
SERPAPI_API_KEY = os.environ["SERPAPI_API_KEY"]
|
47 |
+
GOOGLE_CSE_ID = os.environ["GOOGLE_CSE_ID"]
|
48 |
+
GOOGLE_API_KEY = os.environ["GOOGLE_API_KEY"]
|
49 |
+
LLAMA_PARSE_API_KEY = os.environ["LLAMA_PARSE_API_KEY"]
|
50 |
+
HUGGINGFACEHUB_API_TOKEN = os.environ["HUGGINGFACEHUB_API_TOKEN"]
|
51 |
+
groq_api_key=os.getenv('GROQ_API_KEY')
|
52 |
+
|
53 |
+
st.set_page_config(layout="wide")
|
54 |
+
|
55 |
+
css = """
|
56 |
+
<style>
|
57 |
+
[data-testid="stAppViewContainer"] {
|
58 |
+
background-color: #f8f9fa; /* Very light grey */
|
59 |
+
}
|
60 |
+
[data-testid="stSidebar"] {
|
61 |
+
background-color: white;
|
62 |
+
color: black;
|
63 |
+
}
|
64 |
+
[data-testid="stAppViewContainer"] * {
|
65 |
+
color: black; /* Ensure all text is black */
|
66 |
+
}
|
67 |
+
button {
|
68 |
+
background-color: #add8e6; /* Light blue for primary buttons */
|
69 |
+
color: black;
|
70 |
+
border: 2px solid green; /* Green border */
|
71 |
+
}
|
72 |
+
button:hover {
|
73 |
+
background-color: #87ceeb; /* Slightly darker blue on hover */
|
74 |
+
}
|
75 |
+
button:active {
|
76 |
+
outline: 2px solid green; /* Green outline when the button is pressed */
|
77 |
+
outline-offset: 2px; /* Space between button and outline */
|
78 |
+
}
|
79 |
+
.stButton>button:first-child {
|
80 |
+
background-color: #add8e6; /* Light blue for primary buttons */
|
81 |
+
color: black;
|
82 |
+
}
|
83 |
+
.stButton>button:first-child:hover {
|
84 |
+
background-color: #87ceeb; /* Slightly darker blue on hover */
|
85 |
+
}
|
86 |
+
.stButton>button:nth-child(2) {
|
87 |
+
background-color: #b0e0e6; /* Even lighter blue for secondary buttons */
|
88 |
+
color: black;
|
89 |
+
}
|
90 |
+
.stButton>button:nth-child(2):hover {
|
91 |
+
background-color: #add8e6; /* Slightly darker blue on hover */
|
92 |
+
}
|
93 |
+
[data-testid="stFileUploadDropzone"] {
|
94 |
+
background-color: white; /* White background for file upload */
|
95 |
+
}
|
96 |
+
[data-testid="stFileUploadDropzone"] .stDropzone, [data-testid="stFileUploadDropzone"] .stDropzone input {
|
97 |
+
color: black; /* Ensure file upload text is black */
|
98 |
+
}
|
99 |
+
|
100 |
+
.stButton>button:active {
|
101 |
+
outline: 2px solid green; /* Green outline when the button is pressed */
|
102 |
+
outline-offset: 2px;
|
103 |
+
}
|
104 |
+
</style>
|
105 |
+
"""
|
106 |
+
|
107 |
+
st.write(css, unsafe_allow_html=True)
|
108 |
+
|
109 |
+
st.sidebar.image('StratXcel.png', width=150)
|
110 |
+
|
111 |
+
#--------------
|
112 |
+
def load_credentials(filepath):
|
113 |
+
with open(filepath, 'r') as file:
|
114 |
+
return json.load(file)
|
115 |
+
|
116 |
+
# Load credentials from 'credentials.json'
|
117 |
+
credentials = load_credentials('Assets/credentials.json')
|
118 |
+
|
119 |
+
# Initialize session state if not already done
|
120 |
+
if 'logged_in' not in st.session_state:
|
121 |
+
st.session_state.logged_in = False
|
122 |
+
st.session_state.username = ''
|
123 |
+
|
124 |
+
# Function to handle login
|
125 |
+
def login(username, password):
|
126 |
+
if username in credentials and credentials[username] == password:
|
127 |
+
st.session_state.logged_in = True
|
128 |
+
st.session_state.username = username
|
129 |
+
st.rerun() # Rerun to reflect login state
|
130 |
+
else:
|
131 |
+
st.session_state.logged_in = False
|
132 |
+
st.session_state.username = ''
|
133 |
+
st.error("Invalid username or password.")
|
134 |
+
|
135 |
+
# Function to handle logout
|
136 |
+
def logout():
|
137 |
+
st.session_state.logged_in = False
|
138 |
+
st.session_state.username = ''
|
139 |
+
st.rerun() # Rerun to reflect logout state
|
140 |
+
|
141 |
+
# If not logged in, show login form
|
142 |
+
if not st.session_state.logged_in:
|
143 |
+
st.sidebar.write("Login")
|
144 |
+
username = st.sidebar.text_input('Username')
|
145 |
+
password = st.sidebar.text_input('Password', type='password')
|
146 |
+
if st.sidebar.button('Login'):
|
147 |
+
login(username, password)
|
148 |
+
# Stop the script here if the user is not logged in
|
149 |
+
st.stop()
|
150 |
+
|
151 |
+
# If logged in, show logout button and main content
|
152 |
+
if st.session_state.logged_in:
|
153 |
+
st.sidebar.write(f"Welcome, {st.session_state.username}!")
|
154 |
+
if st.sidebar.button('Logout'):
|
155 |
+
logout()
|
156 |
+
#-------------
|
157 |
+
llm=ChatGroq(groq_api_key=groq_api_key,
|
158 |
+
model_name="Llama-3.1-70b-Versatile", temperature = 0.0, streaming=True)
|
159 |
+
#model_name="Llama-3.1-70b-Versatile", temperature = 0.0, streaming=True)
|
160 |
+
|
161 |
+
llm_tool=ChatGroq(groq_api_key=groq_api_key,
|
162 |
+
model_name="llama3-groq-70b-8192-tool-use-preview", temperature = 0.0, streaming=True)
|
163 |
+
#model_name="Llama-3.1-70b-Versatile", temperature = 0.0, streaming=True)
|
164 |
+
#--------------
|
165 |
+
doc_retriever_ESG = None
|
166 |
+
#--------------
|
167 |
+
|
168 |
+
#@st.cache_data
|
169 |
+
def load_or_parse_data_ESG():
|
170 |
+
data_file = "./data/parsed_data_ESG.pkl"
|
171 |
+
|
172 |
+
parsingInstructionUber10k = """The provided document contains detailed information about the company's environmental, social, and governance matters.
|
173 |
+
It contains several tables, figures, and statistical information about CO2 emissions and energy consumption.
|
174 |
+
Give only precise CO2 and energy consumption levels from the context documents.
|
175 |
+
You must never provide false numeric or statistical data not included in the context document.
|
176 |
+
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 the company's own data."""
|
177 |
+
|
178 |
+
parser = LlamaParse(api_key=LLAMA_PARSE_API_KEY,
|
179 |
+
result_type="markdown",
|
180 |
+
parsing_instruction=parsingInstructionUber10k,
|
181 |
+
max_timeout=5000,
|
182 |
+
gpt4o_mode=True,
|
183 |
+
)
|
184 |
+
|
185 |
+
file_extractor = {".pdf": parser}
|
186 |
+
reader = SimpleDirectoryReader("./ESG_Documents", file_extractor=file_extractor)
|
187 |
+
documents = reader.load_data()
|
188 |
+
|
189 |
+
print("Saving the parse results in .pkl format ..........")
|
190 |
+
joblib.dump(documents, data_file)
|
191 |
+
|
192 |
+
# Set the parsed data to the variable
|
193 |
+
parsed_data_ESG = documents
|
194 |
+
|
195 |
+
return parsed_data_ESG
|
196 |
+
|
197 |
+
#--------------
|
198 |
+
# Create vector database
|
199 |
+
|
200 |
+
@st.cache_resource
|
201 |
+
def create_vector_database_ESG():
|
202 |
+
# Call the function to either load or parse the data
|
203 |
+
llama_parse_documents = load_or_parse_data_ESG()
|
204 |
+
|
205 |
+
with open('data/output_ESG.md', 'a') as f: # Open the file in append mode ('a')
|
206 |
+
for doc in llama_parse_documents:
|
207 |
+
f.write(doc.text + '\n')
|
208 |
+
|
209 |
+
markdown_path = "data/output_ESG.md"
|
210 |
+
loader = UnstructuredMarkdownLoader(markdown_path)
|
211 |
+
documents = loader.load()
|
212 |
+
# Split loaded documents into chunks
|
213 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=400, chunk_overlap=30)
|
214 |
+
docs = text_splitter.split_documents(documents)
|
215 |
+
|
216 |
+
#len(docs)
|
217 |
+
print(f"length of documents loaded: {len(documents)}")
|
218 |
+
print(f"total number of document chunks generated :{len(docs)}")
|
219 |
+
persist_directory = "./chroma_db_LT" # Specify directory for Chroma persistence
|
220 |
+
embed_model = HuggingFaceEmbeddings()
|
221 |
+
|
222 |
+
vs = Chroma.from_documents(
|
223 |
+
documents=docs,
|
224 |
+
embedding=embed_model,
|
225 |
+
collection_name="rag_ESG",
|
226 |
+
persist_directory=persist_directory # Ensure persistence
|
227 |
+
)
|
228 |
+
|
229 |
+
doc_retriever_ESG = vs.as_retriever()
|
230 |
+
|
231 |
+
index = VectorStoreIndex.from_documents(llama_parse_documents)
|
232 |
+
query_engine = index.as_query_engine()
|
233 |
+
|
234 |
+
return doc_retriever_ESG, query_engine
|
235 |
+
|
236 |
+
#--------------
|
237 |
+
ESG_analysis_button_key = "ESG_strategy_button"
|
238 |
+
|
239 |
+
#---------------
|
240 |
+
def delete_files_and_folders(folder_path):
|
241 |
+
for root, dirs, files in os.walk(folder_path, topdown=False):
|
242 |
+
for file in files:
|
243 |
+
try:
|
244 |
+
os.unlink(os.path.join(root, file))
|
245 |
+
except Exception as e:
|
246 |
+
st.error(f"Error deleting {os.path.join(root, file)}: {e}")
|
247 |
+
for dir in dirs:
|
248 |
+
try:
|
249 |
+
os.rmdir(os.path.join(root, dir))
|
250 |
+
except Exception as e:
|
251 |
+
st.error(f"Error deleting directory {os.path.join(root, dir)}: {e}")
|
252 |
+
#---------------
|
253 |
+
|
254 |
+
uploaded_files_ESG = st.sidebar.file_uploader("Choose a Sustainability Report", accept_multiple_files=True, key="ESG_files")
|
255 |
+
for uploaded_file in uploaded_files_ESG:
|
256 |
+
st.write("filename:", uploaded_file.name)
|
257 |
+
def save_uploadedfile(uploadedfile):
|
258 |
+
with open(os.path.join("ESG_Documents",uploadedfile.name),"wb") as f:
|
259 |
+
f.write(uploadedfile.getbuffer())
|
260 |
+
return st.success("Saved File:{} to ESG_Documents".format(uploadedfile.name))
|
261 |
+
save_uploadedfile(uploaded_file)
|
262 |
+
|
263 |
+
|
264 |
+
#---------------
|
265 |
+
def ESG_strategy():
|
266 |
+
doc_retriever_ESG, _ = create_vector_database_ESG()
|
267 |
+
|
268 |
+
prompt_template = """<|system|>
|
269 |
+
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|>
|
270 |
+
<|user|>
|
271 |
+
Answer the {question} based on the information you find in context: {context} <|end|>
|
272 |
+
<|assistant|>"""
|
273 |
+
|
274 |
+
prompt = PromptTemplate(template=prompt_template, input_variables=["question", "context"])
|
275 |
+
|
276 |
+
qa = (
|
277 |
+
{
|
278 |
+
"context": doc_retriever_ESG,
|
279 |
+
"question": RunnablePassthrough(),
|
280 |
+
}
|
281 |
+
| prompt
|
282 |
+
| llm
|
283 |
+
| StrOutputParser()
|
284 |
+
)
|
285 |
+
|
286 |
+
ESG_answer_1 = qa.invoke("Give a summary what specific ESG measures the company has taken recently and compare these to the best practices.")
|
287 |
+
ESG_answer_2 = qa.invoke("Does the company's main business fall under the European Union's taxonomy regulation? Answer whether the company is taxonomy compliant under European Union Taxonomy Regulation?")
|
288 |
+
ESG_answer_3 = qa.invoke("Describe what specific ESG transparency commitments the company has given. Give details how the company has followed the Paris Treaty's obligation to limit globabl warming to 1.5 celcius degrees.")
|
289 |
+
ESG_answer_4 = qa.invoke("Does the company have carbon emissions reduction plan? Has the company reached its carbon dioxide reduction objectives? Set the company's carbon footprint by location and its development or equivalent figures in a table. List carbon dioxide emissions compared to turnover.")
|
290 |
+
ESG_answer_5 = qa.invoke("Describe and set out in a table the following specific information: (i) Scope 1 CO2 emissions, (ii) Scope 2 CO2 emissions, and (iii) Scope 3 CO2 emissions of the company for 2021, 2022 and 2023. List the material changes relating to these figures.")
|
291 |
+
ESG_answer_6 = qa.invoke("List in a table the company's energy and renewable energy usage for each material activity. Explain the main energy efficiency measures taken by the company.")
|
292 |
+
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?")
|
293 |
+
ESG_answer_8 = qa.invoke("List the environmental permits and certifications held by the company. Set out and explain any environmental procedures, investigations, and decisions taken against the company. Answer whether the company's locations or operations are connected to areas sensitive in relation to biodiversity.")
|
294 |
+
ESG_answer_9 = qa.invoke("Set out waste management produces by the company and possible waste into the soil. Describe if the company's real estates have hazardous waste.")
|
295 |
+
ESG_answer_10 = qa.invoke("What percentage of women are represented in the (i) board, (ii) executive directors, and (iii) upper management? Set out the measures taken to have the gender balance on the upper management of the company.")
|
296 |
+
ESG_answer_11 = qa.invoke("What policies has the company implemented to counter money laundering and corruption?")
|
297 |
+
|
298 |
+
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}"
|
299 |
+
|
300 |
+
with open("ESG_analysis.txt", 'w') as file:
|
301 |
+
file.write(ESG_output)
|
302 |
+
|
303 |
+
return ESG_output
|
304 |
+
|
305 |
+
#-------------
|
306 |
+
@st.cache_data
|
307 |
+
def generate_ESG_strategy() -> str:
|
308 |
+
ESG_output = ESG_strategy()
|
309 |
+
st.session_state.results["ESG_analysis_button_key"] = ESG_output
|
310 |
+
return ESG_output
|
311 |
+
|
312 |
+
#---------------
|
313 |
+
#@st.cache_data
|
314 |
+
def create_pdf():
|
315 |
+
text_file = "ESG_analysis.txt"
|
316 |
+
pdf = FPDF('P', 'mm', 'A4')
|
317 |
+
pdf.add_page()
|
318 |
+
pdf.set_margins(10, 10, 10)
|
319 |
+
pdf.set_font("Arial", size=15)
|
320 |
+
#image = "lt.png"
|
321 |
+
#pdf.image(image, w = 40)
|
322 |
+
# Add introductory lines
|
323 |
+
#pdf.cell(0, 10, txt="Company name", ln=1, align='C')
|
324 |
+
pdf.cell(0, 10, txt="Structured ESG Analysis", ln=2, align='C')
|
325 |
+
pdf.ln(5)
|
326 |
+
|
327 |
+
pdf.set_font("Arial", size=11)
|
328 |
+
try:
|
329 |
+
with open(text_file, 'r', encoding='utf-8') as f:
|
330 |
+
for line in f:
|
331 |
+
# Replace '\u2019' with a different character or string
|
332 |
+
#line = line.replace('\u2019', "'") # For example, replace with apostrophe
|
333 |
+
#line = line.replace('\u2265', "'") # For example, replace with apostrophe
|
334 |
+
#pdf.multi_cell(0, 6, txt=line, align='L')
|
335 |
+
pdf.multi_cell(0, 6, txt=line.encode('latin-1', 'replace').decode('latin-1'), align='L')
|
336 |
+
pdf.ln(5)
|
337 |
+
except UnicodeEncodeError:
|
338 |
+
print("UnicodeEncodeError: Some characters could not be encoded in Latin-1. Skipping...")
|
339 |
+
pass # Skip the lines causing UnicodeEncodeError
|
340 |
+
|
341 |
+
output_pdf_path = "ESG_analysis.pdf"
|
342 |
+
pdf.output(output_pdf_path)
|
343 |
+
|
344 |
+
#----------------
|
345 |
+
#llm = build_llm()
|
346 |
+
|
347 |
+
if 'results' not in st.session_state:
|
348 |
+
st.session_state.results = {
|
349 |
+
"ESG_analysis_button_key": {}
|
350 |
+
}
|
351 |
+
|
352 |
+
loaders = {'.pdf': PyMuPDFLoader,
|
353 |
+
'.xml': UnstructuredXMLLoader,
|
354 |
+
'.csv': CSVLoader,
|
355 |
+
}
|
356 |
+
|
357 |
+
def create_directory_loader(file_type, directory_path):
|
358 |
+
return DirectoryLoader(
|
359 |
+
path=directory_path,
|
360 |
+
glob=f"**/*{file_type}",
|
361 |
+
loader_cls=loaders[file_type],
|
362 |
+
)
|
363 |
+
|
364 |
+
strategies_container = st.container()
|
365 |
+
with strategies_container:
|
366 |
+
mrow1_col1, mrow1_col2 = st.columns(2)
|
367 |
+
|
368 |
+
st.sidebar.info("To get started, please upload the documents from the company you would like to analyze.")
|
369 |
+
button_container = st.sidebar.container()
|
370 |
+
if os.path.exists("ESG_analysis.txt"):
|
371 |
+
create_pdf()
|
372 |
+
with open("ESG_analysis.pdf", "rb") as pdf_file:
|
373 |
+
PDFbyte = pdf_file.read()
|
374 |
+
|
375 |
+
st.sidebar.download_button(label="Download Analyses",
|
376 |
+
data=PDFbyte,
|
377 |
+
file_name="strategy_sheet.pdf",
|
378 |
+
mime='application/octet-stream',
|
379 |
+
)
|
380 |
+
|
381 |
+
if button_container.button("Clear All"):
|
382 |
+
|
383 |
+
st.session_state.button_states = {
|
384 |
+
"ESG_analysis_button_key": False,
|
385 |
+
}
|
386 |
+
|
387 |
+
st.session_state.results = {}
|
388 |
+
|
389 |
+
st.session_state['history'] = []
|
390 |
+
st.session_state['generated'] = ["Let's discuss the ESG issues of the company π€"]
|
391 |
+
st.session_state['past'] = ["Hey ! π"]
|
392 |
+
st.cache_data.clear()
|
393 |
+
st.cache_resource.clear()
|
394 |
+
|
395 |
+
# Check if the subfolder exists
|
396 |
+
if os.path.exists("ESG_Documents"):
|
397 |
+
for filename in os.listdir("ESG_Documents"):
|
398 |
+
file_path = os.path.join("ESG_Documents", filename)
|
399 |
+
try:
|
400 |
+
if os.path.isfile(file_path):
|
401 |
+
os.unlink(file_path)
|
402 |
+
except Exception as e:
|
403 |
+
st.error(f"Error deleting {file_path}: {e}")
|
404 |
+
else:
|
405 |
+
pass
|
406 |
+
|
407 |
+
with mrow1_col1:
|
408 |
+
st.subheader("Summary of the ESG Analysis")
|
409 |
+
st.info("This tool is designed to provide a comprehensive ESG risk analysis for institutional investors.")
|
410 |
+
button_container2 = st.container()
|
411 |
+
if "button_states" not in st.session_state:
|
412 |
+
st.session_state.button_states = {
|
413 |
+
"ESG_analysis_button_key": False,
|
414 |
+
}
|
415 |
+
|
416 |
+
if "results" not in st.session_state:
|
417 |
+
st.session_state.results = {}
|
418 |
+
|
419 |
+
if button_container2.button("ESG Analysis", key=ESG_analysis_button_key):
|
420 |
+
st.session_state.button_states[ESG_analysis_button_key] = True
|
421 |
+
result_generator = generate_ESG_strategy() # Call the generator function
|
422 |
+
st.session_state.results["ESG_analysis_output"] = result_generator
|
423 |
+
|
424 |
+
if "ESG_analysis_output" in st.session_state.results:
|
425 |
+
st.write(st.session_state.results["ESG_analysis_output"])
|
426 |
+
st.divider()
|
427 |
+
|
428 |
+
with mrow1_col2:
|
429 |
+
if "ESG_analysis_button_key" in st.session_state.results and st.session_state.results["ESG_analysis_button_key"]:
|
430 |
+
|
431 |
+
doc_retriever_ESG, query_engine = create_vector_database_ESG()
|
432 |
+
|
433 |
+
memory = ConversationBufferMemory(memory_key="chat_history", k=3, return_messages=True)
|
434 |
+
search = SerpAPIWrapper()
|
435 |
+
|
436 |
+
# Updated prompt templates to include chat history
|
437 |
+
def format_chat_history(chat_history):
|
438 |
+
"""Format chat history as a single string for input to the chain."""
|
439 |
+
formatted_history = "\n".join([f"User: {entry['input']}\nAI: {entry['output']}" for entry in chat_history])
|
440 |
+
return formatted_history
|
441 |
+
|
442 |
+
prompt_ESG = PromptTemplate.from_template(
|
443 |
+
template="""
|
444 |
+
You are a seasoned finance specialist and a specialist in environmental, social, and governance matters.
|
445 |
+
Use figures, and numerical, and statistical data when possible. Never give false information, numbers or data.
|
446 |
+
Conversation history:
|
447 |
+
{chat_history}
|
448 |
+
Based on the context: {context}, answer the following question: {question}.
|
449 |
+
"""
|
450 |
+
)
|
451 |
+
|
452 |
+
ESG_chain = (
|
453 |
+
{
|
454 |
+
"context": doc_retriever_ESG,
|
455 |
+
"chat_history": lambda _: format_chat_history(memory.load_memory_variables({})["chat_history"]),
|
456 |
+
"question": RunnablePassthrough(),
|
457 |
+
}
|
458 |
+
| prompt_ESG
|
459 |
+
| llm_tool
|
460 |
+
| StrOutputParser()
|
461 |
+
)
|
462 |
+
|
463 |
+
# Define the vector query engine tool
|
464 |
+
vector_query_tool_ESG = Tool(
|
465 |
+
name="Vector Query Engine ESG",
|
466 |
+
func=lambda query: query_engine.query(query), # Use query_engine to query the vector database
|
467 |
+
description="Useful for answering questions about specific ESG figures, data and specific statistics.",
|
468 |
+
)
|
469 |
+
|
470 |
+
tools = [
|
471 |
+
Tool(
|
472 |
+
name="ESG QA System",
|
473 |
+
func=ESG_chain.invoke,
|
474 |
+
description="Useful for answering general ESG questions related to the company. ",
|
475 |
+
),
|
476 |
+
Tool(
|
477 |
+
name="Search Tool",
|
478 |
+
func=search.run,
|
479 |
+
description="Useful for answering financial, or general questions, but not ESG or sustainability questions.",
|
480 |
+
),
|
481 |
+
vector_query_tool_ESG,
|
482 |
+
]
|
483 |
+
|
484 |
+
# Initialize the agent with LCEL tools and memory
|
485 |
+
agent = initialize_agent(
|
486 |
+
tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True, memory=memory, handle_parsing_errors=True)
|
487 |
+
def conversational_chat(query):
|
488 |
+
# Get the result from the agent
|
489 |
+
result = agent.invoke({"input": query, "chat_history": st.session_state['history']})
|
490 |
+
|
491 |
+
# Handle different response types
|
492 |
+
if isinstance(result, dict):
|
493 |
+
# Extract the main content if the result is a dictionary
|
494 |
+
result = result.get("output", "") # Adjust the key as needed based on your agent's output
|
495 |
+
elif isinstance(result, list):
|
496 |
+
# If the result is a list, join it into a single string
|
497 |
+
result = "\n".join(result)
|
498 |
+
elif not isinstance(result, str):
|
499 |
+
# Convert the result to a string if it is not already one
|
500 |
+
result = str(result)
|
501 |
+
|
502 |
+
# Add the query and the result to the session state
|
503 |
+
st.session_state['history'].append((query, result))
|
504 |
+
|
505 |
+
# Update memory with the conversation
|
506 |
+
memory.save_context({"input": query}, {"output": result})
|
507 |
+
|
508 |
+
# Return the result
|
509 |
+
return result
|
510 |
+
|
511 |
+
# Ensure session states are initialized
|
512 |
+
if 'history' not in st.session_state:
|
513 |
+
st.session_state['history'] = []
|
514 |
+
|
515 |
+
if 'generated' not in st.session_state:
|
516 |
+
st.session_state['generated'] = ["Let's discuss the ESG matters and financial matters π€"]
|
517 |
+
|
518 |
+
if 'past' not in st.session_state:
|
519 |
+
st.session_state['past'] = ["Hey ! π"]
|
520 |
+
|
521 |
+
if 'input' not in st.session_state:
|
522 |
+
st.session_state['input'] = ""
|
523 |
+
|
524 |
+
# Streamlit layout
|
525 |
+
st.subheader("Discuss the ESG and financial matters")
|
526 |
+
st.info("This tool is designed to enable discussion about the ESG and financial matters concerning the company.")
|
527 |
+
response_container = st.container()
|
528 |
+
container = st.container()
|
529 |
+
|
530 |
+
with container:
|
531 |
+
with st.form(key='my_form'):
|
532 |
+
user_input = st.text_input("Query:", placeholder="What would you like to know about ESG and financial matters", key='input')
|
533 |
+
submit_button = st.form_submit_button(label='Send')
|
534 |
+
if submit_button and user_input:
|
535 |
+
output = conversational_chat(user_input)
|
536 |
+
st.session_state['past'].append(user_input)
|
537 |
+
st.session_state['generated'].append(output)
|
538 |
+
user_input = "Query:"
|
539 |
+
#st.session_state['input'] = ""
|
540 |
+
# Display generated responses
|
541 |
+
if st.session_state['generated']:
|
542 |
+
with response_container:
|
543 |
+
for i in range(len(st.session_state['generated'])):
|
544 |
+
message(st.session_state["past"][i], is_user=True, key=str(i) + '_user', avatar_style="shapes")
|
545 |
+
message(st.session_state["generated"][i], key=str(i), avatar_style="icons")
|