OuroborosM commited on
Commit
5edac6d
·
1 Parent(s): b09e27c

Update app.py

Browse files

Correct test msg length

Files changed (1) hide show
  1. app.py +451 -451
app.py CHANGED
@@ -1,451 +1,451 @@
1
- # from typing import Any, Coroutine
2
- import openai
3
- import os
4
- from langchain.vectorstores import Chroma
5
- from langchain.embeddings.openai import OpenAIEmbeddings
6
- from langchain.text_splitter import CharacterTextSplitter
7
- from langchain.chat_models import AzureChatOpenAI
8
- from langchain.document_loaders import DirectoryLoader
9
- from langchain.chains import RetrievalQA
10
- from langchain.vectorstores import Pinecone
11
- from langchain.agents import initialize_agent
12
- from langchain.agents import AgentType
13
- from langchain.agents import Tool
14
- # from langchain.agents import load_tools
15
- from langchain.tools import BaseTool
16
- from langchain.tools import DuckDuckGoSearchRun
17
- from langchain.utilities import WikipediaAPIWrapper
18
- from langchain.python import PythonREPL
19
- from langchain.chains import LLMMathChain
20
-
21
- import pinecone
22
- from pinecone.core.client.configuration import Configuration as OpenApiConfiguration
23
- import gradio as gr
24
- import time
25
-
26
- import glob
27
- from typing import List
28
- from multiprocessing import Pool
29
- from tqdm import tqdm
30
-
31
- from langchain.document_loaders import (
32
- CSVLoader,
33
- EverNoteLoader,
34
- PyMuPDFLoader,
35
- TextLoader,
36
- UnstructuredEmailLoader,
37
- UnstructuredEPubLoader,
38
- UnstructuredHTMLLoader,
39
- UnstructuredMarkdownLoader,
40
- UnstructuredODTLoader,
41
- UnstructuredPowerPointLoader,
42
- UnstructuredWordDocumentLoader,
43
- )
44
- from langchain.text_splitter import RecursiveCharacterTextSplitter
45
- from langchain.docstore.document import Document
46
-
47
- # Custom document loaders
48
- class MyElmLoader(UnstructuredEmailLoader):
49
- """Wrapper to fallback to text/plain when default does not work"""
50
-
51
- def load(self) -> List[Document]:
52
- """Wrapper adding fallback for elm without html"""
53
- try:
54
- try:
55
- doc = UnstructuredEmailLoader.load(self)
56
- except ValueError as e:
57
- if 'text/html content not found in email' in str(e):
58
- # Try plain text
59
- self.unstructured_kwargs["content_source"]="text/plain"
60
- doc = UnstructuredEmailLoader.load(self)
61
- else:
62
- raise
63
- except Exception as e:
64
- # Add file_path to exception message
65
- raise type(e)(f"{self.file_path}: {e}") from e
66
-
67
- return doc
68
-
69
- LOADER_MAPPING = {
70
- ".csv": (CSVLoader, {}),
71
- # ".docx": (Docx2txtLoader, {}),
72
- ".doc": (UnstructuredWordDocumentLoader, {}),
73
- ".docx": (UnstructuredWordDocumentLoader, {}),
74
- ".enex": (EverNoteLoader, {}),
75
- ".eml": (MyElmLoader, {}),
76
- ".epub": (UnstructuredEPubLoader, {}),
77
- ".html": (UnstructuredHTMLLoader, {}),
78
- ".md": (UnstructuredMarkdownLoader, {}),
79
- ".odt": (UnstructuredODTLoader, {}),
80
- ".pdf": (PyMuPDFLoader, {}),
81
- ".ppt": (UnstructuredPowerPointLoader, {}),
82
- ".pptx": (UnstructuredPowerPointLoader, {}),
83
- ".txt": (TextLoader, {"encoding": "utf8"}),
84
- # Add more mappings for other file extensions and loaders as needed
85
- }
86
-
87
- source_directory = 'Upload Files'
88
- file_path = ''
89
- chunk_size = 500
90
- chunk_overlap = 300
91
-
92
- def load_single_document(file_path: str) -> List[Document]:
93
- ext = "." + file_path.rsplit(".", 1)[-1]
94
- if ext in LOADER_MAPPING:
95
- loader_class, loader_args = LOADER_MAPPING[ext]
96
- loader = loader_class(file_path, **loader_args)
97
- return loader.load()
98
-
99
- raise ValueError(f"Unsupported file extension '{ext}'")
100
-
101
-
102
- def load_documents(source_dir: str, ignored_files: List[str] = []) -> List[Document]:
103
- """
104
- Loads all documents from the source documents directory, ignoring specified files
105
- """
106
- all_files = []
107
- for ext in LOADER_MAPPING:
108
- all_files.extend(
109
- glob.glob(os.path.join(source_dir, f"**/*{ext}"), recursive=True)
110
- )
111
- filtered_files = [file_path for file_path in all_files if file_path not in ignored_files]
112
-
113
- with Pool(processes=os.cpu_count()) as pool:
114
- results = []
115
- with tqdm(total=len(filtered_files), desc='Loading new documents', ncols=80) as pbar:
116
- for i, docs in enumerate(pool.imap_unordered(load_single_document, filtered_files)):
117
- results.extend(docs)
118
- pbar.update()
119
-
120
- return results
121
-
122
- def process_documents(ignored_files: List[str] = []) -> List[Document]:
123
- """
124
- Load documents and split in chunks
125
- """
126
- print(f"Loading documents from {source_directory}")
127
- documents = load_documents(source_directory, ignored_files)
128
- if not documents:
129
- print("No new documents to load")
130
- exit(0)
131
- print(f"Loaded {len(documents)} new documents from {source_directory}")
132
- text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
133
- texts = text_splitter.split_documents(documents)
134
- print(f"Split into {len(texts)} chunks of text (max. {chunk_size} tokens each)")
135
- return texts
136
-
137
- def process_documents_2(ignored_files: List[str] = []) -> List[Document]:
138
- """
139
- Load documents and split in chunks
140
- """
141
- print(f"Loading documents from {source_directory}")
142
- print("File Path to start processing:", file_path)
143
- documents = load_documents(file_path, ignored_files)
144
- if not documents:
145
- print("No new documents to load")
146
- exit(0)
147
- print(f"Loaded {len(documents)} new documents from {source_directory}")
148
- text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
149
- texts = text_splitter.split_documents(documents)
150
- print(f"Split into {len(texts)} chunks of text (max. {chunk_size} tokens each)")
151
- return texts
152
-
153
- def UpdateDb():
154
- global vectordb_p
155
- # pinecone.Index(index_name).delete(delete_all=True, namespace='')
156
- # collection = vectordb_p.get()
157
- # split_docs = process_documents([metadata['source'] for metadata in collection['metadatas']])
158
- # split_docs = process_documents()
159
- split_docs = process_documents_2()
160
- tt = len(split_docs)
161
- print(split_docs[tt-1])
162
- print(f"Creating embeddings. May take some minutes...")
163
- vectordb_p = Pinecone.from_documents(split_docs, embeddings, index_name = "stla-baby")
164
- print("Pinecone Updated Done")
165
- print(index.describe_index_stats())
166
-
167
-
168
- class DB_Search(BaseTool):
169
- name = "Vector Database Search"
170
- description = "This is the internal database to search information firstly. If information is found, it is trustful."
171
- def _run(self, query: str) -> str:
172
- response, source = QAQuery_p(query)
173
- # response = "test db_search feedback"
174
- return response
175
-
176
- def _arun(self, query: str):
177
- raise NotImplementedError("N/A")
178
-
179
-
180
-
181
- Wikipedia = WikipediaAPIWrapper()
182
- Netsearch = DuckDuckGoSearchRun()
183
- Python_REPL = PythonREPL()
184
-
185
- wikipedia_tool = Tool(
186
- name = "Wikipedia Search",
187
- func = Wikipedia.run,
188
- description = "Useful to search a topic, country or person when there is no availble information in vector database"
189
- )
190
-
191
- duckduckgo_tool = Tool(
192
- name = "Duckduckgo Internet Search",
193
- func = Netsearch.run,
194
- description = "Useful to search information in internet when it is not available in other tools"
195
- )
196
-
197
- python_tool = Tool(
198
- name = "Python REPL",
199
- func = Python_REPL.run,
200
- description = "Useful when you need python to answer questions. You should input python code."
201
- )
202
-
203
- # tools = [DB_Search(), wikipedia_tool, duckduckgo_tool, python_tool]
204
-
205
-
206
- os.environ["OPENAI_API_TYPE"] = "azure"
207
- os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
208
- os.environ["OPENAI_API_BASE"] = os.getenv("OPENAI_API_BASE")
209
- os.environ["OPENAI_API_VERSION"] = "2023-05-15"
210
- username = os.getenv("username")
211
- password = os.getenv("password")
212
- SysLock = os.getenv("SysLock") # 0=unlock 1=lock
213
-
214
- chat = AzureChatOpenAI(
215
- deployment_name="Chattester",
216
- temperature=0,
217
- )
218
- llm = chat
219
-
220
- llm_math = LLMMathChain.from_llm(llm)
221
-
222
- math_tool = Tool(
223
- name ='Calculator',
224
- func = llm_math.run,
225
- description ='Useful for when you need to answer questions about math.'
226
- )
227
-
228
- tools = [DB_Search(), duckduckgo_tool, wikipedia_tool, python_tool, math_tool]
229
-
230
- # tools = load_tools(["Vector Database Search","Wikipedia Search","Python REPL","llm-math"], llm=llm)
231
-
232
- embeddings = OpenAIEmbeddings(deployment="model_embedding", chunk_size=15)
233
-
234
-
235
- pinecone.init(
236
- api_key = os.getenv("pinecone_api_key"),
237
- environment='asia-southeast1-gcp-free',
238
- # openapi_config=openapi_config
239
- )
240
- index_name = 'stla-baby'
241
- index = pinecone.Index(index_name)
242
- # index.delete(delete_all=True, namespace='')
243
- # print(pinecone.whoami())
244
- # print(index.describe_index_stats())
245
-
246
- PREFIX = """Answer the following questions as best you can with details. You must always check internal vector database first and try to answer the question based on the information in internal vector database only.
247
- Only when there is no information available from vector database, you can search information by using another tools.
248
- You have access to the following tools:
249
-
250
- Vector Database Search: This is the internal database to search information firstly. If information is found, it is trustful.
251
- Duckduckgo Internet Search: Useful to search information in internet when it is not available in other tools.
252
- Wikipedia Search: Useful to search a topic, country or person when there is no availble information in vector database
253
- Python REPL: Useful when you need python to answer questions. You should input python code.
254
- Calculator: Useful for when you need to answer questions about math."""
255
-
256
- FORMAT_INSTRUCTIONS = """Use the following format:
257
-
258
- Question: the input question you must answer
259
- Thought: you should always think about what to do
260
- Action: the action to take, should be one of [Vector Database Search, Duckduckgo Internet Search, Python REPL, Calculator]
261
- Action Input: the input to the action
262
- Observation: the result of the action
263
- ... (this Thought/Action/Action Input/Observation can repeat N times)
264
- Thought: I now know the final answer
265
- Final Answer: the final answer to the original input question"""
266
-
267
- SUFFIX = """Begin!
268
- Question: {input}
269
- Thought:{agent_scratchpad}"""
270
-
271
- agent = initialize_agent(tools, llm,
272
- agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
273
- verbose = True,
274
- handle_parsing_errors = True,
275
- max_iterations = int(os.getenv("max_iterations")),
276
- early_stopping_method="generate",
277
- agent_kwargs={
278
- 'prefix': PREFIX,
279
- 'format_instructions': FORMAT_INSTRUCTIONS,
280
- 'suffix': SUFFIX
281
- }
282
- )
283
-
284
- print(agent.agent.llm_chain.prompt.template)
285
-
286
- global vectordb
287
- vectordb = Chroma(persist_directory='db', embedding_function=embeddings)
288
- global vectordb_p
289
- vectordb_p = Pinecone.from_existing_index(index_name, embeddings)
290
-
291
- # loader = DirectoryLoader('./documents', glob='**/*.txt')
292
- # documents = loader.load()
293
- # text_splitter = CharacterTextSplitter(chunk_size=500, chunk_overlap=200)
294
- # split_docs = text_splitter.split_documents(documents)
295
- # print(split_docs)
296
- # vectordb = Chroma.from_documents(split_docs, embeddings, persist_directory='db')
297
-
298
-
299
-
300
- # question = "what is LCDV ?"
301
- # rr = vectordb.similarity_search(query=question, k=4)
302
- # vectordb.similarity_search(question)
303
- # print(type(rr))
304
- # print(rr)
305
- def chathmi(message, history):
306
- # response = "I don't know"
307
- # print(message)
308
- response, source = QAQuery_p(message)
309
- time.sleep(0.3)
310
- print(history)
311
- yield response
312
- # yield history
313
-
314
- def chathmi2(message, history):
315
- try:
316
- output = agent.run(message)
317
- time.sleep(0.3)
318
- print("History: ", history)
319
- response = output
320
- yield response
321
- except Exception as e:
322
- print("error:", e)
323
-
324
- # yield history
325
- # chatbot = gr.Chatbot().style(color_map =("blue", "pink"))
326
- # chatbot = gr.Chatbot(color_map =("blue", "pink"))
327
-
328
- def func_upload_file(files, chat_history):
329
- file_path = files
330
- print(file_path)
331
- # UpdateDb()
332
- test_msg = ["How are you?", "I love you", "I'm very hungry"]
333
- chat_history.append(test_msg)
334
- return chat_history
335
-
336
- with gr.Blocks() as demo:
337
- main = gr.ChatInterface(
338
- chathmi2,
339
- title="STLA BABY - YOUR FRIENDLY GUIDE",
340
- description= "v0.3: Powered by MECH Core Team",
341
- )
342
- upload_button = gr.UploadButton("Upload File", file_count="multiple")
343
- upload_button.upload(func_upload_file, [upload_button, main.chatbot], main.chatbot)
344
-
345
- # demo = gr.Interface(
346
- # chathmi,
347
- # ["text", "state"],
348
- # [chatbot, "state"],
349
- # allow_flagging="never",
350
- # )
351
-
352
- def CreatDb_P():
353
- global vectordb_p
354
- index_name = 'stla-baby'
355
- loader = DirectoryLoader('./documents', glob='**/*.txt')
356
- documents = loader.load()
357
- text_splitter = CharacterTextSplitter(chunk_size=500, chunk_overlap=200)
358
- split_docs = text_splitter.split_documents(documents)
359
- print(split_docs)
360
- pinecone.Index(index_name).delete(delete_all=True, namespace='')
361
- vectordb_p = Pinecone.from_documents(split_docs, embeddings, index_name = "stla-baby")
362
- print("Pinecone Updated Done")
363
- print(index.describe_index_stats())
364
-
365
- def QAQuery_p(question: str):
366
- global vectordb_p
367
- # vectordb = Chroma(persist_directory='db', embedding_function=embeddings)
368
- retriever = vectordb_p.as_retriever()
369
- retriever.search_kwargs['k'] = int(os.getenv("search_kwargs_k"))
370
- # retriever.search_kwargs['fetch_k'] = 100
371
-
372
- qa = RetrievalQA.from_chain_type(llm=chat, chain_type="stuff",
373
- retriever=retriever, return_source_documents = True,
374
- verbose = True)
375
- # qa = VectorDBQA.from_chain_type(llm=chat, chain_type="stuff", vectorstore=vectordb, return_source_documents=True)
376
- # res = qa.run(question)
377
- res = qa({"query": question})
378
-
379
- print("-" * 20)
380
- print("Question:", question)
381
- # print("Answer:", res)
382
- print("Answer:", res['result'])
383
- print("-" * 20)
384
- print("Source:", res['source_documents'])
385
- response = res['result']
386
- # response = res['source_documents']
387
- source = res['source_documents']
388
- return response, source
389
-
390
- def CreatDb():
391
- global vectordb
392
- loader = DirectoryLoader('./documents', glob='**/*.txt')
393
- documents = loader.load()
394
- text_splitter = CharacterTextSplitter(chunk_size=500, chunk_overlap=200)
395
- split_docs = text_splitter.split_documents(documents)
396
- print(split_docs)
397
- vectordb = Chroma.from_documents(split_docs, embeddings, persist_directory='db')
398
- vectordb.persist()
399
-
400
- def QAQuery(question: str):
401
- global vectordb
402
- # vectordb = Chroma(persist_directory='db', embedding_function=embeddings)
403
- retriever = vectordb.as_retriever()
404
- retriever.search_kwargs['k'] = 3
405
- # retriever.search_kwargs['fetch_k'] = 100
406
-
407
- qa = RetrievalQA.from_chain_type(llm=chat, chain_type="stuff", retriever=retriever, return_source_documents = True)
408
- # qa = VectorDBQA.from_chain_type(llm=chat, chain_type="stuff", vectorstore=vectordb, return_source_documents=True)
409
- # res = qa.run(question)
410
- res = qa({"query": question})
411
-
412
- print("-" * 20)
413
- print("Question:", question)
414
- # print("Answer:", res)
415
- print("Answer:", res['result'])
416
- print("-" * 20)
417
- print("Source:", res['source_documents'])
418
- response = res['result']
419
- return response
420
-
421
- # Used to complete content
422
- def completeText(Text):
423
- deployment_id="Chattester"
424
- prompt = Text
425
- completion = openai.Completion.create(deployment_id=deployment_id,
426
- prompt=prompt, temperature=0)
427
- print(f"{prompt}{completion['choices'][0]['text']}.")
428
-
429
- # Used to chat
430
- def chatText(Text):
431
- deployment_id="Chattester"
432
- conversation = [{"role": "system", "content": "You are a helpful assistant."}]
433
- user_input = Text
434
- conversation.append({"role": "user", "content": user_input})
435
- response = openai.ChatCompletion.create(messages=conversation,
436
- deployment_id="Chattester")
437
- print("\n" + response["choices"][0]["message"]["content"] + "\n")
438
-
439
- if __name__ == '__main__':
440
- # chatText("what is AI?")
441
- # CreatDb()
442
- # QAQuery("what is COFOR ?")
443
- # CreatDb_P()
444
- # QAQuery_p("what is GST ?")
445
- if SysLock == "1":
446
- demo.queue().launch(auth=(username, password))
447
- else:
448
- demo.queue().launch()
449
- pass
450
-
451
-
 
1
+ # from typing import Any, Coroutine
2
+ import openai
3
+ import os
4
+ from langchain.vectorstores import Chroma
5
+ from langchain.embeddings.openai import OpenAIEmbeddings
6
+ from langchain.text_splitter import CharacterTextSplitter
7
+ from langchain.chat_models import AzureChatOpenAI
8
+ from langchain.document_loaders import DirectoryLoader
9
+ from langchain.chains import RetrievalQA
10
+ from langchain.vectorstores import Pinecone
11
+ from langchain.agents import initialize_agent
12
+ from langchain.agents import AgentType
13
+ from langchain.agents import Tool
14
+ # from langchain.agents import load_tools
15
+ from langchain.tools import BaseTool
16
+ from langchain.tools import DuckDuckGoSearchRun
17
+ from langchain.utilities import WikipediaAPIWrapper
18
+ from langchain.python import PythonREPL
19
+ from langchain.chains import LLMMathChain
20
+
21
+ import pinecone
22
+ from pinecone.core.client.configuration import Configuration as OpenApiConfiguration
23
+ import gradio as gr
24
+ import time
25
+
26
+ import glob
27
+ from typing import List
28
+ from multiprocessing import Pool
29
+ from tqdm import tqdm
30
+
31
+ from langchain.document_loaders import (
32
+ CSVLoader,
33
+ EverNoteLoader,
34
+ PyMuPDFLoader,
35
+ TextLoader,
36
+ UnstructuredEmailLoader,
37
+ UnstructuredEPubLoader,
38
+ UnstructuredHTMLLoader,
39
+ UnstructuredMarkdownLoader,
40
+ UnstructuredODTLoader,
41
+ UnstructuredPowerPointLoader,
42
+ UnstructuredWordDocumentLoader,
43
+ )
44
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
45
+ from langchain.docstore.document import Document
46
+
47
+ # Custom document loaders
48
+ class MyElmLoader(UnstructuredEmailLoader):
49
+ """Wrapper to fallback to text/plain when default does not work"""
50
+
51
+ def load(self) -> List[Document]:
52
+ """Wrapper adding fallback for elm without html"""
53
+ try:
54
+ try:
55
+ doc = UnstructuredEmailLoader.load(self)
56
+ except ValueError as e:
57
+ if 'text/html content not found in email' in str(e):
58
+ # Try plain text
59
+ self.unstructured_kwargs["content_source"]="text/plain"
60
+ doc = UnstructuredEmailLoader.load(self)
61
+ else:
62
+ raise
63
+ except Exception as e:
64
+ # Add file_path to exception message
65
+ raise type(e)(f"{self.file_path}: {e}") from e
66
+
67
+ return doc
68
+
69
+ LOADER_MAPPING = {
70
+ ".csv": (CSVLoader, {}),
71
+ # ".docx": (Docx2txtLoader, {}),
72
+ ".doc": (UnstructuredWordDocumentLoader, {}),
73
+ ".docx": (UnstructuredWordDocumentLoader, {}),
74
+ ".enex": (EverNoteLoader, {}),
75
+ ".eml": (MyElmLoader, {}),
76
+ ".epub": (UnstructuredEPubLoader, {}),
77
+ ".html": (UnstructuredHTMLLoader, {}),
78
+ ".md": (UnstructuredMarkdownLoader, {}),
79
+ ".odt": (UnstructuredODTLoader, {}),
80
+ ".pdf": (PyMuPDFLoader, {}),
81
+ ".ppt": (UnstructuredPowerPointLoader, {}),
82
+ ".pptx": (UnstructuredPowerPointLoader, {}),
83
+ ".txt": (TextLoader, {"encoding": "utf8"}),
84
+ # Add more mappings for other file extensions and loaders as needed
85
+ }
86
+
87
+ source_directory = 'Upload Files'
88
+ file_path = ''
89
+ chunk_size = 500
90
+ chunk_overlap = 300
91
+
92
+ def load_single_document(file_path: str) -> List[Document]:
93
+ ext = "." + file_path.rsplit(".", 1)[-1]
94
+ if ext in LOADER_MAPPING:
95
+ loader_class, loader_args = LOADER_MAPPING[ext]
96
+ loader = loader_class(file_path, **loader_args)
97
+ return loader.load()
98
+
99
+ raise ValueError(f"Unsupported file extension '{ext}'")
100
+
101
+
102
+ def load_documents(source_dir: str, ignored_files: List[str] = []) -> List[Document]:
103
+ """
104
+ Loads all documents from the source documents directory, ignoring specified files
105
+ """
106
+ all_files = []
107
+ for ext in LOADER_MAPPING:
108
+ all_files.extend(
109
+ glob.glob(os.path.join(source_dir, f"**/*{ext}"), recursive=True)
110
+ )
111
+ filtered_files = [file_path for file_path in all_files if file_path not in ignored_files]
112
+
113
+ with Pool(processes=os.cpu_count()) as pool:
114
+ results = []
115
+ with tqdm(total=len(filtered_files), desc='Loading new documents', ncols=80) as pbar:
116
+ for i, docs in enumerate(pool.imap_unordered(load_single_document, filtered_files)):
117
+ results.extend(docs)
118
+ pbar.update()
119
+
120
+ return results
121
+
122
+ def process_documents(ignored_files: List[str] = []) -> List[Document]:
123
+ """
124
+ Load documents and split in chunks
125
+ """
126
+ print(f"Loading documents from {source_directory}")
127
+ documents = load_documents(source_directory, ignored_files)
128
+ if not documents:
129
+ print("No new documents to load")
130
+ exit(0)
131
+ print(f"Loaded {len(documents)} new documents from {source_directory}")
132
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
133
+ texts = text_splitter.split_documents(documents)
134
+ print(f"Split into {len(texts)} chunks of text (max. {chunk_size} tokens each)")
135
+ return texts
136
+
137
+ def process_documents_2(ignored_files: List[str] = []) -> List[Document]:
138
+ """
139
+ Load documents and split in chunks
140
+ """
141
+ print(f"Loading documents from {source_directory}")
142
+ print("File Path to start processing:", file_path)
143
+ documents = load_documents(file_path, ignored_files)
144
+ if not documents:
145
+ print("No new documents to load")
146
+ exit(0)
147
+ print(f"Loaded {len(documents)} new documents from {source_directory}")
148
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
149
+ texts = text_splitter.split_documents(documents)
150
+ print(f"Split into {len(texts)} chunks of text (max. {chunk_size} tokens each)")
151
+ return texts
152
+
153
+ def UpdateDb():
154
+ global vectordb_p
155
+ # pinecone.Index(index_name).delete(delete_all=True, namespace='')
156
+ # collection = vectordb_p.get()
157
+ # split_docs = process_documents([metadata['source'] for metadata in collection['metadatas']])
158
+ # split_docs = process_documents()
159
+ split_docs = process_documents_2()
160
+ tt = len(split_docs)
161
+ print(split_docs[tt-1])
162
+ print(f"Creating embeddings. May take some minutes...")
163
+ vectordb_p = Pinecone.from_documents(split_docs, embeddings, index_name = "stla-baby")
164
+ print("Pinecone Updated Done")
165
+ print(index.describe_index_stats())
166
+
167
+
168
+ class DB_Search(BaseTool):
169
+ name = "Vector Database Search"
170
+ description = "This is the internal database to search information firstly. If information is found, it is trustful."
171
+ def _run(self, query: str) -> str:
172
+ response, source = QAQuery_p(query)
173
+ # response = "test db_search feedback"
174
+ return response
175
+
176
+ def _arun(self, query: str):
177
+ raise NotImplementedError("N/A")
178
+
179
+
180
+
181
+ Wikipedia = WikipediaAPIWrapper()
182
+ Netsearch = DuckDuckGoSearchRun()
183
+ Python_REPL = PythonREPL()
184
+
185
+ wikipedia_tool = Tool(
186
+ name = "Wikipedia Search",
187
+ func = Wikipedia.run,
188
+ description = "Useful to search a topic, country or person when there is no availble information in vector database"
189
+ )
190
+
191
+ duckduckgo_tool = Tool(
192
+ name = "Duckduckgo Internet Search",
193
+ func = Netsearch.run,
194
+ description = "Useful to search information in internet when it is not available in other tools"
195
+ )
196
+
197
+ python_tool = Tool(
198
+ name = "Python REPL",
199
+ func = Python_REPL.run,
200
+ description = "Useful when you need python to answer questions. You should input python code."
201
+ )
202
+
203
+ # tools = [DB_Search(), wikipedia_tool, duckduckgo_tool, python_tool]
204
+
205
+
206
+ os.environ["OPENAI_API_TYPE"] = "azure"
207
+ os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
208
+ os.environ["OPENAI_API_BASE"] = os.getenv("OPENAI_API_BASE")
209
+ os.environ["OPENAI_API_VERSION"] = "2023-05-15"
210
+ username = os.getenv("username")
211
+ password = os.getenv("password")
212
+ SysLock = os.getenv("SysLock") # 0=unlock 1=lock
213
+
214
+ chat = AzureChatOpenAI(
215
+ deployment_name="Chattester",
216
+ temperature=0,
217
+ )
218
+ llm = chat
219
+
220
+ llm_math = LLMMathChain.from_llm(llm)
221
+
222
+ math_tool = Tool(
223
+ name ='Calculator',
224
+ func = llm_math.run,
225
+ description ='Useful for when you need to answer questions about math.'
226
+ )
227
+
228
+ tools = [DB_Search(), duckduckgo_tool, wikipedia_tool, python_tool, math_tool]
229
+
230
+ # tools = load_tools(["Vector Database Search","Wikipedia Search","Python REPL","llm-math"], llm=llm)
231
+
232
+ embeddings = OpenAIEmbeddings(deployment="model_embedding", chunk_size=15)
233
+
234
+
235
+ pinecone.init(
236
+ api_key = os.getenv("pinecone_api_key"),
237
+ environment='asia-southeast1-gcp-free',
238
+ # openapi_config=openapi_config
239
+ )
240
+ index_name = 'stla-baby'
241
+ index = pinecone.Index(index_name)
242
+ # index.delete(delete_all=True, namespace='')
243
+ # print(pinecone.whoami())
244
+ # print(index.describe_index_stats())
245
+
246
+ PREFIX = """Answer the following questions as best you can with details. You must always check internal vector database first and try to answer the question based on the information in internal vector database only.
247
+ Only when there is no information available from vector database, you can search information by using another tools.
248
+ You have access to the following tools:
249
+
250
+ Vector Database Search: This is the internal database to search information firstly. If information is found, it is trustful.
251
+ Duckduckgo Internet Search: Useful to search information in internet when it is not available in other tools.
252
+ Wikipedia Search: Useful to search a topic, country or person when there is no availble information in vector database
253
+ Python REPL: Useful when you need python to answer questions. You should input python code.
254
+ Calculator: Useful for when you need to answer questions about math."""
255
+
256
+ FORMAT_INSTRUCTIONS = """Use the following format:
257
+
258
+ Question: the input question you must answer
259
+ Thought: you should always think about what to do
260
+ Action: the action to take, should be one of [Vector Database Search, Duckduckgo Internet Search, Python REPL, Calculator]
261
+ Action Input: the input to the action
262
+ Observation: the result of the action
263
+ ... (this Thought/Action/Action Input/Observation can repeat N times)
264
+ Thought: I now know the final answer
265
+ Final Answer: the final answer to the original input question"""
266
+
267
+ SUFFIX = """Begin!
268
+ Question: {input}
269
+ Thought:{agent_scratchpad}"""
270
+
271
+ agent = initialize_agent(tools, llm,
272
+ agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
273
+ verbose = True,
274
+ handle_parsing_errors = True,
275
+ max_iterations = int(os.getenv("max_iterations")),
276
+ early_stopping_method="generate",
277
+ agent_kwargs={
278
+ 'prefix': PREFIX,
279
+ 'format_instructions': FORMAT_INSTRUCTIONS,
280
+ 'suffix': SUFFIX
281
+ }
282
+ )
283
+
284
+ print(agent.agent.llm_chain.prompt.template)
285
+
286
+ global vectordb
287
+ vectordb = Chroma(persist_directory='db', embedding_function=embeddings)
288
+ global vectordb_p
289
+ vectordb_p = Pinecone.from_existing_index(index_name, embeddings)
290
+
291
+ # loader = DirectoryLoader('./documents', glob='**/*.txt')
292
+ # documents = loader.load()
293
+ # text_splitter = CharacterTextSplitter(chunk_size=500, chunk_overlap=200)
294
+ # split_docs = text_splitter.split_documents(documents)
295
+ # print(split_docs)
296
+ # vectordb = Chroma.from_documents(split_docs, embeddings, persist_directory='db')
297
+
298
+
299
+
300
+ # question = "what is LCDV ?"
301
+ # rr = vectordb.similarity_search(query=question, k=4)
302
+ # vectordb.similarity_search(question)
303
+ # print(type(rr))
304
+ # print(rr)
305
+ def chathmi(message, history):
306
+ # response = "I don't know"
307
+ # print(message)
308
+ response, source = QAQuery_p(message)
309
+ time.sleep(0.3)
310
+ print(history)
311
+ yield response
312
+ # yield history
313
+
314
+ def chathmi2(message, history):
315
+ try:
316
+ output = agent.run(message)
317
+ time.sleep(0.3)
318
+ print("History: ", history)
319
+ response = output
320
+ yield response
321
+ except Exception as e:
322
+ print("error:", e)
323
+
324
+ # yield history
325
+ # chatbot = gr.Chatbot().style(color_map =("blue", "pink"))
326
+ # chatbot = gr.Chatbot(color_map =("blue", "pink"))
327
+
328
+ def func_upload_file(files, chat_history):
329
+ file_path = files
330
+ print(file_path)
331
+ # UpdateDb()
332
+ test_msg = ["Test upload"]
333
+ chat_history.append(test_msg)
334
+ return chat_history
335
+
336
+ with gr.Blocks() as demo:
337
+ main = gr.ChatInterface(
338
+ chathmi2,
339
+ title="STLA BABY - YOUR FRIENDLY GUIDE",
340
+ description= "v0.3: Powered by MECH Core Team",
341
+ )
342
+ upload_button = gr.UploadButton("Upload File", file_count="multiple")
343
+ upload_button.upload(func_upload_file, [upload_button, main.chatbot], main.chatbot)
344
+
345
+ # demo = gr.Interface(
346
+ # chathmi,
347
+ # ["text", "state"],
348
+ # [chatbot, "state"],
349
+ # allow_flagging="never",
350
+ # )
351
+
352
+ def CreatDb_P():
353
+ global vectordb_p
354
+ index_name = 'stla-baby'
355
+ loader = DirectoryLoader('./documents', glob='**/*.txt')
356
+ documents = loader.load()
357
+ text_splitter = CharacterTextSplitter(chunk_size=500, chunk_overlap=200)
358
+ split_docs = text_splitter.split_documents(documents)
359
+ print(split_docs)
360
+ pinecone.Index(index_name).delete(delete_all=True, namespace='')
361
+ vectordb_p = Pinecone.from_documents(split_docs, embeddings, index_name = "stla-baby")
362
+ print("Pinecone Updated Done")
363
+ print(index.describe_index_stats())
364
+
365
+ def QAQuery_p(question: str):
366
+ global vectordb_p
367
+ # vectordb = Chroma(persist_directory='db', embedding_function=embeddings)
368
+ retriever = vectordb_p.as_retriever()
369
+ retriever.search_kwargs['k'] = int(os.getenv("search_kwargs_k"))
370
+ # retriever.search_kwargs['fetch_k'] = 100
371
+
372
+ qa = RetrievalQA.from_chain_type(llm=chat, chain_type="stuff",
373
+ retriever=retriever, return_source_documents = True,
374
+ verbose = True)
375
+ # qa = VectorDBQA.from_chain_type(llm=chat, chain_type="stuff", vectorstore=vectordb, return_source_documents=True)
376
+ # res = qa.run(question)
377
+ res = qa({"query": question})
378
+
379
+ print("-" * 20)
380
+ print("Question:", question)
381
+ # print("Answer:", res)
382
+ print("Answer:", res['result'])
383
+ print("-" * 20)
384
+ print("Source:", res['source_documents'])
385
+ response = res['result']
386
+ # response = res['source_documents']
387
+ source = res['source_documents']
388
+ return response, source
389
+
390
+ def CreatDb():
391
+ global vectordb
392
+ loader = DirectoryLoader('./documents', glob='**/*.txt')
393
+ documents = loader.load()
394
+ text_splitter = CharacterTextSplitter(chunk_size=500, chunk_overlap=200)
395
+ split_docs = text_splitter.split_documents(documents)
396
+ print(split_docs)
397
+ vectordb = Chroma.from_documents(split_docs, embeddings, persist_directory='db')
398
+ vectordb.persist()
399
+
400
+ def QAQuery(question: str):
401
+ global vectordb
402
+ # vectordb = Chroma(persist_directory='db', embedding_function=embeddings)
403
+ retriever = vectordb.as_retriever()
404
+ retriever.search_kwargs['k'] = 3
405
+ # retriever.search_kwargs['fetch_k'] = 100
406
+
407
+ qa = RetrievalQA.from_chain_type(llm=chat, chain_type="stuff", retriever=retriever, return_source_documents = True)
408
+ # qa = VectorDBQA.from_chain_type(llm=chat, chain_type="stuff", vectorstore=vectordb, return_source_documents=True)
409
+ # res = qa.run(question)
410
+ res = qa({"query": question})
411
+
412
+ print("-" * 20)
413
+ print("Question:", question)
414
+ # print("Answer:", res)
415
+ print("Answer:", res['result'])
416
+ print("-" * 20)
417
+ print("Source:", res['source_documents'])
418
+ response = res['result']
419
+ return response
420
+
421
+ # Used to complete content
422
+ def completeText(Text):
423
+ deployment_id="Chattester"
424
+ prompt = Text
425
+ completion = openai.Completion.create(deployment_id=deployment_id,
426
+ prompt=prompt, temperature=0)
427
+ print(f"{prompt}{completion['choices'][0]['text']}.")
428
+
429
+ # Used to chat
430
+ def chatText(Text):
431
+ deployment_id="Chattester"
432
+ conversation = [{"role": "system", "content": "You are a helpful assistant."}]
433
+ user_input = Text
434
+ conversation.append({"role": "user", "content": user_input})
435
+ response = openai.ChatCompletion.create(messages=conversation,
436
+ deployment_id="Chattester")
437
+ print("\n" + response["choices"][0]["message"]["content"] + "\n")
438
+
439
+ if __name__ == '__main__':
440
+ # chatText("what is AI?")
441
+ # CreatDb()
442
+ # QAQuery("what is COFOR ?")
443
+ # CreatDb_P()
444
+ # QAQuery_p("what is GST ?")
445
+ if SysLock == "1":
446
+ demo.queue().launch(auth=(username, password))
447
+ else:
448
+ demo.queue().launch()
449
+ pass
450
+
451
+