JBHF commited on
Commit
537d6a1
1 Parent(s): 755f224

NonToxicGlazeAdvisor_Chat_with_Docs_Groq_Edition_1 - app.py - 02-04-2024

Browse files
Files changed (1) hide show
  1. app-02-04-2024.py +444 -0
app-02-04-2024.py ADDED
@@ -0,0 +1,444 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NonToxicGlazeAdvisor_Chat_with_Docs_Groq_Edition_1 - app.py - 02-04-2024
2
+
3
+ # STREAMLIT:
4
+ # https://www.datacamp.com/tutorial/streamlit:
5
+ #
6
+ # st.title(): This function allows you to add the title of the app.
7
+ # st.header(): This function is used to set header of a section.
8
+ # st.markdown(): This function is used to set a markdown of a section.
9
+ # st.subheader(): This function is used to set sub-header of a section.
10
+ # st.caption(): This function is used to write caption.
11
+ # st.code(): This function is used to set a code.
12
+ # st.latex(): This function is used to display mathematical expressions formatted as LaTeX.
13
+ #
14
+ # st.title ("this is the app title")
15
+ # st.header("this is the header ")
16
+ # st.markdown("this is the markdown")
17
+ # st.subheader("this is the subheader")
18
+ # st.caption("this is the caption")
19
+ # st.code("x=2021")
20
+ # st.latex(r''' a+a r^1+a r^2+a r^3 ''')
21
+
22
+
23
+
24
+ # JB:
25
+ # LangChainDeprecationWarning: Importing embeddings from langchain is deprecated.
26
+ # Importing from langchain will no longer be supported as of langchain==0.2.0.
27
+ # Please import from langchain-community instead:
28
+ # `from langchain_community.embeddings import FastEmbedEmbeddings`.
29
+ # To install langchain-community run `pip install -U langchain-community`.
30
+ from langchain_community.embeddings import FastEmbedEmbeddings
31
+
32
+ import os
33
+ import streamlit as st
34
+ from langchain_groq import ChatGroq
35
+ from langchain_community.document_loaders import WebBaseLoader
36
+ # JB:
37
+ from langchain_community.document_loaders import PyPDFLoader
38
+ from langchain_community.embeddings import OllamaEmbeddings
39
+
40
+ # JB:
41
+ from langchain_community.embeddings import FastEmbedEmbeddings
42
+ from langchain_community.document_loaders import PyPDFDirectoryLoader
43
+
44
+ # JB:
45
+ # File Directory
46
+ # This covers how to load all documents in a directory.
47
+ # Under the hood, by default this uses the UnstructuredLoader.
48
+ from langchain_community.document_loaders import DirectoryLoader
49
+ from langchain_community.document_loaders import TextLoader
50
+ import chardet
51
+
52
+ from langchain_community.vectorstores import FAISS
53
+ # from langchain.vectorstores import Chroma
54
+ # from langchain_community.vectorstores import Chroma
55
+
56
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
57
+ from langchain.chains.combine_documents import create_stuff_documents_chain
58
+ from langchain_core.prompts import ChatPromptTemplate
59
+ from langchain.chains import create_retrieval_chain
60
+ import time
61
+ from dotenv import load_dotenv
62
+
63
+ import glob
64
+
65
+ load_dotenv() #
66
+
67
+ groq_api_key = os.environ['GROQ_API_KEY']
68
+ # groq_api_key = "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" # os.environ['GROQ_API_KEY']
69
+ # groq_api_key = "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" # JB OK 24-03-2024
70
+ # print("groq_api_key: ", groq_api_key)
71
+
72
+ # st.title("Chat with Docs - Groq Edition :) ")
73
+ # # st.title ("this is the app title")
74
+ # st.title("Non-Toxic Glaze Advisor:")
75
+ # st.subheader("A tool for getting advicgroqe on non-toxic ceramic glazes for earthenware temperature ranges.")
76
+ # st.subheader("Victor Benchuijsen : (Glaze techniques / Ceramics)")
77
+ # st.subheader("Jan Bours : Artificial Intelligence / Data Science / Natural Language Processing (ALL RIGHTS RESERVED)")
78
+ # st.write("---------------------------------")
79
+ # st.subheader("Chat with Docs - Using AI: 'mixtral-8x7b-32768' Groq Edition (Very Fast!) - VERSION 1 - March 18, 2024")
80
+ # st.write("---------------------------------")
81
+
82
+ st.title("Adviseur voor niet-giftige glazuren:")
83
+ st.subheader("Een gereedschap gebaseerd op Kunstmatige Intelligentie (AI) om advies te krijgen over niet-giftige keramische glazuren voor aardewerk temperatuur bereiken.")
84
+ st.write("---------------------------------")
85
+ st.subheader("Victor Benckhuijsen : (Glazuur technieken / Keramiek)")
86
+ st.subheader("(ALL RIGHTS RESERVED)")
87
+ st.image('Victor_Benckhuijsen_2.png', caption='Victor Benckhuijsen')
88
+ # st.subheader("---------------------------------")
89
+ # st.write("---------------------------------")
90
+ st.subheader("Jan Bours : Artificial Intelligence / Data Science / Natural Language Processing")
91
+ st.subheader("(ALL RIGHTS RESERVED)")
92
+ st.image('Jan_Bours_2.png', caption='Jan Bours')
93
+ st.write("---------------------------------")
94
+ st.subheader("Chat with Docs - Using AI: 'mixtral-8x7b-32768' Groq Edition (Very Fast!) - VERSION 1 - March 31, 2024")
95
+ st.write("---------------------------------")
96
+
97
+ # st.header("LIST OF ALL THE LOADED DOCUMENTS: ")
98
+ st.header("LIJST MET ALLE ACTUEEL GELADEN DOCUMENTEN: ")
99
+
100
+ st.write("")
101
+ pdf_files = glob.glob("*.pdf")
102
+ # word_files = glob.glob("*.docx")
103
+ for file in pdf_files:
104
+ # for file in word_files:
105
+ st.subheader(file)
106
+
107
+ st.write("---------------------------------")
108
+
109
+
110
+ start1 = time.process_time()
111
+
112
+ if "vector" not in st.session_state:
113
+
114
+ st.write("Even geduld a.u.b. ........")
115
+ # st.header("Chunking, embedding, storing in FAISS vectorstore (Can take a long time!).")
116
+ # st.subheader("Wait till this hase been done before you can enter your query! .......")
117
+
118
+ # st.session_state.embeddings = OllamaEmbeddings() # ORIGINAL
119
+ st.session_state.embeddings = FastEmbedEmbeddings() # JB
120
+
121
+
122
+ # st.session_state.loader = WebBaseLoader("https://paulgraham.com/greatwork.html") # ORIGINAL
123
+ # st.session_state.docs = st.session_state.loader.load() # ORIGINAL
124
+ # https://api.python.langchain.com/en/latest/document_loaders/langchain_community.document_loaders.pdf.PyPDFLoader.html
125
+ # https://python.langchain.com/docs/integrations/document_loaders/merge_doc
126
+ # from langchain_community.document_loaders import PyPDFLoader
127
+ # loader_pdf = PyPDFLoader("../MachineLearning-Lecture01.pdf")
128
+ #
129
+ # https://stackoverflow.com/questions/60215731/pypdf-to-read-each-pdf-in-a-folder
130
+ #
131
+ # https://api.python.langchain.com/en/latest/document_loaders/langchain_community.document_loaders.pdf.PyPDFDirectoryLoader.html
132
+ # https://python.langchain.com/docs/modules/data_connection/document_loaders/pdf#pypdf-directory
133
+ # !!!!!
134
+ # PyPDF Directory
135
+ # Load PDFs from directory
136
+ # from langchain_community.document_loaders import PyPDFDirectoryLoader
137
+ # loader = PyPDFDirectoryLoader("example_data/")
138
+ # docs = loader.load()
139
+ #
140
+ # ZIE OOK:
141
+ # https://python.langchain.com/docs/modules/data_connection/document_loaders/pdf#using-pypdf
142
+ # Using MathPix
143
+ # Inspired by Daniel Gross's https://gist.github.com/danielgross/3ab4104e14faccc12b49200843adab21
144
+ # from langchain_community.document_loaders import MathpixPDFLoader
145
+ # loader = MathpixPDFLoader("example_data/layout-parser-paper.pdf")
146
+ # data = loader.load()
147
+ # pdf_file_path = "*.pdf" # JB
148
+ # st.session_state.loader = PyPDFLoader(file_path=pdf_file_path).load() # JB
149
+ # st.session_state.loader = PyPDFLoader(*.pdf).load() # JB syntax error *.pdf !
150
+ # st.session_state.loader = PyPDFDirectoryLoader("*.pdf") # JB PyPDFDirectoryLoader("example_data/")
151
+ # chunks = self.text_splitter.split_documents(docs)
152
+ # chunks = filter_complex_metadata(chunks)
153
+
154
+ # JB:
155
+ # https://python.langchain.com/docs/modules/data_connection/document_loaders/pdf#pypdf-directory
156
+ # st.session_state.docs = st.session_state.loader.load()
157
+ # loader = PyPDFDirectoryLoader(".")
158
+ # docs = loader.load()
159
+ # st.session_state.docs = docs
160
+
161
+
162
+ # https://docs.streamlit.io/library/api-reference/status/st.status
163
+ # st.status(label, *, expanded=False, state="running")
164
+ with st.status("Laden van de PDF documenten / Splitting de teksten / Genereer de Vector Store ...", expanded=True) as status:
165
+ # st.write("Searching for data...")
166
+ # time.sleep(2)
167
+ # st.write("Found URL.")
168
+ # time.sleep(1)
169
+ # st.write("Downloading data...")
170
+ # time.sleep(1)
171
+ #status.update(label="Download complete!", state="complete", expanded=False)
172
+
173
+ st.write("Laden van de PDF documenten...")
174
+ # JB:
175
+ # https://python.langchain.com/docs/modules/data_connection/document_loaders/file_directory
176
+ # text_loader_kwargs={'autodetect_encoding': True}
177
+ text_loader_kwargs={'autodetect_encoding': False}
178
+ path = '../'
179
+ # loader = DirectoryLoader(path, glob="**/*.pdf", loader_cls=TextLoader, loader_kwargs=text_loader_kwargs)
180
+ # PyPDFDirectoryLoader (TEST):
181
+ # loader = PyPDFDirectoryLoader(path, glob="**/*.pdf", loader_cls=TextLoader, loader_kwargs=text_loader_kwargs)
182
+ # loader = PyPDFDirectoryLoader(path, glob="**/*.pdf", loader_kwargs=text_loader_kwargs)
183
+ loader = PyPDFDirectoryLoader(path, glob="**/*.pdf")
184
+ docs = loader.load()
185
+ st.session_state.docs = docs
186
+
187
+ # JB 18-03-2024:
188
+ # https://python.langchain.com/docs/integrations/document_loaders/
189
+ # MICROSOFT WORD:
190
+ # https://python.langchain.com/docs/integrations/document_loaders/microsoft_word
191
+ # 1 - Using Docx2txt
192
+ # Load .docx using Docx2txt into a document.
193
+ # %pip install --upgrade --quiet docx2txt
194
+ # from langchain_community.document_loaders import Docx2txtLoader
195
+ # loader = Docx2txtLoader("example_data/fake.docx")
196
+ # data = loader.load()
197
+ # data
198
+ # [Document(page_content='Lorem ipsum dolor sit amet.', metadata={'source': 'example_data/fake.docx'})]
199
+ #
200
+ # 2A - Using Unstructured
201
+ # from langchain_community.document_loaders import UnstructuredWordDocumentLoader
202
+ # loader = UnstructuredWordDocumentLoader("example_data/fake.docx")
203
+ # data = loader.load()
204
+ # data
205
+ # [Document(page_content='Lorem ipsum dolor sit amet.', lookup_str='', metadata={'source': 'fake.docx'}, lookup_index=0)]
206
+ #
207
+ # 2B - Retain Elements
208
+ # Under the hood, Unstructured creates different “elements” for different chunks of text.
209
+ # By default we combine those together, but you can easily keep that separation by specifying mode="elements".
210
+ # loader = UnstructuredWordDocumentLoader("example_data/fake.docx", mode="elements")
211
+ # data = loader.load()
212
+ # data[0]
213
+ # Document(page_content='Lorem ipsum dolor sit amet.', lookup_str='', metadata={'source': 'fake.docx', 'filename': 'fake.docx', 'category': 'Title'}, lookup_index=0)
214
+ #
215
+ # 2A - Using Unstructured
216
+ # from langchain_community.document_loaders import UnstructuredWordDocumentLoader
217
+ # loader = UnstructuredWordDocumentLoader(path, glob="**/*.docx")
218
+ # docs = loader.load()
219
+ # st.session_state.docs = docs
220
+
221
+
222
+ st.write("Splitting / chunking de teksten...")
223
+ st.session_state.text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
224
+ st.session_state.documents = st.session_state.text_splitter.split_documents(st.session_state.docs)
225
+
226
+ st.write("Genereer de Vector Store (kan enige minuten duren)...")
227
+ # https://python.langchain.com/docs/integrations/vectorstores/faiss
228
+ # docs_and_scores = db.similarity_search_with_score(query)
229
+ # Saving and loading
230
+ # You can also save and load a FAISS index.
231
+ # This is useful so you don’t have to recreate it everytime you use it.
232
+ # db.save_local("faiss_index")
233
+ # new_db = FAISS.load_local("faiss_index", embeddings)
234
+ # docs = new_db.similarity_search(query)
235
+ # docs[0]
236
+ # Document(page_content='Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \n\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \n\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n\nAnd I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.', metadata={'source': '../../../state_of_the_union.txt'})
237
+ #
238
+ st.session_state.vector = FAISS.from_documents(st.session_state.documents, st.session_state.embeddings) # ORIGINAL
239
+
240
+ # st.session_state.vector = FAISS.from_documents(st.session_state.documents, st.session_state.embeddings) # ORIGINAL
241
+ #st.session_state.vector.save_local("faiss_index")
242
+ # The de-serialization relies loading a pickle file.
243
+ # Pickle files can be modified to deliver a malicious payload that results in execution of arbitrary code on your machine.
244
+ # You will need to set `allow_dangerous_deserialization` to `True` to enable deserialization. If you do this, make sure that you trust the source of the data.
245
+
246
+ #st.session_state.vector = FAISS.load_local("faiss_index", st.session_state.embeddings, allow_dangerous_deserialization=True)
247
+
248
+ # ZIE:
249
+ # ZIE VOOR EEN APP MET CHROMADB:
250
+ # https://github.com/vndee/local-rag-example/blob/main/rag.py
251
+ # https://raw.githubusercontent.com/vndee/local-rag-example/main/rag.py
252
+ # Chroma.from_documents(documents=chunks, embedding=FastEmbedEmbeddings())
253
+ # st.session_state.vector = Chroma.from_documents(st.session_state.documents, st.session_state.embeddings) # JB
254
+
255
+ # st.write(f"Response time van de LLM: {elapsed_time:.1f} seconds")
256
+ # print(f"Response time: {time.process_time() - start}")
257
+ elapsed_time = time.process_time() - start1
258
+ st.write(f"Response time voor: Laden van de PDF documenten / Splitting de teksten / Genereer de Vector Store: {elapsed_time:.1f} seconds")
259
+
260
+ st.write("---------------------------------")
261
+
262
+ # st.title("Chat with Docs - Groq Edition :) ")
263
+ # st.title("Literature Based Research (LBR) - A. Unzicker and J. Bours - Chat with Docs - Groq Edition (Very Fast!) - VERSION 3 - March 8 2024")
264
+
265
+ llm = ChatGroq(
266
+ temperature=0.2,
267
+ groq_api_key=groq_api_key,
268
+ model_name='mixtral-8x7b-32768'
269
+ )
270
+
271
+ prompt = ChatPromptTemplate.from_template("""
272
+ Answer the following question based only on the provided context.
273
+ Think step by step before providing a detailed answer.
274
+ I will tip you $200 if the user finds the answer helpful.
275
+ <context>
276
+ {context}
277
+ </context>
278
+ Question: {input}""")
279
+
280
+ document_chain = create_stuff_documents_chain(llm, prompt)
281
+
282
+ retriever = st.session_state.vector.as_retriever()
283
+ retrieval_chain = create_retrieval_chain(retriever, document_chain)
284
+
285
+ ## prompt = st.text_input("Input your prompt here") #, key=key)
286
+ #prompt = st.text_input("Stel hieronder Uw vraag:") #, key=key)
287
+ #
288
+ ## If the user hits enter
289
+ #if prompt:
290
+ # # Then pass the prompt to the LLM
291
+ # start = time.process_time()
292
+ # response = retrieval_chain.invoke({"input": prompt})
293
+ # # print(f"Response time: {time.process_time() - start}")
294
+ # st.write(f"Response time: {time.process_time() - start} seconds")
295
+ #
296
+ # st.write(response["answer"])
297
+ #
298
+ # # With a streamlit expander
299
+ # with st.expander("Document Similarity Search"):
300
+ # # Find the relevant chunks
301
+ # for i, doc in enumerate(response["context"]):
302
+ # # print(doc)
303
+ # # st.write(f"Source Document # {i+1} : {doc.metadata['source'].split('/')[-1]}")
304
+ # st.write(doc)
305
+ # st.write(f"Source Document # {i+1} : {doc.metadata['source'].split('/')[-1]}")
306
+ #
307
+ #
308
+ # st.write(doc.page_content)
309
+ # st.write("--------------------------------")
310
+ #
311
+ #st.write("---------------------------------")
312
+
313
+
314
+ # ZIE:
315
+ # https://raw.githubusercontent.com/streamlit/llm-examples/main/Chatbot.py
316
+ # from openai import OpenAI
317
+ # import streamlit as st
318
+
319
+ with st.sidebar:
320
+ # openai_api_key = st.text_input("OpenAI API Key", key="chatbot_api_key", type="password")
321
+ UserEmailAdress = st.text_input("Vul Uw email adres hier in: ", key="UserEmailAdress", type="password")
322
+ # "[Zelf keramische glazuren NON TOXIC samenstellen vanuit 1 basisglazuur](http://www.ceramicconcepts.nl/)"
323
+ "[Keramische ateliers Victor Benckhuijsen](https://victorglazuren.nl/)"
324
+ "[Keramiek Victor Glazuren Victor Benckhuijsen - Instagram](https://www.instagram.com/benckhuijsenvictor/?hl=am-et)"
325
+ "[Keramiek Victor Glazuren Victor Benckhuijsen - Facebook](https://www.facebook.com/harryjamaar)"
326
+ "[Keramiek Victor Glazuren Victor Benckhuijsen - YouTube](https://www.youtube.com/@kleienhoop/videos)"
327
+
328
+ st.title("💬 Chatbot")
329
+ st.caption("🚀 A streamlit chatbot powered by mixtral-8x7b-32768 Groq LLM (VERY FAST !). temperature=0.2")
330
+
331
+ if "messages" not in st.session_state:
332
+ st.session_state["messages"] = [{"role": "assistant", "content": "Hoe kan ik U helpen?"}]
333
+
334
+ for msg in st.session_state.messages:
335
+ st.chat_message(msg["role"]).write(msg["content"])
336
+
337
+
338
+ # TAAL KIEZER
339
+ option = st.selectbox(
340
+ 'In welke taal wilt U Uw vragen stellen en de AI laten antwoorden? Keuzemogelijkheden zijn : Nederlands, Engels, Duits, Frans, Spaans.',
341
+ ('Nederlands', 'Engels', 'Duits', 'Frans', 'Spaans'))
342
+
343
+ st.write('You selected:', option)
344
+
345
+ language_prompt = " Antwoordt uitsluitend en alleen in de taal: " + option + " en beslist niet in een andere taal!"
346
+ st.write('language_prompt:', language_prompt)
347
+
348
+ if prompt := st.chat_input():
349
+ #if not openai_api_key:
350
+ # st.info("Please add your OpenAI API key to continue.")
351
+ # st.stop()
352
+
353
+ original_prompt = prompt
354
+ prompt = prompt + language_prompt
355
+ st.write('prompt + language_prompt:', prompt)
356
+
357
+ # Then pass the prompt to the LLM
358
+ start = time.process_time()
359
+ response = retrieval_chain.invoke({"input": prompt})
360
+ # print(f"Response time: {time.process_time() - start}")
361
+ elapsed_time = time.process_time() - start
362
+ st.write(f"Response time van de LLM: {elapsed_time:.1f} seconds")
363
+
364
+ # st.write(response["answer"])
365
+
366
+ # https://docs.streamlit.io/library/api-reference/chat/st.chat_message
367
+ # st.chat_message(name, *, avatar=None)
368
+ # The avatar shown next to the message. Can be one of:
369
+ # - A single emoji, e.g. "🧑‍💻", "🤖", "🦖". Shortcodes are not supported.
370
+ # - An image using one of the formats allowed for st.image: path of a local image file;
371
+ # URL to fetch the image from; an SVG image; array of shape (w,h) or (w,h,1) for a monochrome image,
372
+ # (w,h,3) for a color image, or (w,h,4) for an RGBA image.
373
+ # If None (default), uses default icons if name is "user", "assistant", "ai", "human" or the first letter of the name value.
374
+
375
+ #client = OpenAI(api_key=openai_api_key)
376
+ st.session_state.messages.append({"role": "user", "content": prompt})
377
+ # st.chat_message("user").write(prompt)
378
+ # original_prompt
379
+ st.chat_message("user").write(original_prompt)
380
+ # response = client.chat.completions.create(model="gpt-3.5-turbo", messages=st.session_state.messages)
381
+ # msg = response.choices[0].message.content
382
+ msg = response["answer"]
383
+ st.session_state.messages.append({"role": "assistant", "content": msg})
384
+ # st.chat_message("assistant").write(msg)
385
+ # MET ALS AVATAR EEN IMAGE VAN VICTOR:
386
+ st.chat_message("assistant", avatar="Victor_Benckhuisen_20_percent.jpg").write(msg)
387
+
388
+ # With a streamlit expander
389
+ with st.expander("Document Similarity Search"):
390
+ # Find the relevant chunks
391
+ for i, doc in enumerate(response["context"]):
392
+ # print(doc)
393
+ # st.write(f"Source Document # {i+1} : {doc.metadata['source'].split('/')[-1]}")
394
+ st.write(doc)
395
+ st.write(f"Source Document # {i+1} : {doc.metadata['source'].split('/')[-1]}")
396
+
397
+
398
+ st.write(doc.page_content)
399
+ st.write("--------------------------------")
400
+
401
+ st.write("---------------------------------")
402
+
403
+
404
+
405
+ #i=0
406
+ #while True:
407
+ #
408
+ # # data = ["input1", "input2", "input3"]
409
+ #
410
+ # #for i, item in enumerate(data):
411
+ # key = f"input_{i}"
412
+ # # text_input = st.text_input(f"Enter value for {item}", key=key)
413
+ # # Access the value directly
414
+ # print(f"Value for key: {key}")
415
+ #
416
+ # i=i+1
417
+ #
418
+ # prompt = st.text_input("Input your prompt here", key=key)
419
+ #
420
+ #
421
+ # # If the user hits enter
422
+ # if prompt:
423
+ # # Then pass the prompt to the LLM
424
+ # start = time.process_time()
425
+ # response = retrieval_chain.invoke({"input": prompt})
426
+ # # print(f"Response time: {time.process_time() - start}")
427
+ # st.write(f"Response time: {time.process_time() - start} seconds")
428
+ #
429
+ # st.write(response["answer"])
430
+ #
431
+ # # With a streamlit expander
432
+ # with st.expander("Document Similarity Search"):
433
+ # # Find the relevant chunks
434
+ # for i, doc in enumerate(response["context"]):
435
+ # # print(doc)
436
+ # # st.write(f"Source Document # {i+1} : {doc.metadata['source'].split('/')[-1]}")
437
+ # st.write(doc)
438
+ # st.write(f"Source Document # {i+1} : {doc.metadata['source'].split('/')[-1]}")
439
+ #
440
+ #
441
+ # st.write(doc.page_content)
442
+ # st.write("--------------------------------")
443
+ #
444
+ # st.write("---------------------------------")