forked from AllAboutAI-YT/easy-local-rag
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgroq_lama_MIlvs_RAG_ETTS.py
636 lines (517 loc) · 19.1 KB
/
groq_lama_MIlvs_RAG_ETTS.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
import argparse
import ollama
from groq import Groq
import io
from pydub import AudioSegment
from pydub.playback import play
import threading
import subprocess
import queue
import re
import os
import time
from pymilvus import (
MilvusClient,
connections,
Collection,
FieldSchema,
CollectionSchema,
DataType,
utility,
)
import speech_recognition as sr
import edge_tts
import asyncio
import nest_asyncio
# Constants
EMBEDDINGS_DIR = "Embeddings"
model = "mxbai-embed-large"
# groq_model="llama3-70b-8192"
groq_model = "llama-3.1-70b-versatile"
ollama_model = "phi-3"
json_file = "semantic_vault.json"
# ANSI escape codes for colors
PINK = "\033[95m"
CYAN = "\033[96m"
YELLOW = "\033[93m"
NEON_GREEN = "\033[92m"
MAGENTA = "\033[35m"
BLUE = "\033[94m"
RED = "\033[91m"
BOLD = "\033[1m"
RESET_COLOR = "\033[0m"
"""
######## ######## ######
## ## ## ##
## ## ##
## ## ######
## ## ##
## ## ## ##
## ## ######
"""
# Apply the nest_asyncio patch
nest_asyncio.apply()
# Function to process the queue
def process_TTS_Audio_play_queue(TTS_Audio_play_queue):
while True:
audio_fp = TTS_Audio_play_queue.get()
audio_fp.seek(0)
sound = AudioSegment.from_file(audio_fp, format="mp3")
# Play the adjusted audio
play(sound)
TTS_Audio_play_queue.task_done()
# Queue for sentences
TTS_Audio_play_queue = queue.Queue()
# Start the worker thread
worker_thread = threading.Thread(
target=process_TTS_Audio_play_queue, args=(TTS_Audio_play_queue,), daemon=True
)
worker_thread.start()
# Function to convert text to speech using edge-tts and play using pydub with speed adjustment
async def text_to_speech(text, speed=1.2, volume=1, voice="en-GB-MiaNeural"):
try:
rate = "+" + str(int((speed - 1) * 100)) + "%"
communicate = edge_tts.Communicate(text, voice, rate=rate)
audio_bytes = b""
async for chunk in communicate.stream():
if chunk["type"] == "audio":
audio_bytes += chunk["data"]
if not audio_bytes:
raise ValueError(
"No audio was received. Please verify that your parameters are correct."
)
audio_fp = io.BytesIO(audio_bytes)
audio_fp.seek(0)
TTS_Audio_play_queue.put(audio_fp)
except Exception as e:
print(f"Error occurred during playback: {e}")
# Function to process the queue
def process_TTS_queue(TTS_queue):
while True:
sentence = TTS_queue.get()
if sentence is None: # Sentinel value to stop the worker
break
asyncio.run(text_to_speech(sentence, speed=1.2))
TTS_queue.task_done()
"""
###### ######## ########
## ## ## ##
## ## ##
###### ## ##
## ## ##
## ## ## ##
###### ## ##
"""
# Function to listen for the wake word
def listen_for_wake_word(wake_word="hey llama"):
recognizer = sr.Recognizer()
microphone = sr.Microphone()
with microphone as source:
recognizer.adjust_for_ambient_noise(source)
print("Listening for the wake word...")
while True:
audio = recognizer.listen(source)
try:
speech_text = recognizer.recognize_google(audio).lower()
if wake_word in speech_text:
print(f"{wake_word.capitalize()} detected!")
prompt_user()
except sr.UnknownValueError:
pass
except sr.RequestError:
print("API unavailable")
"""
###### ## ## ### ########
## ## ## ## ## ## ##
## ## ## ## ## ##
## ######### ## ## ##
## ## ## ######### ##
## ## ## ## ## ## ##
###### ## ## ## ## ##
"""
def chat_with_model(
user_input,
system_message,
groq_model,
ollama_model,
conversation_history,
):
try:
response = groq_chat(
user_input, system_message, groq_model, conversation_history
)
except Exception as e:
if "Groq API limit reached" in str(e):
response = ollama_chat(
user_input, system_message, ollama_model, conversation_history
)
else:
raise e
return response
"""
####### ## ## ### ## ## ###
## ## ## ## ## ## ### ### ## ##
## ## ## ## ## ## #### #### ## ##
## ## ## ## ## ## ## ### ## ## ##
## ## ## ## ######### ## ## #########
## ## ## ## ## ## ## ## ## ##
####### ######## ######## ## ## ## ## ## ##
"""
# Function to interact with the Ollama model
def ollama_chat(
user_input,
system_message,
ollama_model,
conversation_history,
):
# Get relevant context from Milvus
relevant_context = get_relevant_context(user_input, top_k=5)
if relevant_context:
print(
"Context Pulled from Documents: \n\n"
+ CYAN
+ relevant_context
+ RESET_COLOR
+ "\n\n"
)
else:
print("No relevant context found.")
# Prepare the user's input by concatenating it with the relevant context
user_input_with_context = user_input
if relevant_context:
user_input_with_context = relevant_context + "\n\n" + user_input
# Reset conversation history
conversation_history = []
# Append the user's input to the conversation history
conversation_history.append({"role": "user", "content": user_input_with_context})
# Create a message history including the system message and the conversation history
messages = [{"role": "system", "content": system_message}, *conversation_history]
# Send the completion request to the Ollama model with stream=True
stream = ollama.chat(
model=ollama_model,
messages=messages,
stream=True,
keep_alive=-1,
)
# Queue for sentences
TTS_queue = queue.Queue()
# Start the worker thread
worker_thread = threading.Thread(
target=process_TTS_queue, args=(TTS_queue,), daemon=True
)
worker_thread.start()
response = ""
for chunk in stream:
print(NEON_GREEN + chunk["message"]["content"], end="", flush=True)
chunk_text = chunk["message"]["content"]
response = f"{response}{chunk_text}"
if any(delimiter in response for delimiter in ".;,!?"):
response = response[1:] # Remove the first character
sentence, response = split_sentence(response)
TTS_queue.put(sentence)
# Print the response
print(RESET_COLOR + "\n")
return response
"""
###### ######## ####### #######
## ## ## ## ## ## ## ##
## ## ## ## ## ## ##
## #### ######## ## ## ## ##
## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ##
###### ## ## ####### ##### ##
"""
# Initialize Groq client
client = Groq(
api_key="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",
)
def groq_chat(
user_input,
system_message,
groq_model,
conversation_history,
):
# Get relevant context from Milvus
relevant_context = get_relevant_context(user_input, top_k=5)
if relevant_context:
print(
"Context Pulled from Documents: \n\n"
+ CYAN
+ relevant_context
+ RESET_COLOR
+ "\n\n"
)
else:
print("No relevant context found.")
# Prepare the user's input by concatenating it with the relevant context
user_input_with_context = user_input
if relevant_context:
user_input_with_context = relevant_context + "\n\n" + user_input
# Reset conversation history
conversation_history = []
# Append the user's input to the conversation history
conversation_history.append({"role": "user", "content": user_input_with_context})
# Create a message history including the system message and the conversation history
messages = [
{"role": "system", "content": system_message},
*conversation_history,
{"role": "user", "content": user_input},
]
stream = client.chat.completions.create(
#
# Required parameters
#
messages=messages,
# The language model which will generate the completion.
model=groq_model,
# Optional parameters
# Controls randomness: lowering results in less random completions.
# As the temperature approaches zero, the model will become deterministic
# and repetitive.
temperature=1,
# The maximum number of tokens to generate. Requests can use up to
# 2048 tokens shared between prompt and completion.
max_tokens=7999,
# Controls diversity via nucleus sampling: 0.5 means half of all
# likelihood-weighted options are considered.
top_p=1,
# A stop sequence is a predefined or user-specified text string that
# signals an AI to stop generating content, ensuring its responses
# remain focused and concise. Examples include punctuation marks and
# markers like "[end]".
stop="",
# If set, partial message deltas will be sent.
stream=True,
)
# Queue for sentences
TTS_queue = queue.Queue()
# Start the worker thread
worker_thread = threading.Thread(
target=process_TTS_queue, args=(TTS_queue,), daemon=True
)
worker_thread.start()
response = ""
print(NEON_GREEN)
for chunk in stream:
print(chunk.choices[0].delta.content, end="")
chunk_text = chunk.choices[0].delta.content
response = f"{response}{chunk_text}"
if any(delimiter in response for delimiter in ".;!?"):
response = response[1:] # Remove the first character
sentence, response = split_sentence(response)
TTS_queue.put(sentence)
# Print the response
print(RESET_COLOR + "\n")
return response
"""
###### ######## ## ## ######## ######## ## ## ###### ########
## ## ## ### ## ## ## ### ## ## ## ##
## ## #### ## ## ## #### ## ## ##
###### ###### ## ## ## ## ###### ## ## ## ## ######
## ## ## #### ## ## ## #### ## ##
## ## ## ## ### ## ## ## ### ## ## ##
###### ######## ## ## ## ######## ## ## ###### ########
"""
# Define the function to split sentences
def split_sentence(response):
# delimiters = r"[.,;!?]" # Add more delimiters if needed
delimiters = r"[\n]" # Add more delimiters if needed
sentences = re.split(delimiters, response, maxsplit=1)
if len(sentences) > 1:
sentence, response = sentences[0], sentences[1]
else:
sentence, response = sentences[0], ""
return sentence, response
"""
###### ####### ## ## ######## ######## ## ## ########
## ## ## ## ### ## ## ## ## ## ##
## ## ## #### ## ## ## ## ## ##
## ## ## ## ## ## ## ###### ### ##
## ## ## ## #### ## ## ## ## ##
## ## ## ## ## ### ## ## ## ## ##
###### ####### ## ## ## ######## ## ## ##
"""
def get_relevant_context(rewritten_input, top_k=5):
try:
relevant_context = ""
# collection.load()
# Encode the rewritten input
input_embedding = ollama.embeddings(
model=model,
prompt=rewritten_input,
keep_alive=-1,
)["embedding"]
# Perform similarity search
search_result = collection.search(
data=[input_embedding],
anns_field="embedding",
param={
"metric_type": "IP",
"params": {}, # Search parameters
}, # Search parameters
limit=5,
output_fields=["text"], # Fields to return in the search results
consistency_level="Bounded",
)
# len(search_result)
if search_result:
all_titles = [hit.entity.get("text") for hit in search_result[0]]
# Assuming you have a list of titles in `all_titles`
relevant_context = "\n\n".join(all_titles)
"""
# Extract top_k results
top_k_results = search_result[0] # Assuming single query
relevant_context = [result.entity["text"] for result in top_k_results]
"""
# Disconnect from Milvus
connections.disconnect(alias="html_chunks")
return relevant_context
except Exception as e:
print(f"An error occurred: {e}")
return "answer this yourself!"
"""
## ### ## ## ### ###### ######## ### ######## ########
## ## ## ### ### ## ## ## ## ## ## ## ## ## ##
## ## ## #### #### ## ## ## ## ## ## ## ## ##
## ## ## ## ### ## ## ## ###### ## ## ## ######## ##
## ######### ## ## ######### ## ## ######### ## ## ##
## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
######## ## ## ## ## ## ## ###### ## ## ## ## ## ##
"""
def check_and_start_ollama():
try:
# Check if Ollama is serving by attempting to connect to the server
response = subprocess.run(
["curl", "-I", "http://127.0.0.1:11434/"],
capture_output=True,
text=True,
check=True,
)
# Check if the response indicates the server is up
if "HTTP/1.1 200 OK" in response.stdout:
print("Ollama is already serving.")
else:
start_ollama_server()
except subprocess.CalledProcessError:
start_ollama_server()
except Exception as e:
print(f"An error occurred: {e}")
def start_ollama_server():
# Redirect output to devnull to suppress it
with open(os.devnull, "w") as devnull:
subprocess.Popen(["ollama", "serve"], stdout=devnull, stderr=devnull)
print("Ollama has been started.")
print("Enter your message (or 'exit' to quit):")
"""
######## ###### ## ## ######## ## ## ## ## ## ###### ###### ## ## ## ##
## ## ## ## ## ## ## ## ### ### ## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## #### #### ## ## ## ## ## ## ## ## ##
## ## ## ##### ######## ## ### ## ## ## ## ###### ## ######### #####
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
######## ###### ## ## ## ## ## ## ######## ### ###### ###### ## ## ## ##
"""
def is_docker_running():
try:
# Run the `docker info` command to check if Docker is running
result = subprocess.run(
["docker", "info"], stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
if result.returncode == 0:
print("Docker is running")
return True
else:
print("Docker is not running")
return False
except FileNotFoundError:
# Docker command not found
return False
def is_Milvus_running():
load_state_str = "None"
try:
Milvus_collection_Client = MilvusClient(uri="http://localhost:19530")
collection_name = "html_chunks"
collection_load_state = Milvus_collection_Client.get_load_state(collection_name)
load_state_str = str(collection_load_state["state"])
print("Milvus is", load_state_str)
if load_state_str == "Loaded":
return True
elif load_state_str == "Loading":
time.sleep(10) # Wait 10 seconds and recheck
return is_Milvus_running()
elif load_state_str == "NotLoad":
print(f"Collection {collection_name} is not loaded.")
# Optionally, you can trigger a load operation here
return False
elif load_state_str == "NotExist":
print(f"Collection {collection_name} does not exist.")
# Handle the case where the collection does not exist
return False
else:
print(f"Unknown load state: {load_state_str}")
return False
except Exception as e:
print(f"Error checking Milvus state: {e}")
return False
def start_docker_milvus():
try:
subprocess.run(
["docker-compose", "up", "-d"],
cwd="C:\\Users\\deletable\\OneDrive\\easy-local-rag",
check=True,
)
print("Milvus started using Docker.")
except subprocess.CalledProcessError as e:
print(f"Failed to start Milvus with Docker: {e}")
"""
## ## ### #### ## ##
### ### ## ## ## ### ##
#### #### ## ## ## #### ##
## ### ## ## ## ## ## ## ##
## ## ######### ## ## ####
## ## ## ## ## ## ###
## ## ## ## #### ## ##
"""
def main():
global collection
parser = argparse.ArgumentParser(description="Ollama Chat")
parser.add_argument(
"--model", default="phi3", help="Ollama model to use phi3 (default: llama3)"
)
args = parser.parse_args()
# Example conversation history
conversation_history = [{"role": "system", "content": "Welcome to Ollama Chat!"}]
# Start the Ollama server in a separate thread
ollama_thread = threading.Thread(target=check_and_start_ollama)
ollama_thread.start()
# Connect to Milvus
connections.connect(host="localhost", port="19530")
collection = Collection(name="html_chunks")
if not is_docker_running():
print("start docker")
elif not is_Milvus_running():
start_docker_milvus()
while True:
user_input = input(
"\n"
+ RED
+ BOLD
+ "Enter your message (or 'exit' to quit):"
+ "\n"
+ RESET_COLOR
+ "\n"
)
if user_input.lower() == "exit" or user_input.lower() == "quit":
break
system_message = "You are a helpful assistant. You will give precise and concise answers from the given context. if the context doesnot have the answer then give it from your knowledge"
# Interact with the Ollama model
if user_input:
chat_with_model(
user_input,
system_message,
groq_model,
ollama_model,
conversation_history=conversation_history,
)
if __name__ == "__main__":
main()