Mjlehtim commited on
Commit
e8259e3
·
verified ·
1 Parent(s): 229a705

Delete LocalT_ESG_RAG_1.25.py

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