-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
858 lines (729 loc) Β· 31.9 KB
/
app.py
File metadata and controls
858 lines (729 loc) Β· 31.9 KB
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
import os
import chainlit as cl
import asyncio
import tempfile
from pathlib import Path
import sys
import socket
import psutil
import time
import requests
import logging
import traceback
# Configure logging
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# Add the RAG-Agent source code to the Python path
rag_agent_path = os.path.join(os.path.dirname(__file__), "rag-agent/src")
sys.path.append(rag_agent_path)
try:
# Import Ollama with error handling
import ollama
logger.info("Successfully imported ollama package")
except ImportError as e:
logger.error(f"Failed to import ollama package: {str(e)}")
sys.exit(1)
try:
# Import local modules from the rag-agent source
from ollama_pure_chat import OllamaChat
from fileloader import Loader_Local
logger.info("Successfully imported modules from rag-agent")
except ImportError as e:
logger.error(f"Failed to import modules from rag-agent: {str(e)}")
sys.exit(1)
# Initialize global variables
loader = None
chat_instance = None
default_model = "llama3.2:latest"
file_collections = {}
available_models = []
initialization_lock = False
# Check if Ollama API is available
def is_ollama_available():
try:
response = requests.get("http://localhost:11434/api/tags", timeout=2)
return response.status_code == 200
except:
return False
# Initialize the loader only once
def init_loader():
global loader
if loader is None:
try:
loader = Loader_Local()
logger.info("Successfully initialized Loader_Local")
return True
except Exception as e:
logger.error(f"Failed to initialize Loader_Local: {str(e)}")
return False
return True
# Process file uploads
async def process_file(file):
global loader
if not init_loader():
await cl.Message(
author="System",
content="Document loader could not be initialized. Cannot process files."
).send()
return False
logger.info(f"Processing uploaded file: {file.name}")
# Create a temporary file
temp_dir = tempfile.mkdtemp()
temp_file_path = os.path.join(temp_dir, file.name)
try:
# For chainlit latest versions, we need to access the file content differently
# Try different approaches based on what's available in the File object
try:
# Try direct file path approach if available
if hasattr(file, 'path'):
# If file has a path attribute, just copy the file
with open(file.path, 'rb') as src_file:
file_content = src_file.read()
# Try content attribute
elif hasattr(file, 'content'):
file_content = file.content
# Try to get as bytes
elif hasattr(file, 'get_bytes'):
file_content = await file.get_bytes()
# Last resort - try direct content
else:
logger.info(f"File object attributes: {dir(file)}")
raise AttributeError(f"Could not find a way to access file content. Available attributes: {dir(file)}")
except Exception as file_err:
logger.error(f"Error accessing file content: {str(file_err)}")
await cl.Message(
author="System",
content=f"Error accessing file content: {str(file_err)}. Please try a different file format."
).send()
return False
# Write the file content
with open(temp_file_path, "wb") as f:
f.write(file_content)
# Get file extension
file_extension = Path(file.name).suffix.lstrip(".").lower()
# Create a collection name
collection_name = f"collection_{file.id}"
# Process the file
loader.create_or_insert_collection(
temp_file_path,
collection_name,
extension=file_extension,
parser_type='local_parser'
)
# Store the collection name
file_collections[file.id] = collection_name
logger.info(f"File processed successfully: {file.name}")
await cl.Message(
author="System",
content=f"File '{file.name}' uploaded and processed successfully. You can now ask questions about this document.",
).send()
return True
except Exception as e:
logger.error(f"Error processing file: {str(e)}\n{traceback.format_exc()}")
await cl.Message(
author="System",
content=f"Error processing file '{file.name}': {str(e)}",
).send()
return False
finally:
# Clean up
try:
if os.path.exists(temp_file_path):
os.remove(temp_file_path)
if os.path.exists(temp_dir):
os.rmdir(temp_dir)
except Exception as cleanup_error:
logger.warning(f"Failed to clean up temporary files: {str(cleanup_error)}")
# Function to show model selection UI
async def show_model_selection():
global available_models
current_model = cl.user_session.get("selected_model")
# Display model options as a simple text list
models_list = "\n".join([f"- `/model {model}`" + (" (current)" if model == current_model else "") for model in available_models])
await cl.Message(
author="System",
content=f"""
### Available Models:
{models_list}
To select a model, type `/model modelname` (for example: `/model {available_models[0]}`)
"""
).send()
# Create a persistent database toggle button
async def setup_toggle_button():
# Get current state
enable_retrieval = cl.user_session.get("enable_retrieval", True)
# Create icon and label based on state
icon = "π" if enable_retrieval else "π«"
status = "ON" if enable_retrieval else "OFF"
# Create a pinned message with the toggle info
toggle_message = cl.Message(
author="", # Empty author for a cleaner look
content=f"{icon} **Database Retrieval: {status}**",
)
# Add the toggle action
toggle_message.actions = [
cl.Action(
name="toggle_retrieval",
label=f"{'Turn OFF' if enable_retrieval else 'Turn ON'} Retrieval",
value="toggle",
payload={"current_state": enable_retrieval}
),
cl.Action(
name="show_models_dropdown",
label=f"π€ Select Model",
value="show_models"
),
cl.Action(
name="show_chunks_slider",
label=f"π Set Chunks",
value="show_chunks"
)
]
# Send the toggle message
sent_message = await toggle_message.send()
# Store the message ID for reference
cl.user_session.set("toggle_id", sent_message.id)
return sent_message.id
# Function to handle button click to toggle retrieval on/off
@cl.action_callback("toggle_retrieval")
async def toggle_retrieval_callback(action):
# Toggle the state
current_state = cl.user_session.get("enable_retrieval", True)
new_state = not current_state
cl.user_session.set("enable_retrieval", new_state)
# Get the icon and status based on the new state
icon = "π" if new_state else "π«"
status = "ON" if new_state else "OFF"
# Create a new toggle message
toggle_message = cl.Message(
author="", # Empty author for a cleaner look
content=f"{icon} **Database Retrieval: {status}**",
)
# Add the toggle action
toggle_message.actions = [
cl.Action(
name="toggle_retrieval",
label=f"{'Turn OFF' if new_state else 'Turn ON'} Retrieval",
value="toggle",
payload={"current_state": new_state}
),
cl.Action(
name="show_models_dropdown",
label=f"π€ Select Model",
value="show_models"
),
cl.Action(
name="show_chunks_slider",
label=f"π Set Chunks",
value="show_chunks"
)
]
# Send the new toggle message
new_toggle = await toggle_message.send()
# Update the stored message ID
cl.user_session.set("toggle_id", new_toggle.id)
# Send a temporary notification about the change
await cl.Message(
author="System",
content=f"{icon} Database retrieval has been turned **{status}**",
type="info"
).send()
# Function to display model selection dropdown
@cl.action_callback("show_models_dropdown")
async def show_models_dropdown(action):
global available_models
current_model = cl.user_session.get("selected_model", default_model)
# Create a message with model selection options
model_msg = cl.Message(
author="",
content="### Select a Model:"
)
# Create action buttons for each model option
model_actions = []
for model in available_models:
model_actions.append(
cl.Action(
name="select_model",
label=f"{model} {'β' if model == current_model else ''}",
value=model,
payload={"model": model}
)
)
model_msg.actions = model_actions
await model_msg.send()
# Function to display chunks slider
@cl.action_callback("show_chunks_slider")
async def show_chunks_slider(action):
# Get current number of chunks
current_chunks = cl.user_session.get("num_results", 5)
# Create a slider element
chunks_slider = cl.Slider(
id="chunks_slider",
label="Number of chunks to retrieve",
initial=current_chunks,
min=1,
max=20,
step=1
)
# Create a message with the slider
slider_msg = cl.Message(
author="System",
content="### Set Number of Document Chunks to Retrieve",
elements=[chunks_slider]
)
await slider_msg.send()
# Function to handle slider change
@cl.on_slider_change
async def on_slider_change(slider):
if slider.id == "chunks_slider":
# Update the number of chunks to retrieve
cl.user_session.set("num_results", slider.value)
# Send confirmation message
await cl.Message(
author="System",
content=f"π Number of document chunks to retrieve set to: **{slider.value}**",
type="info"
).send()
# Function to handle model selection
@cl.action_callback("select_model")
async def select_model_callback(action):
global chat_instance, available_models
# Get the selected model from the payload
model_name = action.payload.get("model")
if model_name and model_name in available_models:
current_model = cl.user_session.get("selected_model")
# Only change if different
if model_name != current_model:
cl.user_session.set("selected_model", model_name)
try:
# Initialize chat with the new model
chat_instance = OllamaChat(
model=model_name,
system_prompt="You are a helpful chatbot assistant designed to answer questions about the given context. Context: <context> \nYou can answer questions about the given chat history."
)
# Confirm the change
await cl.Message(
author="System",
content=f"π€ Model changed to: **{model_name}**"
).send()
# Update the toggle button to reflect the change
await setup_toggle_button()
logger.info(f"Model changed to: {model_name}")
except Exception as e:
logger.error(f"Error changing model: {str(e)}")
await cl.Message(
author="System",
content=f"β Error changing model: {str(e)}"
).send()
else:
# Model is already selected
await cl.Message(
author="System",
content=f"Model **{model_name}** is already selected."
).send()
@cl.on_chat_start
async def on_chat_start():
global chat_instance, available_models, initialization_lock, loader
# Prevent concurrent initializations
if initialization_lock:
logger.info("Initialization already in progress, skipping")
return
initialization_lock = True
try:
# Initialize the loader
if not init_loader():
await cl.Message(
author="System",
content="Failed to initialize document loader. Some features may not work correctly."
).send()
# Check if Ollama API is available
if not is_ollama_available():
await cl.Message(
author="System",
content="Could not connect to Ollama API. Please make sure Ollama is running at http://localhost:11434"
).send()
initialization_lock = False
return
# Set up session
cl.user_session.set("chat_history", [])
# Set default value for database retrieval toggle (on by default)
cl.user_session.set("enable_retrieval", True)
# Set default number of chunks to retrieve
cl.user_session.set("num_results", 5)
# Get available models from Ollama
try:
models_response = ollama.list()
logger.info(f"Ollama models response: {models_response}")
# Extract models directly from the response
available_models = []
# Check if the response is a list of Model objects
if isinstance(models_response, list):
for model in models_response:
if hasattr(model, 'model'):
available_models.append(model.model)
elif isinstance(model, dict) and 'model' in model:
available_models.append(model['model'])
elif isinstance(model, dict) and 'name' in model:
available_models.append(model['name'])
# If it has 'models' attribute like in older versions
elif hasattr(models_response, 'models'):
models_list = models_response.models
for model in models_list:
if hasattr(model, 'model'):
available_models.append(model.model)
elif isinstance(model, dict) and 'model' in model:
available_models.append(model['model'])
elif isinstance(model, dict) and 'name' in model:
available_models.append(model['name'])
# If it's a dict with 'models' key
elif isinstance(models_response, dict) and 'models' in models_response:
models_list = models_response['models']
for model in models_list:
if isinstance(model, dict) and 'name' in model:
available_models.append(model['name'])
elif isinstance(model, dict) and 'model' in model:
available_models.append(model['model'])
elif hasattr(model, 'name'):
available_models.append(model.name)
elif hasattr(model, 'model'):
available_models.append(model.model)
# Manual extraction from the string representation as last resort
if not available_models and isinstance(models_response, str):
import re
model_matches = re.findall(r"model='([^']+)'", models_response)
available_models.extend(model_matches)
# Try direct string parsing if all else fails
if not available_models and hasattr(models_response, '__str__'):
models_str = str(models_response)
logger.info(f"Trying to extract from string representation: {models_str}")
# Extract anything that looks like model='...'
import re
model_matches = re.findall(r"model='([^']+)'", models_str)
available_models.extend(model_matches)
# Also try to match model="..."
model_matches = re.findall(r'model="([^"]+)"', models_str)
available_models.extend(model_matches)
logger.info(f"Found {len(available_models)} Ollama models: {available_models}")
# If we couldn't extract any models, use defaults
if not available_models:
available_models = ["llama3.2:latest", "llama3:latest", "mistral:latest"]
logger.warning(f"Could not extract models from response, using defaults: {available_models}")
except Exception as e:
logger.error(f"Failed to fetch models: {str(e)}")
logger.error(f"Error details: {traceback.format_exc()}")
available_models = ["llama3.2:latest", "llama3:latest", "mistral:latest"]
# Remove duplicates and sort models alphabetically
available_models = sorted(list(set(available_models)))
logger.info(f"Unique available models: {available_models}")
# Make sure we have at least one model
if not available_models:
available_models = ["llama3.2:latest", "llama3:latest", "mistral:latest"]
# Set default model initially
model_name = default_model if default_model in available_models else available_models[0]
cl.user_session.set("selected_model", model_name)
# Create welcome message
await cl.Message(
author="System",
content="# Welcome to RAG-Agent Chat!"
).send()
# Setup the toggle button interface
await setup_toggle_button()
# Initialize chat with the default model
try:
chat_instance = OllamaChat(
model=model_name,
system_prompt="You are a helpful chatbot assistant designed to answer questions about the given context. Context: <context> \nYou can answer questions about the given chat history."
)
# Display instructions for uploading documents
await cl.Message(
author="System",
content=f"""
### Getting Started
- Upload documents using the upload button
- Ask questions about your documents
- Use the toggle at the top to turn database retrieval ON/OFF
- Click "Select Model" to change models
- Click "Set Chunks" to adjust how many document chunks to retrieve (default: 5)
Currently using model: **{model_name}**
"""
).send()
logger.info(f"Chat initialized with default model: {model_name}")
except Exception as e:
logger.error(f"Error initializing chat with model {model_name}: {str(e)}")
await cl.Message(
author="System",
content=f"Error initializing chat with model {model_name}: {str(e)}. Please select a different model.",
).send()
except Exception as e:
logger.error(f"Error in on_chat_start: {str(e)}\n{traceback.format_exc()}")
await cl.Message(
author="System",
content="An error occurred while starting the chat. Please refresh the page and try again.",
).send()
finally:
initialization_lock = False
@cl.on_message
async def on_message(message: cl.Message):
global chat_instance, loader, available_models
# Make sure loader is initialized
if not init_loader():
await cl.Message(
author="System",
content="Document loader is not initialized. File-based questions may not work correctly."
).send()
# Get chat history and user question
chat_history = cl.user_session.get("chat_history", [])
question = message.content
# Legacy text commands for retrieval toggle
if question.strip().lower() == "/retrieval on":
cl.user_session.set("enable_retrieval", True)
await cl.Message(
author="System",
content="π **Database retrieval has been turned ON.** Your questions will now use document context."
).send()
# Update the toggle icon
await setup_toggle_button()
return
if question.strip().lower() == "/retrieval off":
cl.user_session.set("enable_retrieval", False)
await cl.Message(
author="System",
content="π« **Database retrieval has been turned OFF.** Your questions will only use chat history."
).send()
# Update the toggle icon
await setup_toggle_button()
return
# Check for command to show model selection UI
if question.strip().lower() == "/models":
await show_model_selection()
return
# Check for command to change model
if question.startswith("/model "):
model_name = question[7:].strip()
if model_name in available_models:
cl.user_session.set("selected_model", model_name)
try:
chat_instance = OllamaChat(
model=model_name,
system_prompt="You are a helpful chatbot assistant designed to answer questions about the given context. Context: <context> \nYou can answer questions about the given chat history."
)
# Send model confirmation message
await cl.Message(
author="System",
content=f"Model changed to: **{model_name}**"
).send()
# Update the toggle button to reflect the change
await setup_toggle_button()
logger.info(f"Model changed to: {model_name}")
except Exception as e:
logger.error(f"Error changing model: {str(e)}")
await cl.Message(
author="System",
content=f"Error changing model: {str(e)}"
).send()
else:
await cl.Message(
author="System",
content=f"Model '{model_name}' not available. Please select from one of these models:"
).send()
await show_model_selection()
return
# Check for clear context command
if question.strip().lower() == "/clear":
cl.user_session.set("chat_history", [])
file_collections.clear()
await cl.Message(
author="System",
content="Chat context and document references have been cleared. You're starting with a fresh conversation."
).send()
return
# Check for help command
if question.strip().lower() == "/help":
help_text = """
# RAG-Agent Chat Help
## Available Commands:
- `/clear` - Clear conversation history and context
- `/help` - Show this help message
## UI Controls:
- π Toggle button - Turn database retrieval ON/OFF
- π€ Select Model button - Choose from available models
- π Set Chunks button - Adjust number of document chunks to retrieve
## Features:
- Chat with selected Ollama model
- Upload documents to ask questions about them
- Use the toggle at the top of the chat to enable/disable database retrieval
- Change models anytime using the Select Model button
- Context is maintained throughout your session
## Tips:
- Upload multiple files to build a larger knowledge base
- Be specific with your questions for better answers
- Toggle database retrieval off if you want pure model responses
- Clear context if you want to start fresh
"""
await cl.Message(author="System", content=help_text).send()
return
# Check if we have file attachments - process them first
try:
has_files = False
# Check if files exist using different Chainlit versions' approaches
if hasattr(message, 'elements') and message.elements:
file_elements = [e for e in message.elements if hasattr(e, 'type') and e.type == 'file']
has_files = len(file_elements) > 0
# Try files attribute (newer Chainlit)
elif hasattr(message, 'files') and message.files:
file_elements = message.files
has_files = len(file_elements) > 0
# Try attachments attribute (alternative name)
elif hasattr(message, 'attachments') and message.attachments:
file_elements = message.attachments
has_files = len(file_elements) > 0
# Process files if found
if has_files:
logger.info(f"Found {len(file_elements)} files in message")
for file_element in file_elements:
await process_file(file_element)
# If this is just a file upload message with no question, return
if not question.strip():
return
except Exception as file_err:
logger.error(f"Error processing message attachments: {str(file_err)}\n{traceback.format_exc()}")
await cl.Message(
author="System",
content=f"Error processing attached files: {str(file_err)}"
).send()
# Get the selected model
selected_model = cl.user_session.get("selected_model", default_model)
# Check if Ollama is running
if not is_ollama_available():
await cl.Message(
author="System",
content="Could not connect to Ollama API. Please make sure Ollama is running."
).send()
return
# Make sure chat instance is initialized
if not chat_instance or chat_instance.model != selected_model:
try:
chat_instance = OllamaChat(
model=selected_model,
system_prompt="You are a helpful chatbot assistant designed to answer questions about the given context. Context: <context> \nYou can answer questions about the given chat history."
)
except Exception as e:
logger.error(f"Error initializing chat instance: {str(e)}")
await cl.Message(
author="System",
content=f"Error initializing chat: {str(e)}"
).send()
return
# Prepare the response message
msg = cl.Message(content="")
await msg.send()
# Only build context if retrieval is enabled
context = ""
enable_retrieval = cl.user_session.get("enable_retrieval", True)
retrieved_context_elements = []
if enable_retrieval and file_collections:
# Create a message in the UI to show we're retrieving context
retrieval_status = await cl.Message(
author="System",
content="π Retrieving relevant context...",
type="info"
).send()
# Create an element to display retrieved context in a separate panel
context_element = cl.Text(
name="context_panel",
content="",
display="side" # Make sure this is "side" not "sidebar"
)
try:
context_chunks = []
for collection_name in set(file_collections.values()):
try:
# Get the number of results to retrieve from the slider setting
num_results = cl.user_session.get("num_results", 5)
results = loader(question, collection_name, num_results)
if results and 'documents' in results and results['documents']:
# Add documents to the context for the model
for i, doc in enumerate(results['documents'][0]):
# Add to context for the model
context += f"doc_{i}: {doc}\n"
# Add the full document to the context chunks for display
context_chunks.append(f"**Document Chunk {i+1}:**\n{doc}")
except Exception as e:
logger.error(f"Error retrieving from collection {collection_name}: {str(e)}")
logger.info(f"Context chunks: {context_chunks}")
# If we found any context, display it in the side panel
if len(context_chunks)>0:
formatted_context = "\n\n".join(context_chunks)
# Save the retrieved context to a text file
timestamp = time.strftime("%Y%m%d-%H%M%S")
filename = f"retrieved_context_{timestamp}.txt"
try:
with open(filename, "w") as f:
f.write(f"# Retrieved Context for Query: {question}\n\n")
f.write(formatted_context)
logger.info(f"Context saved to {filename}")
# Create a downloadable element for the saved context
download_element = cl.Text(
name="download_context",
content=f"Context saved to {filename}. You can download it from your server.",
display="inline"
)
await download_element.send()
except Exception as e:
logger.error(f"Error saving context to file: {str(e)}")
context_element.content = f"# Retrieved Context\n\n{formatted_context}"
await context_element.send(for_id=retrieval_status.id)
# Update the retrieval status
val=min
await retrieval_status.update(content=f"π Found {st.session_state.topk} and enhanced to {len(context_chunks)} relevant document chunks.")
else:
# No context found
await retrieval_status.update(content="π No relevant document chunks found for this query.")
except Exception as e:
logger.error(f"Error displaying context: {str(e)}")
await retrieval_status.update(content=f"β Error retrieving context: {str(e)}")
# Generate response
try:
full_response = ""
async for chunk in chat_instance.chat_async(question, chat_history, context=context):
full_response += chunk
await msg.stream_token(chunk)
# Update chat history
chat_history.append(f"User: {question}\n{full_response}")
# Keep only the last 10 interactions
if len(chat_history) > 10:
chat_history = chat_history[-10:]
cl.user_session.set("chat_history", chat_history)
except Exception as e:
logger.error(f"Error generating response: {str(e)}\n{traceback.format_exc()}")
await msg.stream_token(f"\n\nError: {str(e)}")
# Complete the message
await msg.update()
@cl.action_callback("help")
async def on_help(action):
help_text = """
# RAG-Agent Chat Help
## Available Commands:
- `/clear` - Clear conversation history and context
- `/help` - Show this help message
## UI Controls:
- π Toggle button - Turn database retrieval ON/OFF
- π€ Select Model button - Choose from available models
- π Set Chunks button - Adjust number of document chunks to retrieve
## Features:
- Chat with selected Ollama model
- Upload documents to ask questions about them
- Use the toggle at the top of the chat to enable/disable database retrieval
- Change models anytime using the Select Model button
- Context is maintained throughout your session
## Tips:
- Upload multiple files to build a larger knowledge base
- Be specific with your questions for better answers
- Toggle database retrieval off if you want pure model responses
- Clear context if you want to start fresh
"""
await cl.Message(author="System", content=help_text).send()
if __name__ == "__main__":
logger.info("Starting RAG-Agent Chat application")
cl.run()