aiverify-moonshot 0.4.1__py3-none-any.whl → 0.4.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. {aiverify_moonshot-0.4.1.dist-info → aiverify_moonshot-0.4.3.dist-info}/METADATA +2 -2
  2. {aiverify_moonshot-0.4.1.dist-info → aiverify_moonshot-0.4.3.dist-info}/RECORD +70 -56
  3. moonshot/__main__.py +77 -35
  4. moonshot/api.py +16 -0
  5. moonshot/integrations/cli/benchmark/benchmark.py +29 -13
  6. moonshot/integrations/cli/benchmark/cookbook.py +62 -24
  7. moonshot/integrations/cli/benchmark/datasets.py +79 -40
  8. moonshot/integrations/cli/benchmark/metrics.py +62 -23
  9. moonshot/integrations/cli/benchmark/recipe.py +89 -69
  10. moonshot/integrations/cli/benchmark/result.py +85 -47
  11. moonshot/integrations/cli/benchmark/run.py +99 -59
  12. moonshot/integrations/cli/common/common.py +20 -6
  13. moonshot/integrations/cli/common/connectors.py +154 -74
  14. moonshot/integrations/cli/common/dataset.py +66 -0
  15. moonshot/integrations/cli/common/prompt_template.py +57 -19
  16. moonshot/integrations/cli/redteam/attack_module.py +90 -24
  17. moonshot/integrations/cli/redteam/context_strategy.py +83 -23
  18. moonshot/integrations/cli/redteam/prompt_template.py +1 -1
  19. moonshot/integrations/cli/redteam/redteam.py +52 -6
  20. moonshot/integrations/cli/redteam/session.py +565 -44
  21. moonshot/integrations/cli/utils/process_data.py +52 -0
  22. moonshot/integrations/web_api/__main__.py +2 -0
  23. moonshot/integrations/web_api/app.py +6 -6
  24. moonshot/integrations/web_api/container.py +12 -2
  25. moonshot/integrations/web_api/routes/bookmark.py +173 -0
  26. moonshot/integrations/web_api/routes/dataset.py +46 -1
  27. moonshot/integrations/web_api/schemas/bookmark_create_dto.py +13 -0
  28. moonshot/integrations/web_api/schemas/dataset_create_dto.py +18 -0
  29. moonshot/integrations/web_api/schemas/recipe_create_dto.py +0 -2
  30. moonshot/integrations/web_api/services/bookmark_service.py +94 -0
  31. moonshot/integrations/web_api/services/dataset_service.py +25 -0
  32. moonshot/integrations/web_api/services/recipe_service.py +0 -1
  33. moonshot/integrations/web_api/services/utils/file_manager.py +52 -0
  34. moonshot/integrations/web_api/status_updater/moonshot_ui_webhook.py +0 -1
  35. moonshot/integrations/web_api/temp/.gitkeep +0 -0
  36. moonshot/src/api/api_bookmark.py +95 -0
  37. moonshot/src/api/api_connector_endpoint.py +1 -1
  38. moonshot/src/api/api_context_strategy.py +2 -2
  39. moonshot/src/api/api_dataset.py +35 -0
  40. moonshot/src/api/api_recipe.py +0 -3
  41. moonshot/src/api/api_session.py +1 -1
  42. moonshot/src/bookmark/bookmark.py +257 -0
  43. moonshot/src/bookmark/bookmark_arguments.py +38 -0
  44. moonshot/src/configs/env_variables.py +12 -2
  45. moonshot/src/connectors/connector.py +15 -7
  46. moonshot/src/connectors_endpoints/connector_endpoint.py +65 -49
  47. moonshot/src/cookbooks/cookbook.py +57 -37
  48. moonshot/src/datasets/dataset.py +125 -5
  49. moonshot/src/metrics/metric.py +8 -4
  50. moonshot/src/metrics/metric_interface.py +8 -2
  51. moonshot/src/prompt_templates/prompt_template.py +5 -1
  52. moonshot/src/recipes/recipe.py +38 -40
  53. moonshot/src/recipes/recipe_arguments.py +0 -4
  54. moonshot/src/redteaming/attack/attack_module.py +18 -8
  55. moonshot/src/redteaming/attack/context_strategy.py +6 -2
  56. moonshot/src/redteaming/session/session.py +15 -11
  57. moonshot/src/results/result.py +7 -3
  58. moonshot/src/runners/runner.py +65 -42
  59. moonshot/src/runs/run.py +15 -11
  60. moonshot/src/runs/run_progress.py +7 -3
  61. moonshot/src/storage/db_interface.py +14 -0
  62. moonshot/src/storage/storage.py +33 -2
  63. moonshot/src/utils/find_feature.py +45 -0
  64. moonshot/src/utils/log.py +72 -0
  65. moonshot/src/utils/pagination.py +25 -0
  66. moonshot/src/utils/timeit.py +8 -1
  67. {aiverify_moonshot-0.4.1.dist-info → aiverify_moonshot-0.4.3.dist-info}/WHEEL +0 -0
  68. {aiverify_moonshot-0.4.1.dist-info → aiverify_moonshot-0.4.3.dist-info}/licenses/AUTHORS.md +0 -0
  69. {aiverify_moonshot-0.4.1.dist-info → aiverify_moonshot-0.4.3.dist-info}/licenses/LICENSE.md +0 -0
  70. {aiverify_moonshot-0.4.1.dist-info → aiverify_moonshot-0.4.3.dist-info}/licenses/NOTICES.md +0 -0
@@ -0,0 +1,95 @@
1
+ from moonshot.src.bookmark.bookmark import Bookmark
2
+ from moonshot.src.bookmark.bookmark_arguments import BookmarkArguments
3
+
4
+
5
+ def api_insert_bookmark(
6
+ name: str,
7
+ prompt: str,
8
+ prepared_prompt: str,
9
+ response: str,
10
+ context_strategy: str = "",
11
+ prompt_template: str = "",
12
+ attack_module: str = "",
13
+ metric: str = "",
14
+ ) -> dict:
15
+ """
16
+ Inserts a new bookmark into the database.
17
+
18
+ This function constructs a BookmarkArguments object with the provided details and
19
+ invokes the add_bookmark method of a Bookmark instance to persist the new bookmark.
20
+
21
+ Args:
22
+ name (str): The unique name of the bookmark.
23
+ prompt (str): The associated prompt text for the bookmark.
24
+ response (str): The corresponding response text for the bookmark.
25
+ context_strategy (str): The strategy used for context management in the bookmark.
26
+ prompt_template (str): The template used for generating the prompt.
27
+ attack_module (str): The attack module linked with the bookmark.
28
+ """
29
+ # Create a new BookmarkArguments object
30
+ bookmark_args = BookmarkArguments(
31
+ id=0, # id will be auto-generated by the database
32
+ name=name,
33
+ prompt=prompt,
34
+ prepared_prompt=prepared_prompt,
35
+ response=response,
36
+ context_strategy=context_strategy,
37
+ prompt_template=prompt_template,
38
+ attack_module=attack_module,
39
+ metric=metric,
40
+ bookmark_time="", # bookmark_time will be set to current time in add_bookmark method
41
+ )
42
+ return Bookmark.get_instance().add_bookmark(bookmark_args)
43
+
44
+
45
+ def api_get_all_bookmarks() -> list[dict]:
46
+ """
47
+ Retrieves a list of all bookmarks from the database.
48
+
49
+ Returns:
50
+ list[dict]: A list of bookmarks, each represented as a dictionary.
51
+ """
52
+ return Bookmark.get_instance().get_all_bookmarks()
53
+
54
+
55
+ def api_get_bookmark(bookmark_name: str) -> dict:
56
+ """
57
+ Retrieves the details of a specific bookmark by its name.
58
+
59
+ Args:
60
+ bookmark_name (int): The name of the bookmark to retrieve.
61
+
62
+ Returns:
63
+ dict: The bookmark details corresponding to the provided ID.
64
+ """
65
+ return Bookmark.get_instance().get_bookmark(bookmark_name)
66
+
67
+
68
+ def api_delete_bookmark(bookmark_name: str) -> dict:
69
+ """
70
+ Removes a bookmark from the database using its name.
71
+
72
+ Args:
73
+ bookmark_name (str): The name of the bookmark to be removed.
74
+ """
75
+ return Bookmark.get_instance().delete_bookmark(bookmark_name)
76
+
77
+
78
+ def api_delete_all_bookmark() -> dict:
79
+ """
80
+ Removes all bookmarks from the database.
81
+ """
82
+ return Bookmark.get_instance().delete_all_bookmark()
83
+
84
+
85
+ def api_export_bookmarks(export_file_name: str = "bookmarks") -> str:
86
+ """
87
+ Exports bookmarks to a specified file.
88
+
89
+ Args:
90
+ export_file_name (str): The name of the file to export the bookmarks to.
91
+
92
+ Returns:
93
+ str: The filepath of where the file is written.
94
+ """
95
+ return Bookmark.get_instance().export_bookmarks(export_file_name)
@@ -98,7 +98,7 @@ def api_update_endpoint(ep_id: str, **kwargs) -> bool:
98
98
  existing_endpoint = ConnectorEndpoint.read(ep_id)
99
99
  except Exception:
100
100
  raise RuntimeError(
101
- f"[api_connector_endpoint]: Endpoint with ID '{ep_id}' does not exist"
101
+ f"[api_update_endpoint]: Endpoint with ID '{ep_id}' does not exist"
102
102
  )
103
103
 
104
104
  # Update the fields of the existing endpoint with the provided kwargs
@@ -40,7 +40,7 @@ def api_delete_context_strategy(cs_id: str) -> bool:
40
40
  return ContextStrategy.delete(cs_id)
41
41
 
42
42
 
43
- def api_get_all_context_strategy_metadata() -> list:
43
+ def api_get_all_context_strategy_metadata() -> list[dict]:
44
44
  """
45
45
  Retrieves metadata for all context strategy modules.
46
46
 
@@ -48,7 +48,7 @@ def api_get_all_context_strategy_metadata() -> list:
48
48
  returns a list of metadata dictionaries.
49
49
 
50
50
  Returns:
51
- list: A list of attack module metadata.
51
+ list[dict]: A list of dictionaries, each representing the details of a context strategy metadata.
52
52
  """
53
53
 
54
54
  return [
@@ -1,6 +1,7 @@
1
1
  from pydantic import validate_call
2
2
 
3
3
  from moonshot.src.datasets.dataset import Dataset
4
+ from moonshot.src.datasets.dataset_arguments import DatasetArguments
4
5
 
5
6
 
6
7
  # ------------------------------------------------------------------------------
@@ -44,3 +45,37 @@ def api_get_all_datasets_name() -> list[str]:
44
45
  """
45
46
  datasets_name, _ = Dataset.get_available_items()
46
47
  return datasets_name
48
+
49
+
50
+ def api_create_datasets(
51
+ name: str, description: str, reference: str, license: str, method: str, **kwargs
52
+ ) -> str:
53
+ """
54
+ This function creates a new dataset.
55
+
56
+ This function takes the name, description, reference, and license for a new dataset as input. It then creates a new
57
+ DatasetArguments object with these details and an empty id. The id is left empty because it will be generated
58
+ from the name during the creation process. The function then calls the Dataset's create method to
59
+ create the new dataset.
60
+
61
+ Args:
62
+ name (str): The name of the new dataset.
63
+ description (str): A brief description of the new dataset.
64
+ reference (str): A reference link for the new dataset.
65
+ license (str): The license of the new dataset.
66
+ method (str): The method to create new dataset. (csv/hf)
67
+ kwargs: Additional keyword arguments for the Dataset's create method.
68
+
69
+ Returns:
70
+ str: The ID of the newly created dataset.
71
+ """
72
+ ds_args = DatasetArguments(
73
+ id="",
74
+ name=name,
75
+ description=description,
76
+ reference=reference,
77
+ license=license,
78
+ examples=None,
79
+ )
80
+
81
+ return Dataset.create(ds_args, method, **kwargs)
@@ -16,7 +16,6 @@ def api_create_recipe(
16
16
  datasets: list[str],
17
17
  prompt_templates: list[str],
18
18
  metrics: list[str],
19
- attack_modules: list[str],
20
19
  grading_scale: dict[str, list[int]],
21
20
  ) -> str:
22
21
  """
@@ -34,7 +33,6 @@ def api_create_recipe(
34
33
  datasets (list[str]): A list of datasets used in the recipe.
35
34
  prompt_templates (list[str]): A list of prompt templates for the recipe.
36
35
  metrics (list[str]): A list of metrics to evaluate the recipe.
37
- attack_modules (list[str]): A list of attack modules used in the recipe.
38
36
  grading_scale (dict[str, list[int]]): A grading scale dictionary where the key is the grade and the
39
37
  value is a list of integers representing the scale.
40
38
 
@@ -50,7 +48,6 @@ def api_create_recipe(
50
48
  datasets=datasets,
51
49
  prompt_templates=prompt_templates,
52
50
  metrics=metrics,
53
- attack_modules=attack_modules,
54
51
  grading_scale=grading_scale,
55
52
  )
56
53
  return Recipe.create(rec_args)
@@ -115,7 +115,7 @@ def api_get_available_session_info() -> tuple[list, list]:
115
115
  return runner_ids, session_metadata_list
116
116
 
117
117
 
118
- def api_get_all_session_metadata() -> list:
118
+ def api_get_all_session_metadata() -> list[dict]:
119
119
  """
120
120
  Retrieves metadata for all sessions.
121
121
 
@@ -0,0 +1,257 @@
1
+ from datetime import datetime
2
+
3
+ from moonshot.src.bookmark.bookmark_arguments import BookmarkArguments
4
+ from moonshot.src.configs.env_variables import EnvVariables
5
+ from moonshot.src.storage.storage import Storage
6
+ from moonshot.src.utils.log import configure_logger
7
+
8
+ # Create a logger for this module
9
+ logger = configure_logger(__name__)
10
+
11
+
12
+ class Bookmark:
13
+ _instance = None
14
+
15
+ def __new__(cls, db_name="bookmark"):
16
+ """
17
+ Create a new instance of the Bookmark class or return the existing instance.
18
+
19
+ Args:
20
+ db_name (str): The name of the database.
21
+
22
+ Returns:
23
+ Bookmark: The singleton instance of the Bookmark class.
24
+ """
25
+ if cls._instance is None:
26
+ cls._instance = super(Bookmark, cls).__new__(cls)
27
+ cls._instance.__init_instance(db_name)
28
+ return cls._instance
29
+
30
+ @classmethod
31
+ def get_instance(cls, db_name="bookmark"):
32
+ """
33
+ Get the singleton instance of the Bookmark class.
34
+
35
+ Args:
36
+ db_name (str): The name of the database.
37
+
38
+ Returns:
39
+ Bookmark: The singleton instance of the Bookmark class.
40
+ """
41
+ if cls._instance is None:
42
+ cls._instance = super(Bookmark, cls).__new__(cls)
43
+ cls._instance.__init_instance(db_name)
44
+ return cls._instance
45
+
46
+ sql_create_bookmark_table = """
47
+ CREATE TABLE IF NOT EXISTS bookmark (
48
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
49
+ name TEXT NOT NULL UNIQUE,
50
+ prompt TEXT NOT NULL,
51
+ prepared_prompt TEXT NOT NULL,
52
+ response TEXT NOT NULL,
53
+ context_strategy TEXT,
54
+ prompt_template TEXT,
55
+ attack_module TEXT,
56
+ metric TEXT,
57
+ bookmark_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
58
+ );
59
+ """
60
+
61
+ sql_insert_bookmark_record = """
62
+ INSERT INTO bookmark (
63
+ name, prompt, prepared_prompt, response, context_strategy, prompt_template, attack_module,
64
+ metric, bookmark_time)
65
+ VALUES (?,?,?,?,?,?,?,?,?);
66
+ """
67
+
68
+ sql_select_bookmarks_record = """
69
+ SELECT * FROM bookmark;
70
+ """
71
+
72
+ sql_select_bookmark_record = """
73
+ SELECT * FROM bookmark WHERE name = ? ;
74
+ """
75
+
76
+ sql_delete_bookmark_records = """
77
+ DELETE FROM bookmark;
78
+ """
79
+
80
+ def __init_instance(self, db_name) -> None:
81
+ """
82
+ Initialize the database instance for the Bookmark class.
83
+
84
+ Args:
85
+ db_name (str): The name of the database.
86
+ """
87
+ self.db_instance = Storage.create_database_connection(
88
+ EnvVariables.BOOKMARKS.name, db_name, "db"
89
+ )
90
+ Storage.create_database_table(
91
+ self.db_instance, Bookmark.sql_create_bookmark_table
92
+ )
93
+
94
+ def add_bookmark(self, bookmark: BookmarkArguments) -> dict:
95
+ """
96
+ Add a new bookmark to the database and return the success status.
97
+
98
+ Args:
99
+ bookmark (BookmarkArguments): The bookmark data to add.
100
+
101
+ Returns:
102
+ bool: True if the bookmark was added successfully, False otherwise.
103
+ """
104
+ bookmark.bookmark_time = datetime.now().replace(microsecond=0).isoformat(" ")
105
+
106
+ data = (
107
+ bookmark.name,
108
+ bookmark.prompt,
109
+ bookmark.prepared_prompt,
110
+ bookmark.response,
111
+ bookmark.context_strategy,
112
+ bookmark.prompt_template,
113
+ bookmark.attack_module,
114
+ bookmark.metric,
115
+ bookmark.bookmark_time,
116
+ )
117
+ try:
118
+ results = Storage.create_database_record(
119
+ self.db_instance, data, Bookmark.sql_insert_bookmark_record
120
+ )
121
+ if results is not None:
122
+ return {"success": True, "message": "Bookmark added successfully."}
123
+ else:
124
+ raise Exception("Error inserting record into database.")
125
+ except Exception as e:
126
+ error_message = f"Failed to add bookmark record: {e}"
127
+ return {"success": False, "message": error_message}
128
+
129
+ def get_all_bookmarks(self) -> list[dict]:
130
+ """
131
+ Retrieve all bookmarks from the database.
132
+
133
+ Returns:
134
+ list[dict]: A list of all bookmarks as dictionaries.
135
+ """
136
+ list_of_bookmarks_tuples = Storage.read_database_records(
137
+ self.db_instance,
138
+ Bookmark.sql_select_bookmarks_record,
139
+ )
140
+ if list_of_bookmarks_tuples:
141
+ list_of_bookmarks = [
142
+ BookmarkArguments.from_tuple_to_dict(bookmark_tuple)
143
+ for bookmark_tuple in list_of_bookmarks_tuples
144
+ ]
145
+ else:
146
+ list_of_bookmarks = []
147
+ return list_of_bookmarks
148
+
149
+ def get_bookmark(self, bookmark_name: str) -> dict:
150
+ """
151
+ Retrieve a bookmark by its unique name.
152
+
153
+ Args:
154
+ bookmark_name (int): The unique name for the bookmark.
155
+
156
+ Returns:
157
+ dict: The bookmark information as a dictionary.
158
+
159
+ Raises:
160
+ RuntimeError: If the bookmark cannot be found.
161
+ """
162
+ if bookmark_name is not None:
163
+ bookmark_info = Storage.read_database_record(
164
+ self.db_instance, (bookmark_name,), Bookmark.sql_select_bookmark_record
165
+ )
166
+ if bookmark_info is not None:
167
+ return BookmarkArguments.from_tuple_to_dict(bookmark_info)
168
+ else:
169
+ raise RuntimeError(
170
+ f"[Bookmark] No record found for bookmark name {bookmark_name}"
171
+ )
172
+ else:
173
+ raise RuntimeError(f"[Bookmark] Invalid bookmark name: {bookmark_name}")
174
+
175
+ def delete_bookmark(self, bookmark_name: str) -> dict:
176
+ """
177
+ Delete a bookmark by its unique name.
178
+
179
+ Args:
180
+ bookmark_name (str): The unique name for the bookmark to be deleted.
181
+ """
182
+ if bookmark_name is not None:
183
+ try:
184
+ sql_delete_bookmark_record = f"""
185
+ DELETE FROM bookmark WHERE name = '{bookmark_name}';
186
+ """
187
+ Storage.delete_database_record_in_table(
188
+ self.db_instance, sql_delete_bookmark_record
189
+ )
190
+ return {"success": True, "message": "Bookmark record deleted."}
191
+ except Exception as e:
192
+ error_message = f"Failed to delete bookmark record: {e}"
193
+ return {"success": False, "message": error_message}
194
+ else:
195
+ error_message = f"[Bookmark] Invalid bookmark name: {bookmark_name}"
196
+ return {"success": False, "message": error_message}
197
+
198
+ def delete_all_bookmark(self) -> dict:
199
+ """
200
+ Delete all bookmarks from the database and return the operation result.
201
+
202
+ Returns:
203
+ dict: A dictionary with 'success' status and 'message' containing an error message if failed.
204
+ """
205
+ try:
206
+ Storage.delete_database_record_in_table(
207
+ self.db_instance, Bookmark.sql_delete_bookmark_records
208
+ )
209
+ return {"success": True, "message": "All bookmark records deleted."}
210
+ except Exception as e:
211
+ error_message = f"Failed to delete all bookmark records: {e}"
212
+ return {"success": False, "message": error_message}
213
+
214
+ def export_bookmarks(self, export_file_name: str = "bookmarks") -> str:
215
+ """
216
+ Export all bookmarks to a JSON file.
217
+
218
+ This method retrieves all bookmarks from the database, converts them to a JSON format,
219
+ and writes them to a file in the 'moonshot-data/bookmark' directory with the provided file name.
220
+
221
+ Args:
222
+ export_file_name (str): The base name of the file to export the bookmarks to.
223
+ The '.json' extension will be appended to this base name.
224
+
225
+ Returns:
226
+ str: The path to the exported JSON file containing the bookmarks.
227
+ """
228
+ list_of_bookmarks_tuples = Storage.read_database_records(
229
+ self.db_instance,
230
+ Bookmark.sql_select_bookmarks_record,
231
+ )
232
+
233
+ if list_of_bookmarks_tuples is not None:
234
+ bookmarks_json = [
235
+ BookmarkArguments.from_tuple_to_dict(bookmark_tuple)
236
+ for bookmark_tuple in list_of_bookmarks_tuples
237
+ ]
238
+ else:
239
+ bookmarks_json = []
240
+
241
+ try:
242
+ return Storage.create_object(
243
+ EnvVariables.BOOKMARKS.name,
244
+ export_file_name,
245
+ {"bookmarks": bookmarks_json},
246
+ "json",
247
+ )
248
+ except Exception as e:
249
+ logger.error(f"Failed to export bookmarks - {str(e)}.")
250
+ raise e
251
+
252
+ def close(self) -> None:
253
+ """
254
+ Close the database connection.
255
+ """
256
+ if self.db_instance:
257
+ Storage.close_database_connection(self.db_instance)
@@ -0,0 +1,38 @@
1
+ from __future__ import annotations
2
+
3
+ from pydantic import BaseModel, Field
4
+
5
+
6
+ class BookmarkArguments(BaseModel):
7
+ name: str = Field(min_length=1)
8
+ prompt: str = Field(min_length=1)
9
+ prepared_prompt: str = Field(min_length=1)
10
+ response: str = Field(min_length=1)
11
+ context_strategy: str
12
+ prompt_template: str
13
+ attack_module: str
14
+ metric: str
15
+ bookmark_time: str
16
+
17
+ @classmethod
18
+ def from_tuple_to_dict(cls, values: tuple) -> dict:
19
+ """
20
+ Creates a dictionary from a tuple of values representing BookmarkArguments fields.
21
+
22
+ Args:
23
+ values (tuple): A tuple containing the fields of BookmarkArguments in order.
24
+
25
+ Returns:
26
+ dict: A dictionary representing the BookmarkArguments.
27
+ """
28
+ return {
29
+ "name": values[1],
30
+ "prompt": values[2],
31
+ "prepared_prompt": values[3],
32
+ "response": values[4],
33
+ "context_strategy": values[5],
34
+ "prompt_template": values[6],
35
+ "attack_module": values[7],
36
+ "metric": values[8],
37
+ "bookmark_time": values[9],
38
+ }
@@ -2,11 +2,17 @@ import importlib.resources
2
2
  from enum import Enum
3
3
  from pathlib import Path
4
4
 
5
+ from moonshot.src.utils.log import configure_logger
6
+
7
+ # Create a logger for this module
8
+ logger = configure_logger(__name__)
9
+
5
10
  __app_name__ = "moonshot"
6
11
 
7
12
 
8
13
  class EnvVariables(Enum):
9
14
  ATTACK_MODULES = "ATTACK_MODULES"
15
+ BOOKMARKS = "BOOKMARKS"
10
16
  CONNECTORS = "CONNECTORS"
11
17
  CONNECTORS_ENDPOINTS = "CONNECTORS_ENDPOINTS"
12
18
  CONTEXT_STRATEGY = "CONTEXT_STRATEGY"
@@ -31,6 +37,10 @@ class EnvironmentVars:
31
37
  env_vars.get(EnvVariables.ATTACK_MODULES.value),
32
38
  str(importlib.resources.files(__app_name__).joinpath("data/attack-modules")),
33
39
  ]
40
+ BOOKMARKS = [
41
+ env_vars.get(EnvVariables.BOOKMARKS.value),
42
+ str(importlib.resources.files(__app_name__).joinpath("data/generated-outputs/bookmarks")),
43
+ ]
34
44
  CONNECTORS = [
35
45
  env_vars.get(EnvVariables.CONNECTORS.value),
36
46
  str(importlib.resources.files(__app_name__).joinpath("data/connectors")),
@@ -133,14 +143,14 @@ class EnvironmentVars:
133
143
  if given_path.exists():
134
144
  EnvironmentVars.__dict__[key][0] = str(given_path)
135
145
  else:
136
- print(
146
+ logger.warning(
137
147
  f"Unable to set {key}. The provided path {given_path} does not exist. ",
138
148
  "The stock set will be used.",
139
149
  )
140
150
  else:
141
151
  unset_keys.append(key)
142
152
  if unset_keys:
143
- print(
153
+ logger.warning(
144
154
  f"Unable to retrieve the following environment variables: {unset_keys}. The stock set will be used."
145
155
  )
146
156
 
@@ -15,6 +15,10 @@ from moonshot.src.connectors_endpoints.connector_endpoint_arguments import (
15
15
  )
16
16
  from moonshot.src.storage.storage import Storage
17
17
  from moonshot.src.utils.import_modules import get_instance
18
+ from moonshot.src.utils.log import configure_logger
19
+
20
+ # Create a logger for this module
21
+ logger = configure_logger(__name__)
18
22
 
19
23
 
20
24
  def perform_retry(func):
@@ -42,13 +46,15 @@ def perform_retry(func):
42
46
  try:
43
47
  return await func(self, *args, **kwargs)
44
48
  except Exception as exc:
45
- print(f"Operation failed. {str(exc)} - Retrying...")
49
+ logger.warning(f"Operation failed. {str(exc)} - Retrying...")
46
50
 
47
51
  # Perform retry
48
52
  retry_count += 1
49
53
  if retry_count <= self.retries_times:
50
54
  delay = base_delay * (2**retry_count)
51
- print(f"Attempt {retry_count}, Retrying in {delay} seconds...")
55
+ logger.warning(
56
+ f"Attempt {retry_count}, Retrying in {delay} seconds..."
57
+ )
52
58
  await sleep(delay)
53
59
  # Raise an exception
54
60
  raise ConnectionError("Failed to get response.")
@@ -228,7 +234,7 @@ class Connector:
228
234
  return Connector.load(ep_args)
229
235
 
230
236
  except Exception as e:
231
- print(f"Failed to create connector: {str(e)}")
237
+ logger.error(f"Failed to create connector: {str(e)}")
232
238
  raise e
233
239
 
234
240
  @staticmethod
@@ -255,7 +261,7 @@ class Connector:
255
261
  ]
256
262
 
257
263
  except Exception as e:
258
- print(f"Failed to get available connectors: {str(e)}")
264
+ logger.error(f"Failed to get available connectors: {str(e)}")
259
265
  raise e
260
266
 
261
267
  @staticmethod
@@ -292,14 +298,16 @@ class Connector:
292
298
  Exception: If there is an error during prediction.
293
299
  """
294
300
  try:
295
- print(f"Predicting prompt {generated_prompt.prompt_index} [{connector.id}]")
301
+ logger.info(
302
+ f"Predicting prompt {generated_prompt.prompt_index} [{connector.id}]"
303
+ )
296
304
 
297
305
  start_time = time.perf_counter()
298
306
  generated_prompt.predicted_results = await connector.get_response(
299
307
  generated_prompt.prompt
300
308
  )
301
309
  generated_prompt.duration = time.perf_counter() - start_time
302
- print(
310
+ logger.debug(
303
311
  f"[Prompt {generated_prompt.prompt_index}] took {generated_prompt.duration:.4f}s"
304
312
  )
305
313
 
@@ -311,7 +319,7 @@ class Connector:
311
319
  return generated_prompt
312
320
 
313
321
  except Exception as e:
314
- print(f"Failed to get prediction: {str(e)}")
322
+ logger.error(f"Failed to get prediction: {str(e)}")
315
323
  raise e
316
324
 
317
325
  def set_system_prompt(self, system_prompt: str) -> None: