Mjlehtim commited on
Commit
1468f65
·
verified ·
1 Parent(s): ace55ec

Delete LocalT_ESG_RAG_1.25.py

Browse files
Files changed (1) hide show
  1. LocalT_ESG_RAG_1.25.py +0 -710
LocalT_ESG_RAG_1.25.py DELETED
@@ -1,710 +0,0 @@
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
- import json
36
-
37
- import nest_asyncio # noqa: E402
38
- nest_asyncio.apply()
39
-
40
- load_dotenv()
41
- load_dotenv(find_dotenv())
42
-
43
- os.environ["TOKENIZERS_PARALLELISM"] = "false"
44
- SERPAPI_API_KEY = os.environ["SERPAPI_API_KEY"]
45
- GOOGLE_CSE_ID = os.environ["GOOGLE_CSE_ID"]
46
- GOOGLE_API_KEY = os.environ["GOOGLE_API_KEY"]
47
- LLAMA_PARSE_API_KEY = os.environ["LLAMA_PARSE_API_KEY"]
48
- HUGGINGFACEHUB_API_TOKEN = os.environ["HUGGINGFACEHUB_API_TOKEN"]
49
- groq_api_key=os.getenv('GROQ_API_KEY')
50
-
51
- st.set_page_config(layout="wide")
52
-
53
- css = """
54
- <style>
55
- [data-testid="stAppViewContainer"] {
56
- background-color: #f8f9fa; /* Very light grey */
57
- }
58
- [data-testid="stSidebar"] {
59
- background-color: white;
60
- color: black;
61
- }
62
- [data-testid="stAppViewContainer"] * {
63
- color: black; /* Ensure all text is black */
64
- }
65
- button {
66
- background-color: #add8e6; /* Light blue for primary buttons */
67
- color: black;
68
- border: 2px solid green; /* Green border */
69
- }
70
- button:hover {
71
- background-color: #87ceeb; /* Slightly darker blue on hover */
72
- }
73
-
74
- button:active {
75
- outline: 2px solid green; /* Green outline when the button is pressed */
76
- outline-offset: 2px; /* Space between button and outline */
77
- }
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
- def load_credentials(filepath):
110
- with open(filepath, 'r') as file:
111
- return json.load(file)
112
-
113
- # Load credentials from 'credentials.json'
114
- credentials = load_credentials('Assets/credentials.json')
115
-
116
- # Initialize session state if not already done
117
- if 'logged_in' not in st.session_state:
118
- st.session_state.logged_in = False
119
- st.session_state.username = ''
120
-
121
- # Function to handle login
122
- def login(username, password):
123
- if username in credentials and credentials[username] == password:
124
- st.session_state.logged_in = True
125
- st.session_state.username = username
126
- st.rerun() # Rerun to reflect login state
127
- else:
128
- st.session_state.logged_in = False
129
- st.session_state.username = ''
130
- st.error("Invalid username or password.")
131
-
132
- # Function to handle logout
133
- def logout():
134
- st.session_state.logged_in = False
135
- st.session_state.username = ''
136
- st.rerun() # Rerun to reflect logout state
137
-
138
- # If not logged in, show login form
139
- if not st.session_state.logged_in:
140
- st.sidebar.write("Login")
141
- username = st.sidebar.text_input('Username')
142
- password = st.sidebar.text_input('Password', type='password')
143
- if st.sidebar.button('Login'):
144
- login(username, password)
145
- # Stop the script here if the user is not logged in
146
- st.stop()
147
-
148
- # If logged in, show logout button and main content
149
- if st.session_state.logged_in:
150
- st.sidebar.write(f"Welcome, {st.session_state.username}!")
151
- if st.sidebar.button('Logout'):
152
- logout()
153
-
154
- #-------------
155
- llm=ChatGroq(groq_api_key=groq_api_key,
156
- model_name="llama-3.2-90b-text-preview", temperature = 0.0, streaming=True)
157
- #--------------
158
- doc_retriever_ESG = None
159
- doc_retriever_financials = None
160
- #--------------
161
-
162
- #@st.cache_data
163
- def load_or_parse_data_ESG():
164
- data_file = "./data/parsed_data_ESG.pkl"
165
-
166
- parsingInstructionUber10k = """The provided document contain detailed information about the company's environmental, social and governance matters.
167
- It contains several tables, figures and statistical information about CO2 emissions and energy consumption.
168
- Give only precide CO2 and energy consumotion levels inly from the context documents.
169
- You must never provide false numeric or statistical data that is not included in the context document.
170
- 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."""
171
-
172
- parser = LlamaParse(api_key=LLAMA_PARSE_API_KEY,
173
- result_type="markdown",
174
- parsing_instruction=parsingInstructionUber10k,
175
- max_timeout=5000,
176
- gpt4o_mode=True,
177
- )
178
-
179
- file_extractor = {".pdf": parser}
180
- reader = SimpleDirectoryReader("./ESG_Documents", file_extractor=file_extractor)
181
- documents = reader.load_data()
182
-
183
- print("Saving the parse results in .pkl format ..........")
184
- joblib.dump(documents, data_file)
185
-
186
- # Set the parsed data to the variable
187
- parsed_data_ESG = documents
188
-
189
- return parsed_data_ESG
190
-
191
- #@st.cache_data
192
- def load_or_parse_data_financials():
193
- data_file = "./data/parsed_data_financials.pkl"
194
-
195
- 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.
196
- It contains several tabless, figures and statistical information. You must be precise while answering the questions and never provide false numeric or statistical data."""
197
-
198
- parser = LlamaParse(api_key=LLAMA_PARSE_API_KEY,
199
- result_type="markdown",
200
- parsing_instruction=parsingInstructionUber10k,
201
- max_timeout=5000,
202
- gpt4o_mode=True,
203
- )
204
-
205
- file_extractor = {".pdf": parser}
206
- reader = SimpleDirectoryReader("./Financial_Documents", file_extractor=file_extractor)
207
- documents = reader.load_data()
208
-
209
- print("Saving the parse results in .pkl format ..........")
210
- joblib.dump(documents, data_file)
211
-
212
- # Set the parsed data to the variable
213
- parsed_data_financials = documents
214
-
215
- return parsed_data_financials
216
-
217
- #--------------
218
- # Create vector database
219
-
220
- @st.cache_resource
221
- def create_vector_database_ESG():
222
- # Call the function to either load or parse the data
223
- llama_parse_documents = load_or_parse_data_ESG()
224
-
225
- with open('data/output_ESG.md', 'a') as f: # Open the file in append mode ('a')
226
- for doc in llama_parse_documents:
227
- f.write(doc.text + '\n')
228
-
229
- markdown_path = "data/output_ESG.md"
230
- loader = UnstructuredMarkdownLoader(markdown_path)
231
- documents = loader.load()
232
- # Split loaded documents into chunks
233
- text_splitter = RecursiveCharacterTextSplitter(chunk_size=400, chunk_overlap=30)
234
- docs = text_splitter.split_documents(documents)
235
-
236
- #len(docs)
237
- print(f"length of documents loaded: {len(documents)}")
238
- print(f"total number of document chunks generated :{len(docs)}")
239
- embed_model = HuggingFaceEmbeddings()
240
-
241
- vs = Chroma.from_documents(
242
- documents=docs,
243
- embedding=embed_model,
244
- collection_name="rag",
245
- )
246
- doc_retriever_ESG = vs.as_retriever()
247
-
248
- index = VectorStoreIndex.from_documents(llama_parse_documents)
249
- query_engine = index.as_query_engine()
250
-
251
- return doc_retriever_ESG, query_engine
252
-
253
- @st.cache_resource
254
- def create_vector_database_financials():
255
- # Call the function to either load or parse the data
256
- llama_parse_documents = load_or_parse_data_financials()
257
-
258
- with open('data/output_financials.md', 'a') as f: # Open the file in append mode ('a')
259
- for doc in llama_parse_documents:
260
- f.write(doc.text + '\n')
261
-
262
- markdown_path = "data/output_financials.md"
263
- loader = UnstructuredMarkdownLoader(markdown_path)
264
- documents = loader.load()
265
- text_splitter = RecursiveCharacterTextSplitter(chunk_size=100, chunk_overlap=15)
266
- docs = text_splitter.split_documents(documents)
267
-
268
- embed_model = HuggingFaceEmbeddings()
269
-
270
- vs = Chroma.from_documents(
271
- documents=docs,
272
- embedding=embed_model,
273
- collection_name="rag"
274
- )
275
- doc_retriever_financials = vs.as_retriever()
276
-
277
- index = VectorStoreIndex.from_documents(llama_parse_documents)
278
- query_engine_financials = index.as_query_engine()
279
-
280
- print('Vector DB created successfully !')
281
- return doc_retriever_financials, query_engine_financials
282
-
283
- #--------------
284
- ESG_analysis_button_key = "ESG_strategy_button"
285
- portfolio_analysis_button_key = "portfolio_strategy_button"
286
-
287
- #---------------
288
- def delete_files_and_folders(folder_path):
289
- for root, dirs, files in os.walk(folder_path, topdown=False):
290
- for file in files:
291
- try:
292
- os.unlink(os.path.join(root, file))
293
- except Exception as e:
294
- st.error(f"Error deleting {os.path.join(root, file)}: {e}")
295
- for dir in dirs:
296
- try:
297
- os.rmdir(os.path.join(root, dir))
298
- except Exception as e:
299
- st.error(f"Error deleting directory {os.path.join(root, dir)}: {e}")
300
- #---------------
301
-
302
- uploaded_files_ESG = st.sidebar.file_uploader("Choose a Sustainability Report", accept_multiple_files=True, key="ESG_files")
303
- for uploaded_file in uploaded_files_ESG:
304
- st.write("filename:", uploaded_file.name)
305
- def save_uploadedfile(uploadedfile):
306
- with open(os.path.join("ESG_Documents",uploadedfile.name),"wb") as f:
307
- f.write(uploadedfile.getbuffer())
308
- return st.success("Saved File:{} to ESG_Documents".format(uploadedfile.name))
309
- save_uploadedfile(uploaded_file)
310
-
311
- uploaded_files_financials = st.sidebar.file_uploader("Choose an Annual Report", accept_multiple_files=True, key="financial_files")
312
- for uploaded_file in uploaded_files_financials:
313
- st.write("filename:", uploaded_file.name)
314
- def save_uploadedfile(uploadedfile):
315
- with open(os.path.join("Financial_Documents",uploadedfile.name),"wb") as f:
316
- f.write(uploadedfile.getbuffer())
317
- return st.success("Saved File:{} to Financial_Documents".format(uploadedfile.name))
318
- save_uploadedfile(uploaded_file)
319
-
320
- #---------------
321
- def ESG_strategy():
322
- doc_retriever_ESG, _ = create_vector_database_ESG()
323
- prompt_template = """<|system|>
324
- 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|>
325
- <|user|>
326
- Answer the {question} based on the information you find in context: {context} <|end|>
327
- <|assistant|>"""
328
-
329
- prompt = PromptTemplate(template=prompt_template, input_variables=["question", "context"])
330
-
331
- qa = (
332
- {
333
- "context": doc_retriever_ESG,
334
- "question": RunnablePassthrough(),
335
- }
336
- | prompt
337
- | llm
338
- | StrOutputParser()
339
- )
340
-
341
- ESG_answer_1 = qa.invoke("Give a summary what specific ESG measures the company has taken recently and compare these to the best practices.")
342
- 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?")
343
- 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?")
344
- 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.")
345
- 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.")
346
- 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.")
347
- 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.")
348
- 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.")
349
- 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.")
350
- ESG_answer_10 = qa.invoke("What percentage of women are represented in the (i) board, (ii) executive directors and (iii) upper management?")
351
- ESG_answer_11 = qa.invoke("What policies has the company implemented to counter money laundering and corruption?")
352
-
353
- 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}"
354
- financial_output = ESG_output
355
-
356
- with open("ESG_analysis.txt", 'w') as file:
357
- file.write(financial_output)
358
-
359
- return financial_output
360
-
361
- #-------------
362
- @st.cache_data
363
- def generate_ESG_strategy() -> str:
364
- ESG_output = ESG_strategy()
365
- st.session_state.results["ESG_analysis_button_key"] = ESG_output
366
- return ESG_output
367
-
368
- #---------------
369
- #@st.cache_data
370
- def create_pdf():
371
- text_file = "ESG_analysis.txt"
372
- pdf = FPDF('P', 'mm', 'A4')
373
- pdf.add_page()
374
- pdf.set_margins(10, 10, 10)
375
- pdf.set_font("Arial", size=15)
376
- #image = "lt.png"
377
- #pdf.image(image, w = 40)
378
- # Add introductory lines
379
- #pdf.cell(0, 10, txt="Company name", ln=1, align='C')
380
- pdf.cell(0, 10, txt="Structured ESG Analysis", ln=2, align='C')
381
- pdf.ln(5)
382
-
383
- pdf.set_font("Arial", size=11)
384
- try:
385
- with open(text_file, 'r', encoding='utf-8') as f:
386
- for line in f:
387
- # Replace '\u2019' with a different character or string
388
- #line = line.replace('\u2019', "'") # For example, replace with apostrophe
389
- #line = line.replace('\u2265', "'") # For example, replace with apostrophe
390
- #pdf.multi_cell(0, 6, txt=line, align='L')
391
- pdf.multi_cell(0, 6, txt=line.encode('latin-1', 'replace').decode('latin-1'), align='L')
392
- pdf.ln(5)
393
- except UnicodeEncodeError:
394
- print("UnicodeEncodeError: Some characters could not be encoded in Latin-1. Skipping...")
395
- pass # Skip the lines causing UnicodeEncodeError
396
-
397
- output_pdf_path = "ESG_analysis.pdf"
398
- pdf.output(output_pdf_path)
399
-
400
- #----------------
401
- #llm = build_llm()
402
-
403
- if 'results' not in st.session_state:
404
- st.session_state.results = {
405
- "ESG_analysis_button_key": {}
406
- }
407
-
408
- loaders = {'.pdf': PyMuPDFLoader,
409
- '.xml': UnstructuredXMLLoader,
410
- '.csv': CSVLoader,
411
- }
412
-
413
- def create_directory_loader(file_type, directory_path):
414
- return DirectoryLoader(
415
- path=directory_path,
416
- glob=f"**/*{file_type}",
417
- loader_cls=loaders[file_type],
418
- )
419
-
420
- strategies_container = st.container()
421
- with strategies_container:
422
- mrow1_col1, mrow1_col2 = st.columns(2)
423
-
424
- st.sidebar.info("To get started, please upload the documents from the company you would like to analyze.")
425
- button_container = st.sidebar.container()
426
- if os.path.exists("ESG_analysis.txt"):
427
- create_pdf()
428
- with open("ESG_analysis.pdf", "rb") as pdf_file:
429
- PDFbyte = pdf_file.read()
430
-
431
- st.sidebar.download_button(label="Download Analyses",
432
- data=PDFbyte,
433
- file_name="strategy_sheet.pdf",
434
- mime='application/octet-stream',
435
- )
436
-
437
- if button_container.button("Clear All"):
438
-
439
- st.session_state.button_states = {
440
- "ESG_analysis_button_key": False,
441
- }
442
- st.session_state.button_states = {
443
- "portfolio_analysis_button_key": False,
444
- }
445
- st.session_state.results = {}
446
-
447
- st.session_state['history'] = []
448
- st.session_state['generated'] = ["Let's discuss the ESG issues of the company 🤗"]
449
- st.session_state['past'] = ["Hey ! 👋"]
450
- st.cache_data.clear()
451
- st.cache_resource.clear()
452
-
453
- # Check if the subfolder exists
454
- if os.path.exists("ESG_Documents"):
455
- for filename in os.listdir("ESG_Documents"):
456
- file_path = os.path.join("ESG_Documents", filename)
457
- try:
458
- if os.path.isfile(file_path):
459
- os.unlink(file_path)
460
- except Exception as e:
461
- st.error(f"Error deleting {file_path}: {e}")
462
- else:
463
- pass
464
-
465
- if os.path.exists("Financial_Documents"):
466
- # Iterate through files in the subfolder and delete them
467
- for filename in os.listdir("Financial_Documents"):
468
- file_path = os.path.join("Financial_Documents", filename)
469
- try:
470
- if os.path.isfile(file_path):
471
- os.unlink(file_path)
472
- except Exception as e:
473
- st.error(f"Error deleting {file_path}: {e}")
474
- else:
475
- pass
476
- # st.warning("No 'data' subfolder found.")
477
-
478
- if os.path.exists("ESG_Documents_Portfolio"):
479
- # Iterate through files in the subfolder and delete them
480
- for filename in os.listdir("ESG_Documents_Portfolio"):
481
- file_path = os.path.join("ESG_Documents_Portfolio", filename)
482
- try:
483
- if os.path.isfile(file_path):
484
- os.unlink(file_path)
485
- except Exception as e:
486
- st.error(f"Error deleting {file_path}: {e}")
487
- else:
488
- pass
489
- # st.warning("No 'data' subfolder found.")
490
-
491
- folders_to_clean = ["data", "chroma_db_portfolio", "chroma_db_LT", "chroma_db_fin"]
492
-
493
- for folder_path in folders_to_clean:
494
- if os.path.exists(folder_path):
495
- for item in os.listdir(folder_path):
496
- item_path = os.path.join(folder_path, item)
497
- try:
498
- if os.path.isfile(item_path) or os.path.islink(item_path):
499
- os.unlink(item_path) # Remove files or symbolic links
500
- elif os.path.isdir(item_path):
501
- shutil.rmtree(item_path) # Remove subfolders and all their contents
502
- except Exception as e:
503
- st.error(f"Error deleting {item_path}: {e}")
504
- else:
505
- pass
506
- # st.warning(f"No '{folder_path}' folder found.")
507
-
508
- with mrow1_col1:
509
- st.subheader("Summary of the ESG Analysis")
510
- st.info("This tool is designed to provide a comprehensive ESG risk analysis for institutional investors.")
511
- button_container2 = st.container()
512
- if "button_states" not in st.session_state:
513
- st.session_state.button_states = {
514
- "ESG_analysis_button_key": False,
515
- }
516
-
517
- if "results" not in st.session_state:
518
- st.session_state.results = {}
519
-
520
- if button_container2.button("ESG Analysis", key=ESG_analysis_button_key):
521
- st.session_state.button_states[ESG_analysis_button_key] = True
522
- result_generator = generate_ESG_strategy() # Call the generator function
523
- st.session_state.results["ESG_analysis_output"] = result_generator
524
-
525
- if "ESG_analysis_output" in st.session_state.results:
526
- st.write(st.session_state.results["ESG_analysis_output"])
527
- st.divider()
528
-
529
- with mrow1_col2:
530
- if "ESG_analysis_button_key" in st.session_state.results and st.session_state.results["ESG_analysis_button_key"]:
531
-
532
- doc_retriever_ESG, query_engine = create_vector_database_ESG()
533
- doc_retriever_financials, query_engine_financials = create_vector_database_financials()
534
- memory = ConversationBufferMemory(memory_key="chat_history", k=3, return_messages=True)
535
- search = SerpAPIWrapper()
536
-
537
- # Updated prompt templates to include chat history
538
- def format_chat_history(chat_history):
539
- """Format chat history as a single string for input to the chain."""
540
- formatted_history = "\n".join([f"User: {entry['input']}\nAI: {entry['output']}" for entry in chat_history])
541
- return formatted_history
542
-
543
- prompt_financials = PromptTemplate.from_template(
544
- template="""
545
- You are a seasoned corporate finance specialist.
546
- Use figures, numerical, and statistical data when possible. Never give false information, numbers or data.
547
-
548
- Conversation history:
549
- {chat_history}
550
-
551
- Based on the context: {context}, answer the following question: {question}.
552
- """
553
- )
554
-
555
- prompt_ESG = PromptTemplate.from_template(
556
- template="""
557
- You are a seasoned finance specialist and a specialist in environmental, social, and governance matters.
558
- Use figures, numerical, and statistical data when possible. Never give false information, numbers or data.
559
-
560
- Conversation history:
561
- {chat_history}
562
-
563
- Based on the context: answer the following question: {question}.
564
- """
565
- )
566
-
567
- # LCEL Chains with memory integration
568
- financials_chain = (
569
- {
570
- "context": doc_retriever_financials,
571
- # Lambda function now accepts one argument (even if unused)
572
- "chat_history": lambda _: format_chat_history(memory.load_memory_variables({})["chat_history"]),
573
- "question": RunnablePassthrough(),
574
- }
575
- | prompt_financials
576
- | llm
577
- | StrOutputParser()
578
- )
579
-
580
- ESG_chain = (
581
- {
582
- "context": doc_retriever_ESG,
583
- "chat_history": lambda _: format_chat_history(memory.load_memory_variables({})["chat_history"]),
584
- "question": RunnablePassthrough(),
585
- }
586
- | prompt_ESG
587
- | llm
588
- | StrOutputParser()
589
- )
590
-
591
- # Define the tools with LCEL expressions
592
- # Define the vector query engine tool
593
- vector_query_tool_ESG = Tool(
594
- name="Vector Query Engine ESG",
595
- func=lambda query: query_engine.query(query), # Use query_engine to query the vector database
596
- description="Useful for answering questions that require ESG figures, data and statistics.",
597
- )
598
-
599
- vector_query_tool_financials = Tool(
600
- name="Vector Query Engine Financials",
601
- func=lambda query: query_engine_financials.query(query), # Use query_engine to query the vector database
602
- description="Useful for answering questions that require financial figures, data and statistics.",
603
- )
604
-
605
- # Create a function to validate responses
606
- def validate_esg_response(query):
607
- esg_response = vector_query_tool_ESG.func(query)
608
- esg_validation = ESG_chain.invoke({
609
- "context": doc_retriever_ESG,
610
- "chat_history": format_chat_history(memory.load_memory_variables({})["chat_history"]),
611
- "question": esg_response
612
- })
613
- return esg_validation
614
-
615
- def validate_financials_response(query):
616
- financials_response = vector_query_tool_financials.func(query)
617
- financials_validation = financials_chain.invoke({
618
- "context": doc_retriever_financials,
619
- "chat_history": format_chat_history(memory.load_memory_variables({})["chat_history"]),
620
- "question": financials_response
621
- })
622
- return financials_validation
623
-
624
- # Update the tools list to include validation
625
- tools = [
626
- Tool(
627
- name="Search Tool",
628
- func=search.run,
629
- description="Useful when other tools do not provide the answer.",
630
- ),
631
- Tool(
632
- name="Validate ESG Response",
633
- func=validate_esg_response,
634
- description="Validates the response of the Vector Query Engine ESG tool.",
635
- ),
636
- Tool(
637
- name="Validate Financials Response",
638
- func=validate_financials_response,
639
- description="Validates the response of the Vector Query Engine Financials tool.",
640
- ),
641
- vector_query_tool_ESG,
642
- vector_query_tool_financials,
643
- ]
644
-
645
- # Initialize the agent with LCEL tools and memory
646
- agent = initialize_agent(
647
- tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True, memory=memory, handle_parsing_errors=True)
648
- def conversational_chat(query):
649
- # Get the result from the agent
650
- result = agent.invoke({"input": query, "chat_history": st.session_state['history']})
651
-
652
- # Handle different response types
653
- if isinstance(result, dict):
654
- # Extract the main content if the result is a dictionary
655
- result = result.get("output", "") # Adjust the key as needed based on your agent's output
656
- elif isinstance(result, list):
657
- # If the result is a list, join it into a single string
658
- result = "\n".join(result)
659
- elif not isinstance(result, str):
660
- # Convert the result to a string if it is not already one
661
- result = str(result)
662
-
663
- # Add the query and the result to the session state
664
- st.session_state['history'].append((query, result))
665
-
666
- # Update memory with the conversation
667
- memory.save_context({"input": query}, {"output": result})
668
-
669
- # Return the result
670
- return result
671
-
672
- # Ensure session states are initialized
673
- if 'history' not in st.session_state:
674
- st.session_state['history'] = []
675
-
676
- if 'generated' not in st.session_state:
677
- st.session_state['generated'] = ["Let's discuss the ESG matters and financial matters 🤗"]
678
-
679
- if 'past' not in st.session_state:
680
- st.session_state['past'] = ["Hey ! 👋"]
681
-
682
- if 'input' not in st.session_state:
683
- st.session_state['input'] = ""
684
-
685
- # Streamlit layout
686
- st.subheader("Discuss the ESG and financial matters")
687
- st.info("This tool is designed to enable discussion about the ESG and financial matters concerning the company.")
688
- response_container = st.container()
689
- container = st.container()
690
-
691
- with container:
692
- with st.form(key='my_form'):
693
- user_input = st.text_input("Query:", placeholder="What would you like to know about ESG and financial matters", key='input')
694
- submit_button = st.form_submit_button(label='Send')
695
- if submit_button and user_input:
696
- output = conversational_chat(user_input)
697
- st.session_state['past'].append(user_input)
698
- st.session_state['generated'].append(output)
699
- user_input = "Query:"
700
- #st.session_state['input'] = ""
701
- # Display generated responses
702
- if st.session_state['generated']:
703
- with response_container:
704
- for i in range(len(st.session_state['generated'])):
705
- message(st.session_state["past"][i], is_user=True, key=str(i) + '_user', avatar_style="shapes")
706
- message(st.session_state["generated"][i], key=str(i), avatar_style="icons")
707
-
708
-
709
-
710
-