-
Notifications
You must be signed in to change notification settings - Fork 11
/
tools.py
1613 lines (1320 loc) · 71.7 KB
/
tools.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
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
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import concurrent.futures
import io
import json
import os
import random
import re
import tempfile
import pypandoc
import textwrap
import urllib
import uuid
from datetime import datetime
from urllib.parse import urlparse
import arxiv
import wikipedia
from duckduckgo_search import DDGS
from selenium import webdriver
from pydub import AudioSegment
from libs import load_json_config, mark_down_formatting, between_xml_tag
from config import Config
from utils import Utils, ImageNotFoundError
class ToolError(Exception):
"""
Custom exception for tool-related errors.
Raised when there's an issue with tool execution or usage in the chat system.
Used to provide meaningful error messages to users or the system.
"""
pass
class Tools:
"""
Manages and executes tools for the chatbot.
Loads tool configurations from JSON, initializes utilities, and provides methods
to execute various tools based on tool name and input parameters.
Attributes:
config (Config): Configuration settings
state (dict): Current chatbot state
utils (Utils): Utility functions
tools_json (dict): Tool definitions loaded from JSON
tool_functions (dict): Mapping of tool names to handler functions
"""
def __init__(self, config: Config, state: dict, utils: Utils) -> None:
"""
Initialize Tools with configuration, state and utilities.
Args:
config (Config): Configuration settings
state (dict): Current chatbot state
utils (Utils): Utility functions
"""
self.config = config
self.state = state
self.utils = utils
self.tools_json = load_json_config('./Config/tools.json')
self.tool_functions = {
'python': self.get_tool_result_python,
'duckduckgo_text_search': self.get_tool_result_duckduckgo_text_search,
'duckduckgo_news_search': self.get_tool_result_duckduckgo_news_search,
'duckduckgo_maps_search': self.get_tool_result_duckduckgo_maps_search,
'duckduckgo_images_search': self.get_tool_result_duckduckgo_images_search,
'wikipedia_search': self.get_tool_result_wikipedia_search,
'wikipedia_geodata_search': self.get_tool_result_wikipedia_geodata_search,
'wikipedia_page': self.get_tool_result_wikipedia_page,
'browser': self.get_tool_result_browser,
'retrive_from_archive': self.get_tool_result_retrive_from_archive,
'store_in_archive': self.get_tool_result_store_in_archive,
'sketchbook': self.get_tool_result_sketchbook,
'checklist': self.get_tool_result_checklist,
'generate_image': self.get_tool_result_generate_image,
'search_image_catalog': self.get_tool_result_search_image_catalog,
'similarity_image_catalog': self.get_tool_result_similarity_image_catalog,
'random_images': self.get_tool_result_random_images,
'get_image_by_id': self.get_tool_result_get_image_by_id,
'image_catalog_count': self.get_tool_result_image_catalog_count,
'download_image_into_catalog': self.get_tool_result_download_image_into_catalog,
'personal_improvement': self.get_tool_result_personal_improvement,
'arxiv': self.get_tool_result_arxiv,
'save_text_file': self.get_tool_result_save_text_file,
'check_if_file_exists': self.get_tool_result_check_if_file_exists,
'conversation': self.get_tool_result_conversation,
}
self.check_tools_consistency()
def check_tools_consistency(self) -> None:
"""
Verify consistency between defined tools and their functions.
Compares tool names defined in tools_json against function names in tool_functions
to ensure there is a one-to-one correspondence.
Raises:
Exception: If there is a mismatch between defined tools and functions
"""
tools_set = set([ t['toolSpec']['name'] for t in self.tools_json])
tool_functions_set = set(self.tool_functions.keys())
if tools_set != tool_functions_set:
raise Exception(f"Tools and tool functions are not consistent: {tools_set} != {tool_functions_set}")
def get_tool_result(self, tool_use_block: dict) -> str:
"""
Execute a tool and return its result.
Args:
tool_use_block (dict): Tool execution info containing:
- name (str): Name of tool to execute
- input (dict): Input parameters for the tool
Returns:
tuple: Contains:
- str: Tool execution result
- str: Formatted tool name
- str: Additional metadata (optional)
Raises:
ToolError: If tool name is invalid or execution fails
"""
tool_use_name = tool_use_block['name']
print(f"Tool: {tool_use_name}")
try:
result = self.tool_functions[tool_use_name](tool_use_block['input'])
formatted_tool_use_name = '🛠️ ' + tool_use_name.replace('_', ' ').title()
if type(result) == tuple:
return result[0], formatted_tool_use_name, result[1]
else:
return result, formatted_tool_use_name, ''
except KeyError:
raise ToolError(f"Invalid function name: {tool_use_name}")
def get_tool_result_python(self, tool_input: dict) -> tuple[str, str]:
"""
Execute Python code using AWS Lambda.
Args:
tool_input (dict): Contains:
- script (str): Python code to execute
- install_modules (list): Python packages to install
- number_of_images (int): Expected number of images
- number_of_text_files (int): Expected number of text files
Returns:
tuple: Contains:
- str: Script output wrapped in XML tags
- str: Tool metadata including script, modules, timing info
- str: Additional warnings/errors if any
Note:
- Uses AWS Lambda for code execution
- Truncates output if exceeds MAX_OUTPUT_LENGTH
- Stores generated images in image catalog
"""
input_script = tool_input.get("script", "")
install_modules = tool_input.get("install_modules", [])
number_of_images = tool_input.get("number_of_images", 0)
number_of_text_files = tool_input.get("number_of_text_files", 0)
if type(install_modules) == str:
try:
install_modules = json.loads(install_modules)
except Exception as e:
error_message = f"Error: {e}"
print(error_message)
return error_message
print(f"Script:\n{input_script}")
print(f"Install modules: {install_modules}")
print(f"Number of images: {number_of_images}")
print(f"Number of text files: {number_of_text_files}")
event = {"input_script": input_script, "install_modules": install_modules}
print("Invoking Lambda function...")
result, elapsed_time = self.utils.invoke_lambda_function(self.config.AWS_LAMBDA_FUNCTION_NAME, event)
output = result.get("output", "")
images = result.get("images", [])
text_files = result.get("files", [])
len_output = len(output)
print(f"Output length: {len_output}")
print(f"Images: {len(images)}")
print(f"Text files: {len(text_files)}")
print(f"Elapsed time: {elapsed_time:.2f} seconds")
if len_output == 0:
warning_message = "No output printed."
print(warning_message)
return warning_message
if len_output > self.config.MAX_OUTPUT_LENGTH:
output = output[:self.config.MAX_OUTPUT_LENGTH] + "\n... (truncated)"
print(f"Output:\n---\n{output}\n---")
tool_metadata = f"```python\n{input_script}\n```\n```"
if len(install_modules) > 0:
tool_metadata += f"\nInstall modules: {install_modules}"
if number_of_images > 0:
tool_metadata += f"\nNumber of images: {number_of_images}"
if number_of_text_files > 0:
tool_metadata += f"\nNumber of text files: {number_of_text_files}"
tool_metadata += f"\nElapsed time: {elapsed_time:.2f} seconds\n```\n```\n{output}```"
if len(images) != number_of_images:
warning_message = f"Expected {number_of_images} images but {len(images)} found."
print(warning_message)
return f"{output}\n\n{warning_message}", f"{tool_metadata}\n```\n{warning_message}\n```"
if len(text_files) != number_of_text_files:
warning_message = f"Expected {number_of_text_files} text files but {len(text_files)} found."
print(warning_message)
return f"{output}\n\n{warning_message}", f"{tool_metadata}\n```\n{warning_message}\n```"
for text_file in images:
# Extract the image format from the file extension
image_path = text_file['path']
image_format = os.path.splitext(image_path)[1][1:] # Remove the leading dot
image_format = 'jpeg' if image_format == 'jpg' else image_format # Quick fix
image_base64 = self.utils.get_image_base64(text_file['base64'],
format=image_format,
max_image_size=self.config.MAX_CHAT_IMAGE_SIZE,
max_image_dimension=self.config.MAX_CHAT_IMAGE_DIMENSIONS)
image = self.utils.store_image(image_format, image_base64)
output += f"\nImage {image_path} has been stored in the image catalog with image_id: {image['id']}"
for text_file in text_files:
output += f"{between_xml_tag(text_file['content'], 'file', {'name': text_file['name']})}\n"
return f"{between_xml_tag(output, 'output')}", tool_metadata
def get_tool_result_duckduckgo_text_search(self, tool_input: dict) -> str:
"""
Perform a DuckDuckGo text search and store the results in the archive.
Args:
tool_input (dict): A dictionary containing the 'keywords' for the search.
Returns:
str: XML-tagged output containing the search results.
Note:
This function uses MAX_SEARCH_RESULTS from the config to limit the number of results.
It also adds the search results to the text index for future retrieval.
"""
search_keywords = tool_input.get("keywords", "")
print(f"Keywords: {search_keywords}")
try:
results = DDGS().text(search_keywords, max_results=self.config. MAX_SEARCH_RESULTS)
output = json.dumps(results)
except Exception as e:
error_message = f"Error: {e}"
print(error_message)
return error_message
output = output.strip()
print(f"Output length: {len(output)}")
tool_metadata = f"Keywords: {search_keywords}\nOutput length: {len(output)} characters"
return between_xml_tag(output, "output"), tool_metadata
def get_tool_result_duckduckgo_news_search(self, tool_input: dict) -> str:
"""
Perform a DuckDuckGo news search and store the results in the archive.
Args:
tool_input (dict): A dictionary containing the 'keywords' for the search.
Returns:
str: XML-tagged output containing the search results.
Note:
This function uses the global MAX_SEARCH_RESULTS to limit the number of results.
It also adds the search results to the text index for future retrieval.
"""
search_keywords = tool_input.get("keywords", "")
print(f"Keywords: {search_keywords}")
try:
results = DDGS().news(search_keywords, max_results=self.config.MAX_SEARCH_RESULTS)
output = json.dumps(results)
except Exception as e:
error_message = f"Error: {e}"
print(error_message)
return error_message
output = output.strip()
print(f"Output length: {len(output)}")
tool_metadata = f"Keywords: {search_keywords}\nOutput length: {len(output)} characters"
return between_xml_tag(output, "output"), tool_metadata
def get_tool_result_duckduckgo_maps_search(self, tool_input: dict) -> str:
"""
Perform a DuckDuckGo maps search and store the results in the archive.
Args:
tool_input (dict): A dictionary containing the 'keywords' and 'place' for the search.
Returns:
str: XML-tagged output containing the search results.
Note:
This function uses the global MAX_SEARCH_RESULTS to limit the number of results.
It also adds the search results to the text index for future retrieval.
"""
search_keywords = tool_input.get("keywords", "")
search_place = tool_input.get("place", "")
print(f"Keywords: {search_keywords}")
print(f"Place: {search_place}")
try:
results = DDGS().maps(
search_keywords, search_place, max_results=self.config.MAX_SEARCH_RESULTS
)
output = json.dumps(results)
except Exception as e:
error_message = f"Error: {e}"
print(error_message)
return error_message
output = output.strip()
print(f"Output length: {len(output)}")
tool_metadata = f"Keywords: {search_keywords}\nPlace: {search_place}\nOutput length: {len(output)} characters"
return between_xml_tag(output, "output"), tool_metadata
def get_tool_result_wikipedia_search(self, tool_input: dict) -> str:
"""
Perform a Wikipedia search and return the results.
Args:
tool_input (dict): A dictionary containing the 'query' for the search.
Returns:
str: XML-tagged output containing the search results.
Note:
This function uses the Wikipedia API to perform the search and returns
the results as a JSON string wrapped in XML tags.
"""
search_query = tool_input.get("query", "")
print(f"Query: {search_query}")
try:
results = wikipedia.search(search_query)
output = json.dumps(results)
except Exception as e:
error_message = f"Error: {e}"
print(error_message)
return error_message
output = output.strip()
print(f"Output: {output}")
print(f"Output length: {len(output)}")
tool_metadata = f"Query: {search_query}\nOutput length: {len(output)} characters"
return between_xml_tag(output, "output"), tool_metadata
def get_tool_result_duckduckgo_images_search(self, tool_input: dict) -> str:
"""
Perform a DuckDuckGo images search.
Args:
tool_input (dict): A dictionary containing the 'keywords' for the search.
Returns:
str: XML-tagged output containing the search results.
Note:
This function uses MAX_SEARCH_RESULTS from the config to limit the number of results.
It also adds the search results to the text index for future retrieval.
"""
search_keywords = tool_input.get("keywords", "")
print(f"Keywords: {search_keywords}")
try:
results = DDGS().images(search_keywords, license_image='Share', max_results=self.config.MAX_SEARCH_RESULTS)
output = json.dumps(results)
except Exception as e:
error_message = f"Error: {e}"
print(error_message)
return error_message
output = output.strip()
print(f"Output length: {len(output)}")
tool_metadata = f"Keywords: {search_keywords}\nOutput length: {len(output)} characters"
return between_xml_tag(output, "output"), tool_metadata
def get_tool_result_wikipedia_geodata_search(self, tool_input: dict) -> str:
"""
Perform a Wikipedia geosearch and return the results.
Args:
tool_input (dict): A dictionary containing the search parameters:
- latitude (float): The latitude of the search center.
- longitude (float): The longitude of the search center.
- title (str, optional): The title of a page to search for.
- radius (int, optional): The search radius in meters.
Returns:
str: XML-tagged output containing the search results as a JSON string.
Note:
This function uses the Wikipedia API to perform a geosearch and returns
the results as a JSON string wrapped in XML tags.
"""
latitude = tool_input.get("latitude", "")
longitude = tool_input.get("longitude", "")
search_title = tool_input.get("title", "") # Optional
radius = tool_input.get("radius", "") # Optional
print(f"Latitude: {latitude}")
print(f"Longitude: {longitude}")
print(f"Title: {search_title}")
print(f"Radius: {radius}")
try:
results = wikipedia.geosearch(
latitude=latitude, longitude=longitude, title=search_title, radius=radius
)
output = json.dumps(results)
except Exception as e:
error_message = f"Error: {e}"
print(error_message)
return error_message
output = output.strip()
print(f"Output: {output}")
print(f"Output length: {len(output)}")
tool_metadata = f"Latitude: {latitude}\nLongitude: {longitude}\nTitle: {search_title}\nRadius: {radius}\nOutput length: {len(output)} characters"
return between_xml_tag(output, "output"), tool_metadata
def get_tool_result_wikipedia_page(self, tool_input: dict) -> str:
"""
Retrieve and process a Wikipedia page, storing its content in the archive.
This function fetches a Wikipedia page based on the given title, converts its HTML content
to Markdown format, and stores it in the text index for future retrieval.
Args:
tool_input (dict): A dictionary containing the 'title' and 'keywords' keys with the Wikipedia page title and keywords for the search.
Returns:
str: A message indicating that the page content has been stored in the archive.
Note:
This function uses the wikipedia library to fetch page content and the mark_down_formatting
function to convert HTML to Markdown. It also uses add_to_text_index to store the content
in the archive with appropriate metadata.
"""
search_title = tool_input.get("title", "")
keywords = tool_input.get("keywords", "")
print(f"Title: {search_title}")
print(f"Keywords: {keywords}")
try:
page = wikipedia.page(title=search_title, auto_suggest=False)
page_text = mark_down_formatting(page.html(), page.url)
except Exception as e:
error_message = f"Error: {e}"
print(error_message)
return error_message
page_text = page_text.strip()
text_size = len(page_text)
print(f"Text size: {text_size}")
current_date = datetime.now().strftime("%Y-%m-%d")
metadata = {"wikipedia_page": search_title, "date": current_date}
metadata_delete = {"wikipedia_page": search_title}
self.utils.add_to_text_index(page_text, search_title, metadata, metadata_delete)
summary = self.retrieve_from_archive(search_title)
print(f"Summary length: {len(summary)}")
keywords_content = self.retrieve_from_archive(keywords)
print(f"Keywords content length: {len(keywords_content)}")
output = f"""The full content of the page ({text_size} characters) has been stored in the archive.
Retrieve more information from the archive using keywords or browse links to get more information.
Here is a summary of the page:
{between_xml_tag(summary, 'summary')}
Additional information based on your keywords:
{between_xml_tag(keywords_content, 'info')}"""
print(f"Output length: {len(output)}")
tool_metadata = f"Title: {search_title}\nKeywords: {keywords}\nText size: {text_size} characters\nSummary length: {len(summary)} characters\nKeywords content length: {len(keywords_content)} characters\nOutput length: {len(output)} characters"
return output, tool_metadata
def get_tool_result_browser(self, tool_input: dict) -> str:
"""
Retrieve and process content from a given URL using Selenium.
This function uses Selenium WebDriver to navigate to the specified URL,
retrieve the page content, convert it to Markdown format, and store it
in the text index for future retrieval.
Args:
tool_input (dict): A dictionary containing the 'url' key with the target URL.
Returns:
str: A message indicating that the content has been stored in the archive.
Note:
This function uses Selenium with Chrome in headless mode to retrieve page content.
It also uses mark_down_formatting to convert HTML to Markdown and add_to_text_index
to store the content in the archive with appropriate metadata.
"""
url = tool_input.get("url", "")
keywords = tool_input.get("keywords", "")
print(f"URL: {url}")
print(f"Keywords: {keywords}")
if not url.startswith("https://"):
error_message = "The URL must start with 'https://'."
print(error_message)
return error_message
parsed_url = urlparse(url)
url_file_extension = os.path.splitext(parsed_url.path)[1].lower().lstrip('.')
if url_file_extension in self.config.DOCUMENT_FORMATS:
# Handle document formats
print(f"Downloading and processing document: {url}")
try:
with urllib.request.urlopen(url) as response:
content = response.read()
print(f"Document size: {len(content)}")
download_size = len(content)
content_as_io_bytes = io.BytesIO(content)
if url_file_extension == 'pdf':
page_text = self.utils.process_pdf_document(content_as_io_bytes)
elif url_file_extension == 'pptx':
page_text = self.utils.process_pptx_document(content_as_io_bytes)
else:
raise Exception(f"Unsupported document format for browser: {url_file_extension}")
title = None
text_size = len(page_text)
except Exception as e:
error_message = f"Error downloading or processing the document: {str(e)}"
print(error_message)
return error_message
else:
options = webdriver.ChromeOptions()
options.add_argument("--headless=new")
options.add_argument("--incognito")
options.add_argument("--window-size=1920,1080")
with webdriver.Chrome(options=options) as driver:
try:
driver.get(url)
except Exception as e:
error_message = f"Error navigating to the URL: {e}"
print(error_message)
return error_message
title = driver.title
print(f"Title:", title)
page = driver.page_source
print(f"Page size:", len(page))
download_size = len(page)
page_text = mark_down_formatting(page, url)
text_size = len(page_text)
print(f"Markdown text length:", text_size)
if text_size < 10:
return "I am not able or allowed to get content from this URL."
hostname = parsed_url.hostname
current_date = datetime.now().strftime("%Y-%m-%d")
metadata = {"url": url, "hostname": hostname, "date": current_date}
metadata_delete = {"url": url} # To delete previous content from the same URL
self.utils.add_to_text_index(page_text, url, metadata, metadata_delete)
if title is not None and len(title) > 0:
summary = self.retrieve_from_archive(title + " - " + url)
print(f"Summary length: {len(summary)}")
else:
summary = ""
keywords_content = self.retrieve_from_archive(keywords)
print(f"Keywords content length: {len(keywords_content)}")
output = f"""The full content of the URL ({text_size} characters) has been stored in the archive.
Retrieve more information from the archive using keywords or browse links to get more information.
A summary of the page:
{between_xml_tag(summary, 'summary')}
Additional information based on your keywords:
{between_xml_tag(keywords_content, 'info')}"""
print(f"Output length: {len(output)}")
tool_metadata = f"URL: {url}\nKeywords: {keywords}\nDownload size: {download_size}\nText size: {text_size} characters\nSummary length: {len(summary)} characters\nKeywords content length: {len(keywords_content)} characters\nOutput length: {len(output)} characters"
return output, tool_metadata
def retrieve_from_archive(self, query: str) -> str:
"""
Retrieve content from the archive based on given query.
Args:
query (str): The keywords to search for.
state (dict): The current state of the chat interface.
Returns:
str: XML-tagged output containing the search results as a JSON string.
Note:
This function uses the utils.get_text_catalog_search method to search the text index.
It also keeps track of the archive ids in the state to avoid duplicates.
"""
text_embedding = self.utils.get_embedding(input_text=query)
query = {
"size": self.config.MAX_ARCHIVE_RESULTS,
"query": {"knn": {"embedding_vector": {"vector": text_embedding, "k": 5}}},
"_source": ["date", "url", "hostname", "document"],
}
try:
response = self.utils.get_text_catalog_search(query)
except Exception as ex:
error_message = f"Error: {ex}"
print(error_message)
return error_message
documents = ""
for value in response["hits"]["hits"]:
id = value["_id"]
source = value["_source"]
if id not in self.state["archive"]:
documents += between_xml_tag(json.dumps(source), "document", {"id": id}) + "\n"
self.state["archive"].add(id)
print(f"Retrieved documents length: {len(documents)}")
return between_xml_tag(documents, "documents")
def get_tool_result_retrive_from_archive(self, tool_input: dict) -> str:
"""
Retrieve content from the archive based on given keywords.
This function searches the text index using the provided keywords and returns
the matching documents.
Args:
tool_input (dict): A dictionary containing the 'keywords' to search for.
Returns:
str: XML-tagged output containing the search results as a JSON string.
Note:
This function uses the utils.get_text_catalog_search method to search the text index.
It also keeps track of the archive ids in the state to avoid duplicates.
"""
keywords = tool_input.get("keywords", "")
print(f"Keywords: {keywords}")
output = self.retrieve_from_archive(keywords)
print(f"Output length: {len(output)}")
tool_metadata = f"Keywords: {keywords}\nOutput length: {len(output)} characters"
return output, tool_metadata
def get_tool_result_store_in_archive(self, tool_input: dict) -> str:
"""
Store content in the archive.
This function takes the provided content and stores it in the text index
with the current date as metadata.
Args:
tool_input (dict): A dictionary containing the 'content' key with the text to be stored.
Returns:
str: A message indicating whether the content was successfully stored or an error occurred.
Note:
This function uses the utils.add_to_text_index method to store the content in the archive.
"""
content = tool_input.get("content", "")
if len(content) == 0:
return "You need to provide content to store in the archive."
else:
print(f"Content:\n---\n{content}\n---")
current_date = datetime.now().strftime("%Y-%m-%d")
metadata = {"date": current_date}
id = uuid.uuid4()
self.utils.add_to_text_index(content, id, metadata)
tool_metadata = f"Content length: {len(content)} characters\nContent: {content}"
return "The content has been stored in the archive.", tool_metadata
def render_sketchbook(self, sketchbook: dict, forPreview: bool = False) -> str:
processed_sketchbook = [self.utils.process_image_placeholders(section, forPreview) for section in sketchbook]
rendered_sketchbook = "\n\n".join(processed_sketchbook)
rendered_sketchbook = "\n" + re.sub(r'\n{3,}', '\n\n', rendered_sketchbook) + "\n"
return rendered_sketchbook
def render_sketchbook_from_id(self, id: str) -> str:
"""
Render a sketchbook as a single string, optionally using a new path for images.
Args:
sketchbook (list[str]): A list of strings, each representing a section in the sketchbook.
Returns:
str: A single string containing all sketchbook sections, properly formatted.
"""
sketchbook = self.state["sketchbook"][id]
return self.render_sketchbook(sketchbook)
def get_tool_result_sketchbook(self, tool_input: dict) -> str:
"""
Process a sketchbook command and update the sketchbook state accordingly.
This function handles various sketchbook operations such as starting a new sketchbook,
adding sections, reviewing sections, updating sections, and saving the sketchbook.
Args:
tool_input (dict): A dictionary containing the command and optional content.
Returns:
str: A message indicating the result of the operation.
Commands:
- start_new: Initializes a new empty sketchbook.
- add_section: Adds a new section to the sketchbook.
- start_review: Begins a review of the sketchbook from the first section.
- next_section: Moves to the next section during review.
- update_section: Updates the content of the current section.
- save_sketchbook_file: Saves the sketchbook to a file.
- info: Provides information about the sketchbook and current section.
Note:
This function uses the utils.render_sketchbook method to render the sketchbook.
It also keeps track of the sketchbook sections in the state.
"""
id = tool_input.get("id", "")
command = tool_input.get("command", "")
content = tool_input.get("content", "")
filename = tool_input.get("filename", "")
format = tool_input.get("format", "")
print(f"ID: {id}")
print(f"Command: {self.utils.format_string(command)}")
if len(content) > 0:
print(f"Content:\n---\n{content}\n---")
if len(filename) > 0:
print(f"Filename: {filename}")
if len(format) > 0:
print(f"Format: {format}")
if id not in self.state["sketchbook"] and command != "start_new_with_content":
sketchbook_list = "\n".join(self.state["sketchbook"].keys())
return f"Sketchbook not found. The following sketchbooks are available:\n{sketchbook_list}"
def get_sketchbook_info() -> str:
if id in self.state["sketchbook"]:
sketchbook = self.state["sketchbook"][id]
num_words = sum(len(section.split()) for section in sketchbook)
num_characters = sum(len(section) for section in sketchbook)
return f"The sketchbook has {num_sections} sections / {num_words} words / {num_characters} characters."
else:
return "Sketchbook not found."
def get_tool_metadata() -> str:
output = f"ID: {id}\nCommand: {command}"
if id in self.state["sketchbook"]:
output += f"\n{get_sketchbook_info()}"
return output
match command:
case "info":
return get_sketchbook_info(), get_tool_metadata()
case "start_new_with_content" | "add_section_at_the_end":
if command == "start_new_with_content":
self.state["sketchbook"][id] = []
self.state["sketchbook_current_section"][id] = 0
command_message = f"This is a new sketchbook with ID '{id}'."
else:
command_message = f"A new section has been added at the end of the sketchbook '{id}'."
if len(content) == 0:
return "You need to provide content to add a new section."
try:
_ = self.utils.process_image_placeholders(content)
except Exception as e:
error_message = f"Section not added. Error: {e}"
print(error_message)
return error_message
self.state["sketchbook"][id].append(content)
num_sections = len(self.state["sketchbook"][id])
self.state["sketchbook_current_section"][id] = num_sections - 1
output = f"{command_message}. You're now at section {self.state['sketchbook_current_section'][id] + 1} of {num_sections}. Add more sections ir start a review.\n{get_sketchbook_info()}"
return output, get_tool_metadata()
case "start_review":
num_sections = len(self.state["sketchbook"][id])
if num_sections == 0:
return "The sketchbook is empty. There are no sections to review or update. Start by adding some content."
self.state["sketchbook_current_section"][id] = 0
section_content = self.state["sketchbook"][id][0]
section_content_between_xml_tag = between_xml_tag(section_content, "section")
output = f"You're starting your review at section 1 of {num_sections}. This is the content of the current section:\n\n{section_content_between_xml_tag}\n\nUpdate the content of this section, delete the section, or go to the next section. The review is completed when you reach the end.\n{get_sketchbook_info()}"
return output, get_tool_metadata()
case "next_section":
num_sections = len(self.state["sketchbook"][id])
if self.state["sketchbook_current_section"][id] >= num_sections - 1:
return f"You're at the end. You're at section {self.state['sketchbook_current_section'][id] + 1} of {num_sections}."
self.state["sketchbook_current_section"][id] += 1
section_content = self.state["sketchbook"][id][self.state["sketchbook_current_section"][id]]
section_content_between_xml_tag = between_xml_tag(section_content, "section", {"id": self.state["sketchbook_current_section"][id]})
output = f"Moving to the next section. You're now at section {self.state['sketchbook_current_section'][id] + 1} of {num_sections}. This is the content of the current section:\n\n{section_content_between_xml_tag}\n\nUpdate the content of this section, delete the section, or go to the next section. The review is completed when you reach the end.\n{get_sketchbook_info()}"
return output, get_tool_metadata()
case "update_current_section":
num_sections = len(self.state["sketchbook"][id])
if num_sections == 0:
return "The sketchbook is empty. There are no sections. Start by adding some content."
if len(content) == 0:
return "You need to provide content to update the current section."
try:
_ = self.utils.process_image_placeholders(content)
except Exception as e:
error_message = f"Section not updated. Error: {e}"
print(error_message)
return error_message
self.state["sketchbook"][id][self.state["sketchbook_current_section"][id]] = content
output = f"The current section has been updated with the new content.\n{get_sketchbook_info()}"
return output, get_tool_metadata()
case "delete_current_section":
num_sections = len(self.state["sketchbook"][id])
if num_sections == 0:
return "The sketchbook is empty. There are no sections to delete."
self.state["sketchbook"][id].pop(self.state["sketchbook_current_section"][id])
num_sections = len(self.state["sketchbook"][id])
if num_sections == 0:
return "The section has been deleted. The sketchbook is now empty."
if self.state["sketchbook_current_section"][id] >= num_sections - 1:
self.state["sketchbook_current_section"][id] -= 1
section_content = self.state["sketchbook"][id][self.state["sketchbook_current_section"][id]]
section_content_between_xml_tag = between_xml_tag(section_content, "section", {"id": self.state["sketchbook_current_section"][id]})
output = f"The section has been deleted. You're now at section {self.state['sketchbook_current_section'][id] + 1} of {num_sections}. This is the content of the current section:\n\n{section_content_between_xml_tag}\n\nUpdate the content of this section, delete the section, or go to the next section. The review is completed when you reach the end.\n{get_sketchbook_info()}"
return output, get_tool_metadata()
case "delete_sketchbook":
del self.state["sketchbook"][id]
output = f"The sketchbook '{id}' has been deleted."
return output, get_tool_metadata()
case "save_sketchbook":
num_sections = len(self.state["sketchbook"][id])
if num_sections == 0:
return "The sketchbook is empty. There are no sections to save."
if len(filename) == 0:
return "Provide a filename for the sketchbook."
if format not in ["md", "docx"]:
return "Invalid format. The format must be 'md' (for Markdown) or 'docx' (for Word)."
print("Saving the sketchbook...")
try:
sketchbook_output = self.render_sketchbook_from_id(id)
except ImageNotFoundError as e:
error_message = f"Error: {e}"
print(error_message)
return error_message
current_datetime = datetime.now().strftime("%Y%m%d_%H%M%S")
output_filename = f"{filename}_{current_datetime}.{format}"
output_basename = os.path.basename(output_filename)
output_full_path = os.path.join(self.config.OUTPUT_PATH, output_filename)
match format:
case "md":
try:
with open(output_full_path, 'w', encoding='utf-8') as f:
f.write(sketchbook_output)
except Exception as e:
error_message = f"Error: {e}"
print(error_message)
return error_message
case "docx":
try:
pypandoc.convert_text(
sketchbook_output,
format,
format="md",
extra_args=["--toc"],
outputfile=output_filename,
cworkdir=self.config.OUTPUT_PATH,
)
except Exception as e:
error_message = f"Error: {e}"
print(error_message)
return error_message
output = f"The sketchbook has been saved as {output_basename}.\n{get_sketchbook_info()}\nYou must now share the file with the user adding a line like this:\n[file: {output_basename}]"
return output, get_tool_metadata()
case _:
error_message = f"Invalid command: {command}"
print(error_message)
return error_message, f"Invalid command: {command}"
def get_tool_result_checklist(self, tool_input: dict) -> str:
"""
Process a checklist command and update the checklist state accordingly.
This function handles various checklist operations such as starting a new checklist,
adding items, showing items, and marking items as completed.
Args:
tool_input (dict): A dictionary containing the 'command' and optional 'content'.
Returns:
str: A message indicating the result of the operation.
Commands:
- start_new: Initializes a new empty checklist.
- add_items_at_the_end: Adds a new item to the checklist.
- show_items: Shows all items in the checklist.
- mark_next_to_do_item_as_completed: Marks the next to-do item in the checklist as completed.
Note:
This function uses the utils.render_checklist method to render the checklist.
It also keeps track of the checklist items in the state.
"""
id = tool_input.get("id", "")
command = tool_input.get("command", "")
items = tool_input.get("items", [])
num_items_to_mark_as_completed = tool_input.get("n", 0)
print(f"ID: {id}")
print(f"Command: {command}")
if len(items) > 0:
print(f"Items:\n---\n{items}\n---")
if num_items_to_mark_as_completed > 0:
print(f"Number of items to mark as completed: {num_items_to_mark_as_completed}")
if len(id) == 0:
return "You need to provide an ID for the checklist."
if id not in self.state["checklist"] and command != "start_new_with_items":
checklist_list = "\n".join(self.state["checklist"].keys())
return f"Checklist not found. The following checklists are available:\n{checklist_list}"
def render_checklist(render_for_model: bool = True) -> str:
checklist = self.state["checklist"][id]
output = f"ID: {id}\n"
for index, item in enumerate(checklist):
if render_for_model:
item_state = "COMPLETED" if item['completed'] else "TO DO"
else:
item_state = "X" if item['completed'] else " "
output += f"{index + 1:>2}. [{item_state}] {item['content']}\n"
return between_xml_tag(output, "checklist") if render_for_model else output
match command:
case "start_new_with_items" | "add_items_at_the_beginning":
if command == "start_new_with_items":
self.state["checklist"][id] = []
if len(items) == 0:
return "This is a new empty checklist. Start by adding items."
if len(items) == 0:
return "You need to provide items to add."
for i in reversed(items):
item = {
"content": i,
"completed": False
}
self.state["checklist"][id].insert(0, item)
print(f"Checklist:\n{render_checklist(render_for_model=False)}")
output = f"New items added as next. Add more items or mark the next to-do items as completed.\n{render_checklist()}"
return output, render_checklist(render_for_model=False)
case "add_items_at_the_end":
if len(items) == 0:
return "You need to provide items to add."
for i in items: