aiverify-moonshot 0.4.5__py3-none-any.whl → 0.4.7__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.
@@ -39,7 +39,7 @@ def api_insert_bookmark(
39
39
  metric=metric,
40
40
  bookmark_time="", # bookmark_time will be set to current time in add_bookmark method
41
41
  )
42
- return Bookmark.get_instance().add_bookmark(bookmark_args)
42
+ return Bookmark().add_bookmark(bookmark_args)
43
43
 
44
44
 
45
45
  def api_get_all_bookmarks() -> list[dict]:
@@ -49,7 +49,7 @@ def api_get_all_bookmarks() -> list[dict]:
49
49
  Returns:
50
50
  list[dict]: A list of bookmarks, each represented as a dictionary.
51
51
  """
52
- return Bookmark.get_instance().get_all_bookmarks()
52
+ return Bookmark().get_all_bookmarks()
53
53
 
54
54
 
55
55
  def api_get_bookmark(bookmark_name: str) -> dict:
@@ -62,7 +62,7 @@ def api_get_bookmark(bookmark_name: str) -> dict:
62
62
  Returns:
63
63
  dict: The bookmark details corresponding to the provided ID.
64
64
  """
65
- return Bookmark.get_instance().get_bookmark(bookmark_name)
65
+ return Bookmark().get_bookmark(bookmark_name)
66
66
 
67
67
 
68
68
  def api_delete_bookmark(bookmark_name: str) -> dict:
@@ -72,14 +72,14 @@ def api_delete_bookmark(bookmark_name: str) -> dict:
72
72
  Args:
73
73
  bookmark_name (str): The name of the bookmark to be removed.
74
74
  """
75
- return Bookmark.get_instance().delete_bookmark(bookmark_name)
75
+ return Bookmark().delete_bookmark(bookmark_name)
76
76
 
77
77
 
78
78
  def api_delete_all_bookmark() -> dict:
79
79
  """
80
80
  Removes all bookmarks from the database.
81
81
  """
82
- return Bookmark.get_instance().delete_all_bookmark()
82
+ return Bookmark().delete_all_bookmark()
83
83
 
84
84
 
85
85
  def api_export_bookmarks(export_file_name: str = "bookmarks") -> str:
@@ -92,4 +92,4 @@ def api_export_bookmarks(export_file_name: str = "bookmarks") -> str:
92
92
  Returns:
93
93
  str: The filepath of where the file is written.
94
94
  """
95
- return Bookmark.get_instance().export_bookmarks(export_file_name)
95
+ return Bookmark().export_bookmarks(export_file_name)
@@ -1,7 +1,24 @@
1
+ from __future__ import annotations
2
+
3
+ import textwrap
1
4
  from datetime import datetime
2
5
 
3
6
  from moonshot.src.bookmark.bookmark_arguments import BookmarkArguments
4
7
  from moonshot.src.configs.env_variables import EnvVariables
8
+ from moonshot.src.messages_constants import (
9
+ BOOKMARK_ADD_BOOKMARK_ERROR,
10
+ BOOKMARK_ADD_BOOKMARK_SUCCESS,
11
+ BOOKMARK_ADD_BOOKMARK_VALIDATION_ERROR,
12
+ BOOKMARK_DELETE_ALL_BOOKMARK_ERROR,
13
+ BOOKMARK_DELETE_ALL_BOOKMARK_SUCCESS,
14
+ BOOKMARK_DELETE_BOOKMARK_ERROR,
15
+ BOOKMARK_DELETE_BOOKMARK_ERROR_1,
16
+ BOOKMARK_DELETE_BOOKMARK_SUCCESS,
17
+ BOOKMARK_EXPORT_BOOKMARK_ERROR,
18
+ BOOKMARK_EXPORT_BOOKMARK_VALIDATION_ERROR,
19
+ BOOKMARK_GET_BOOKMARK_ERROR,
20
+ BOOKMARK_GET_BOOKMARK_ERROR_1,
21
+ )
5
22
  from moonshot.src.storage.storage import Storage
6
23
  from moonshot.src.utils.log import configure_logger
7
24
 
@@ -12,36 +29,7 @@ logger = configure_logger(__name__)
12
29
  class Bookmark:
13
30
  _instance = None
14
31
 
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
32
+ sql_table_name = "bookmark"
45
33
 
46
34
  sql_create_bookmark_table = """
47
35
  CREATE TABLE IF NOT EXISTS bookmark (
@@ -77,19 +65,46 @@ class Bookmark:
77
65
  DELETE FROM bookmark;
78
66
  """
79
67
 
80
- def __init_instance(self, db_name) -> None:
68
+ def __new__(cls, db_name="bookmark"):
69
+ """
70
+ Create a new instance of the Bookmark class or return the existing instance.
71
+
72
+ This method ensures that only one instance of the Bookmark class is created (singleton pattern).
73
+ If an instance already exists, it returns that instance. Otherwise, it creates a new instance
74
+ and initializes it with the provided database name.
75
+
76
+ Args:
77
+ db_name (str): The name of the database. Defaults to "bookmark".
78
+
79
+ Returns:
80
+ Bookmark: The singleton instance of the Bookmark class.
81
+ """
82
+ if cls._instance is None:
83
+ cls._instance = super(Bookmark, cls).__new__(cls)
84
+ cls._instance.__init_instance(db_name)
85
+ return cls._instance
86
+
87
+ def __init_instance(self, db_name: str = "bookmark") -> None:
81
88
  """
82
89
  Initialize the database instance for the Bookmark class.
83
90
 
91
+ This method sets up the database connection for the Bookmark class. It creates a new database
92
+ connection using the provided database name and checks if the required table exists. If the table
93
+ does not exist, it creates the table.
94
+
84
95
  Args:
85
- db_name (str): The name of the database.
96
+ db_name (str): The name of the database. Defaults to "bookmark".
86
97
  """
87
98
  self.db_instance = Storage.create_database_connection(
88
99
  EnvVariables.BOOKMARKS.name, db_name, "db"
89
100
  )
90
- Storage.create_database_table(
91
- self.db_instance, Bookmark.sql_create_bookmark_table
92
- )
101
+
102
+ if not Storage.check_database_table_exists(
103
+ self.db_instance, Bookmark.sql_table_name
104
+ ):
105
+ Storage.create_database_table(
106
+ self.db_instance, Bookmark.sql_create_bookmark_table
107
+ )
93
108
 
94
109
  def add_bookmark(self, bookmark: BookmarkArguments) -> dict:
95
110
  """
@@ -99,7 +114,7 @@ class Bookmark:
99
114
  bookmark (BookmarkArguments): The bookmark data to add.
100
115
 
101
116
  Returns:
102
- bool: True if the bookmark was added successfully, False otherwise.
117
+ dict: A dictionary containing the success status and a message.
103
118
  """
104
119
  bookmark.bookmark_time = datetime.now().replace(microsecond=0).isoformat(" ")
105
120
 
@@ -119,12 +134,14 @@ class Bookmark:
119
134
  self.db_instance, data, Bookmark.sql_insert_bookmark_record
120
135
  )
121
136
  if results is not None:
122
- return {"success": True, "message": "Bookmark added successfully."}
137
+ return {"success": True, "message": BOOKMARK_ADD_BOOKMARK_SUCCESS}
123
138
  else:
124
- raise Exception("Error inserting record into database.")
139
+ raise Exception(BOOKMARK_ADD_BOOKMARK_VALIDATION_ERROR)
125
140
  except Exception as e:
126
- error_message = f"Failed to add bookmark record: {e}"
127
- return {"success": False, "message": error_message}
141
+ return {
142
+ "success": False,
143
+ "message": BOOKMARK_ADD_BOOKMARK_ERROR.format(message=str(e)),
144
+ }
128
145
 
129
146
  def get_all_bookmarks(self) -> list[dict]:
130
147
  """
@@ -137,7 +154,9 @@ class Bookmark:
137
154
  self.db_instance,
138
155
  Bookmark.sql_select_bookmarks_record,
139
156
  )
140
- if list_of_bookmarks_tuples:
157
+ if isinstance(list_of_bookmarks_tuples, list) and all(
158
+ isinstance(item, tuple) for item in list_of_bookmarks_tuples
159
+ ):
141
160
  list_of_bookmarks = [
142
161
  BookmarkArguments.from_tuple_to_dict(bookmark_tuple)
143
162
  for bookmark_tuple in list_of_bookmarks_tuples
@@ -151,7 +170,7 @@ class Bookmark:
151
170
  Retrieve a bookmark by its unique name.
152
171
 
153
172
  Args:
154
- bookmark_name (int): The unique name for the bookmark.
173
+ bookmark_name (str): The unique name for the bookmark.
155
174
 
156
175
  Returns:
157
176
  dict: The bookmark information as a dictionary.
@@ -159,18 +178,24 @@ class Bookmark:
159
178
  Raises:
160
179
  RuntimeError: If the bookmark cannot be found.
161
180
  """
162
- if bookmark_name is not None:
181
+ if isinstance(bookmark_name, str) and bookmark_name:
163
182
  bookmark_info = Storage.read_database_record(
164
183
  self.db_instance, (bookmark_name,), Bookmark.sql_select_bookmark_record
165
184
  )
166
- if bookmark_info is not None:
185
+ if (
186
+ bookmark_info is not None
187
+ and isinstance(bookmark_info, tuple)
188
+ and all(isinstance(item, str) for item in bookmark_info)
189
+ ):
167
190
  return BookmarkArguments.from_tuple_to_dict(bookmark_info)
168
191
  else:
169
192
  raise RuntimeError(
170
- f"[Bookmark] No record found for bookmark name {bookmark_name}"
193
+ BOOKMARK_GET_BOOKMARK_ERROR.format(message=bookmark_name)
171
194
  )
172
195
  else:
173
- raise RuntimeError(f"[Bookmark] Invalid bookmark name: {bookmark_name}")
196
+ raise RuntimeError(
197
+ BOOKMARK_GET_BOOKMARK_ERROR_1.format(message=bookmark_name)
198
+ )
174
199
 
175
200
  def delete_bookmark(self, bookmark_name: str) -> dict:
176
201
  """
@@ -178,22 +203,33 @@ class Bookmark:
178
203
 
179
204
  Args:
180
205
  bookmark_name (str): The unique name for the bookmark to be deleted.
206
+
207
+ Returns:
208
+ dict: A dictionary containing the success status and a message.
181
209
  """
182
- if bookmark_name is not None:
210
+ if isinstance(bookmark_name, str) and bookmark_name:
183
211
  try:
184
- sql_delete_bookmark_record = f"""
212
+ sql_delete_bookmark_record = textwrap.dedent(
213
+ f"""
185
214
  DELETE FROM bookmark WHERE name = '{bookmark_name}';
186
215
  """
216
+ )
187
217
  Storage.delete_database_record_in_table(
188
218
  self.db_instance, sql_delete_bookmark_record
189
219
  )
190
- return {"success": True, "message": "Bookmark record deleted."}
220
+ return {"success": True, "message": BOOKMARK_DELETE_BOOKMARK_SUCCESS}
191
221
  except Exception as e:
192
- error_message = f"Failed to delete bookmark record: {e}"
193
- return {"success": False, "message": error_message}
222
+ return {
223
+ "success": False,
224
+ "message": BOOKMARK_DELETE_BOOKMARK_ERROR.format(message=str(e)),
225
+ }
194
226
  else:
195
- error_message = f"[Bookmark] Invalid bookmark name: {bookmark_name}"
196
- return {"success": False, "message": error_message}
227
+ return {
228
+ "success": False,
229
+ "message": BOOKMARK_DELETE_BOOKMARK_ERROR_1.format(
230
+ message=bookmark_name
231
+ ),
232
+ }
197
233
 
198
234
  def delete_all_bookmark(self) -> dict:
199
235
  """
@@ -206,10 +242,12 @@ class Bookmark:
206
242
  Storage.delete_database_record_in_table(
207
243
  self.db_instance, Bookmark.sql_delete_bookmark_records
208
244
  )
209
- return {"success": True, "message": "All bookmark records deleted."}
245
+ return {"success": True, "message": BOOKMARK_DELETE_ALL_BOOKMARK_SUCCESS}
210
246
  except Exception as e:
211
- error_message = f"Failed to delete all bookmark records: {e}"
212
- return {"success": False, "message": error_message}
247
+ return {
248
+ "success": False,
249
+ "message": BOOKMARK_DELETE_ALL_BOOKMARK_ERROR.format(message=str(e)),
250
+ }
213
251
 
214
252
  def export_bookmarks(self, export_file_name: str = "bookmarks") -> str:
215
253
  """
@@ -224,13 +262,27 @@ class Bookmark:
224
262
 
225
263
  Returns:
226
264
  str: The path to the exported JSON file containing the bookmarks.
265
+
266
+ Raises:
267
+ Exception: If the export file name is invalid or an error occurs during export.
227
268
  """
269
+ if not isinstance(export_file_name, str) or not export_file_name:
270
+ error_message = BOOKMARK_EXPORT_BOOKMARK_ERROR.format(
271
+ message=BOOKMARK_EXPORT_BOOKMARK_VALIDATION_ERROR
272
+ )
273
+ logger.error(error_message)
274
+ raise Exception(error_message)
275
+
228
276
  list_of_bookmarks_tuples = Storage.read_database_records(
229
277
  self.db_instance,
230
278
  Bookmark.sql_select_bookmarks_record,
231
279
  )
232
280
 
233
- if list_of_bookmarks_tuples is not None:
281
+ if (
282
+ list_of_bookmarks_tuples is not None
283
+ and isinstance(list_of_bookmarks_tuples, list)
284
+ and all(isinstance(item, tuple) for item in list_of_bookmarks_tuples)
285
+ ):
234
286
  bookmarks_json = [
235
287
  BookmarkArguments.from_tuple_to_dict(bookmark_tuple)
236
288
  for bookmark_tuple in list_of_bookmarks_tuples
@@ -246,12 +298,19 @@ class Bookmark:
246
298
  "json",
247
299
  )
248
300
  except Exception as e:
249
- logger.error(f"Failed to export bookmarks - {str(e)}.")
250
- raise e
301
+ error_message = BOOKMARK_EXPORT_BOOKMARK_ERROR.format(message=str(e))
302
+ logger.error(error_message)
303
+ raise Exception(error_message)
251
304
 
252
305
  def close(self) -> None:
253
306
  """
254
- Close the database connection.
307
+ Close the database connection and set the Bookmark instance to None.
308
+
309
+ This method ensures that the database connection is properly closed and the singleton
310
+ instance of the Bookmark class is reset to None, allowing for a fresh instance to be created
311
+ if needed in the future.
255
312
  """
256
313
  if self.db_instance:
257
314
  Storage.close_database_connection(self.db_instance)
315
+
316
+ Bookmark._instance = None
@@ -2,6 +2,10 @@ from __future__ import annotations
2
2
 
3
3
  from pydantic import BaseModel, Field
4
4
 
5
+ from moonshot.src.messages_constants import (
6
+ BOOKMARK_ARGUMENTS_FROM_TUPLE_TO_DICT_VALIDATION_ERROR,
7
+ )
8
+
5
9
 
6
10
  class BookmarkArguments(BaseModel):
7
11
  name: str = Field(min_length=1)
@@ -24,7 +28,13 @@ class BookmarkArguments(BaseModel):
24
28
 
25
29
  Returns:
26
30
  dict: A dictionary representing the BookmarkArguments.
31
+
32
+ Raises:
33
+ ValueError: If the number of values in the tuple is less than 10.
27
34
  """
35
+ if len(values) < 10:
36
+ raise ValueError(BOOKMARK_ARGUMENTS_FROM_TUPLE_TO_DICT_VALIDATION_ERROR)
37
+
28
38
  return {
29
39
  "name": values[1],
30
40
  "prompt": values[2],
@@ -0,0 +1,40 @@
1
+ # ------------------------------------------------------------------------------
2
+ # BOOKMARK - add_bookmark
3
+ # ------------------------------------------------------------------------------
4
+ BOOKMARK_ADD_BOOKMARK_SUCCESS = "[Bookmark] Bookmark added successfully."
5
+ BOOKMARK_ADD_BOOKMARK_ERROR = "[Bookmark] Failed to add bookmark record: {message}"
6
+ BOOKMARK_ADD_BOOKMARK_VALIDATION_ERROR = "Error inserting record into database."
7
+
8
+ # ------------------------------------------------------------------------------
9
+ # BOOKMARK - get_bookmark
10
+ # ------------------------------------------------------------------------------
11
+ BOOKMARK_GET_BOOKMARK_ERROR = "[Bookmark] No record found for bookmark name: {message}"
12
+ BOOKMARK_GET_BOOKMARK_ERROR_1 = "[Bookmark] Invalid bookmark name: {message}"
13
+
14
+ # ------------------------------------------------------------------------------
15
+ # BOOKMARK - delete_bookmark
16
+ # ------------------------------------------------------------------------------
17
+ BOOKMARK_DELETE_BOOKMARK_SUCCESS = "[Bookmark] Bookmark record deleted."
18
+ BOOKMARK_DELETE_BOOKMARK_ERROR = (
19
+ "[Bookmark] Failed to delete bookmark record: {message}"
20
+ )
21
+ BOOKMARK_DELETE_BOOKMARK_ERROR_1 = "[Bookmark] Invalid bookmark name: {message}"
22
+
23
+ # ------------------------------------------------------------------------------
24
+ # BOOKMARK - delete_all_bookmark
25
+ # ------------------------------------------------------------------------------
26
+ BOOKMARK_DELETE_ALL_BOOKMARK_SUCCESS = "[Bookmark] All bookmark records deleted."
27
+ BOOKMARK_DELETE_ALL_BOOKMARK_ERROR = (
28
+ "[Bookmark] Failed to delete all bookmark records: {message}"
29
+ )
30
+
31
+ # ------------------------------------------------------------------------------
32
+ # BOOKMARK - export_bookmarks
33
+ # ------------------------------------------------------------------------------
34
+ BOOKMARK_EXPORT_BOOKMARK_ERROR = "[Bookmark] Failed to export bookmarks: {message}"
35
+ BOOKMARK_EXPORT_BOOKMARK_VALIDATION_ERROR = "Export filename must be a non-empty string"
36
+
37
+ # ------------------------------------------------------------------------------
38
+ # BOOKMARK ARGUMENTS - from_tuple_to_dict
39
+ # ------------------------------------------------------------------------------
40
+ BOOKMARK_ARGUMENTS_FROM_TUPLE_TO_DICT_VALIDATION_ERROR = "[BookmarkArguments] Failed to convert to dictionary because of the insufficient number of values" # noqa: E501
@@ -282,7 +282,7 @@ class Runner:
282
282
  logger.error(f"[Runner] Failed to get available runners: {str(e)}")
283
283
  raise e
284
284
 
285
- def close(self) -> None:
285
+ async def close(self) -> None:
286
286
  """
287
287
  Closes the runner instance.
288
288