aiverify-moonshot 0.4.0__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 (163) hide show
  1. aiverify_moonshot-0.4.0.dist-info/METADATA +249 -0
  2. aiverify_moonshot-0.4.0.dist-info/RECORD +163 -0
  3. aiverify_moonshot-0.4.0.dist-info/WHEEL +4 -0
  4. aiverify_moonshot-0.4.0.dist-info/licenses/AUTHORS.md +5 -0
  5. aiverify_moonshot-0.4.0.dist-info/licenses/LICENSE.md +201 -0
  6. aiverify_moonshot-0.4.0.dist-info/licenses/NOTICES.md +3340 -0
  7. moonshot/__init__.py +0 -0
  8. moonshot/__main__.py +198 -0
  9. moonshot/api.py +155 -0
  10. moonshot/integrations/__init__.py +0 -0
  11. moonshot/integrations/cli/__init__.py +0 -0
  12. moonshot/integrations/cli/__main__.py +25 -0
  13. moonshot/integrations/cli/active_session_cfg.py +1 -0
  14. moonshot/integrations/cli/benchmark/__init__.py +0 -0
  15. moonshot/integrations/cli/benchmark/benchmark.py +186 -0
  16. moonshot/integrations/cli/benchmark/cookbook.py +545 -0
  17. moonshot/integrations/cli/benchmark/datasets.py +164 -0
  18. moonshot/integrations/cli/benchmark/metrics.py +141 -0
  19. moonshot/integrations/cli/benchmark/recipe.py +598 -0
  20. moonshot/integrations/cli/benchmark/result.py +216 -0
  21. moonshot/integrations/cli/benchmark/run.py +140 -0
  22. moonshot/integrations/cli/benchmark/runner.py +174 -0
  23. moonshot/integrations/cli/cli.py +64 -0
  24. moonshot/integrations/cli/common/__init__.py +0 -0
  25. moonshot/integrations/cli/common/common.py +72 -0
  26. moonshot/integrations/cli/common/connectors.py +325 -0
  27. moonshot/integrations/cli/common/display_helper.py +42 -0
  28. moonshot/integrations/cli/common/prompt_template.py +94 -0
  29. moonshot/integrations/cli/initialisation/__init__.py +0 -0
  30. moonshot/integrations/cli/initialisation/initialisation.py +14 -0
  31. moonshot/integrations/cli/redteam/__init__.py +0 -0
  32. moonshot/integrations/cli/redteam/attack_module.py +70 -0
  33. moonshot/integrations/cli/redteam/context_strategy.py +147 -0
  34. moonshot/integrations/cli/redteam/prompt_template.py +67 -0
  35. moonshot/integrations/cli/redteam/redteam.py +90 -0
  36. moonshot/integrations/cli/redteam/session.py +467 -0
  37. moonshot/integrations/web_api/.env.dev +7 -0
  38. moonshot/integrations/web_api/__init__.py +0 -0
  39. moonshot/integrations/web_api/__main__.py +56 -0
  40. moonshot/integrations/web_api/app.py +125 -0
  41. moonshot/integrations/web_api/container.py +146 -0
  42. moonshot/integrations/web_api/log/.gitkeep +0 -0
  43. moonshot/integrations/web_api/logging_conf.py +114 -0
  44. moonshot/integrations/web_api/routes/__init__.py +0 -0
  45. moonshot/integrations/web_api/routes/attack_modules.py +66 -0
  46. moonshot/integrations/web_api/routes/benchmark.py +116 -0
  47. moonshot/integrations/web_api/routes/benchmark_result.py +175 -0
  48. moonshot/integrations/web_api/routes/context_strategy.py +129 -0
  49. moonshot/integrations/web_api/routes/cookbook.py +225 -0
  50. moonshot/integrations/web_api/routes/dataset.py +120 -0
  51. moonshot/integrations/web_api/routes/endpoint.py +282 -0
  52. moonshot/integrations/web_api/routes/metric.py +78 -0
  53. moonshot/integrations/web_api/routes/prompt_template.py +128 -0
  54. moonshot/integrations/web_api/routes/recipe.py +219 -0
  55. moonshot/integrations/web_api/routes/redteam.py +609 -0
  56. moonshot/integrations/web_api/routes/runner.py +239 -0
  57. moonshot/integrations/web_api/schemas/__init__.py +0 -0
  58. moonshot/integrations/web_api/schemas/benchmark_runner_dto.py +13 -0
  59. moonshot/integrations/web_api/schemas/cookbook_create_dto.py +19 -0
  60. moonshot/integrations/web_api/schemas/cookbook_response_model.py +9 -0
  61. moonshot/integrations/web_api/schemas/dataset_response_dto.py +9 -0
  62. moonshot/integrations/web_api/schemas/endpoint_create_dto.py +21 -0
  63. moonshot/integrations/web_api/schemas/endpoint_response_model.py +11 -0
  64. moonshot/integrations/web_api/schemas/prompt_response_model.py +14 -0
  65. moonshot/integrations/web_api/schemas/prompt_template_response_model.py +10 -0
  66. moonshot/integrations/web_api/schemas/recipe_create_dto.py +32 -0
  67. moonshot/integrations/web_api/schemas/recipe_response_model.py +7 -0
  68. moonshot/integrations/web_api/schemas/session_create_dto.py +16 -0
  69. moonshot/integrations/web_api/schemas/session_prompt_dto.py +7 -0
  70. moonshot/integrations/web_api/schemas/session_response_model.py +38 -0
  71. moonshot/integrations/web_api/services/__init__.py +0 -0
  72. moonshot/integrations/web_api/services/attack_module_service.py +34 -0
  73. moonshot/integrations/web_api/services/auto_red_team_test_manager.py +86 -0
  74. moonshot/integrations/web_api/services/auto_red_team_test_state.py +57 -0
  75. moonshot/integrations/web_api/services/base_service.py +8 -0
  76. moonshot/integrations/web_api/services/benchmark_result_service.py +25 -0
  77. moonshot/integrations/web_api/services/benchmark_test_manager.py +106 -0
  78. moonshot/integrations/web_api/services/benchmark_test_state.py +56 -0
  79. moonshot/integrations/web_api/services/benchmarking_service.py +31 -0
  80. moonshot/integrations/web_api/services/context_strategy_service.py +22 -0
  81. moonshot/integrations/web_api/services/cookbook_service.py +194 -0
  82. moonshot/integrations/web_api/services/dataset_service.py +20 -0
  83. moonshot/integrations/web_api/services/endpoint_service.py +65 -0
  84. moonshot/integrations/web_api/services/metric_service.py +14 -0
  85. moonshot/integrations/web_api/services/prompt_template_service.py +39 -0
  86. moonshot/integrations/web_api/services/recipe_service.py +155 -0
  87. moonshot/integrations/web_api/services/runner_service.py +147 -0
  88. moonshot/integrations/web_api/services/session_service.py +350 -0
  89. moonshot/integrations/web_api/services/utils/exceptions_handler.py +41 -0
  90. moonshot/integrations/web_api/services/utils/results_formatter.py +47 -0
  91. moonshot/integrations/web_api/status_updater/interface/benchmark_progress_callback.py +14 -0
  92. moonshot/integrations/web_api/status_updater/interface/redteam_progress_callback.py +14 -0
  93. moonshot/integrations/web_api/status_updater/moonshot_ui_webhook.py +72 -0
  94. moonshot/integrations/web_api/types/types.py +99 -0
  95. moonshot/src/__init__.py +0 -0
  96. moonshot/src/api/__init__.py +0 -0
  97. moonshot/src/api/api_connector.py +58 -0
  98. moonshot/src/api/api_connector_endpoint.py +162 -0
  99. moonshot/src/api/api_context_strategy.py +57 -0
  100. moonshot/src/api/api_cookbook.py +160 -0
  101. moonshot/src/api/api_dataset.py +46 -0
  102. moonshot/src/api/api_environment_variables.py +17 -0
  103. moonshot/src/api/api_metrics.py +51 -0
  104. moonshot/src/api/api_prompt_template.py +43 -0
  105. moonshot/src/api/api_recipe.py +182 -0
  106. moonshot/src/api/api_red_teaming.py +59 -0
  107. moonshot/src/api/api_result.py +84 -0
  108. moonshot/src/api/api_run.py +74 -0
  109. moonshot/src/api/api_runner.py +132 -0
  110. moonshot/src/api/api_session.py +290 -0
  111. moonshot/src/configs/__init__.py +0 -0
  112. moonshot/src/configs/env_variables.py +187 -0
  113. moonshot/src/connectors/__init__.py +0 -0
  114. moonshot/src/connectors/connector.py +327 -0
  115. moonshot/src/connectors/connector_prompt_arguments.py +17 -0
  116. moonshot/src/connectors_endpoints/__init__.py +0 -0
  117. moonshot/src/connectors_endpoints/connector_endpoint.py +211 -0
  118. moonshot/src/connectors_endpoints/connector_endpoint_arguments.py +54 -0
  119. moonshot/src/cookbooks/__init__.py +0 -0
  120. moonshot/src/cookbooks/cookbook.py +225 -0
  121. moonshot/src/cookbooks/cookbook_arguments.py +34 -0
  122. moonshot/src/datasets/__init__.py +0 -0
  123. moonshot/src/datasets/dataset.py +255 -0
  124. moonshot/src/datasets/dataset_arguments.py +50 -0
  125. moonshot/src/metrics/__init__.py +0 -0
  126. moonshot/src/metrics/metric.py +192 -0
  127. moonshot/src/metrics/metric_interface.py +95 -0
  128. moonshot/src/prompt_templates/__init__.py +0 -0
  129. moonshot/src/prompt_templates/prompt_template.py +103 -0
  130. moonshot/src/recipes/__init__.py +0 -0
  131. moonshot/src/recipes/recipe.py +340 -0
  132. moonshot/src/recipes/recipe_arguments.py +111 -0
  133. moonshot/src/redteaming/__init__.py +0 -0
  134. moonshot/src/redteaming/attack/__init__.py +0 -0
  135. moonshot/src/redteaming/attack/attack_module.py +618 -0
  136. moonshot/src/redteaming/attack/attack_module_arguments.py +44 -0
  137. moonshot/src/redteaming/attack/context_strategy.py +131 -0
  138. moonshot/src/redteaming/context_strategy/__init__.py +0 -0
  139. moonshot/src/redteaming/context_strategy/context_strategy_interface.py +46 -0
  140. moonshot/src/redteaming/session/__init__.py +0 -0
  141. moonshot/src/redteaming/session/chat.py +209 -0
  142. moonshot/src/redteaming/session/red_teaming_progress.py +128 -0
  143. moonshot/src/redteaming/session/red_teaming_type.py +6 -0
  144. moonshot/src/redteaming/session/session.py +775 -0
  145. moonshot/src/results/__init__.py +0 -0
  146. moonshot/src/results/result.py +119 -0
  147. moonshot/src/results/result_arguments.py +44 -0
  148. moonshot/src/runners/__init__.py +0 -0
  149. moonshot/src/runners/runner.py +476 -0
  150. moonshot/src/runners/runner_arguments.py +46 -0
  151. moonshot/src/runners/runner_type.py +6 -0
  152. moonshot/src/runs/__init__.py +0 -0
  153. moonshot/src/runs/run.py +344 -0
  154. moonshot/src/runs/run_arguments.py +162 -0
  155. moonshot/src/runs/run_progress.py +145 -0
  156. moonshot/src/runs/run_status.py +10 -0
  157. moonshot/src/storage/__init__.py +0 -0
  158. moonshot/src/storage/db_interface.py +128 -0
  159. moonshot/src/storage/io_interface.py +31 -0
  160. moonshot/src/storage/storage.py +525 -0
  161. moonshot/src/utils/__init__.py +0 -0
  162. moonshot/src/utils/import_modules.py +96 -0
  163. moonshot/src/utils/timeit.py +25 -0
@@ -0,0 +1,325 @@
1
+ from ast import literal_eval
2
+
3
+ import cmd2
4
+ from rich.console import Console
5
+ from rich.markup import escape
6
+ from rich.table import Table
7
+
8
+ from moonshot.api import (
9
+ api_create_endpoint,
10
+ api_delete_endpoint,
11
+ api_get_all_connector_type,
12
+ api_get_all_endpoint,
13
+ api_read_endpoint,
14
+ api_update_endpoint,
15
+ )
16
+
17
+ console = Console()
18
+
19
+
20
+ # ------------------------------------------------------------------------------
21
+ # CLI Functions
22
+ # ------------------------------------------------------------------------------
23
+ def add_endpoint(args) -> None:
24
+ """
25
+ Add a new endpoint.
26
+
27
+ This function adds a new endpoint by calling the api_create_endpoint function from the
28
+ moonshot.api module using the endpoint details provided in the args.
29
+
30
+ Args:
31
+ args: A namespace object from argparse. It should have the following attributes:
32
+ name (str): The name of the new endpoint.
33
+ connector_type (str): The type of the connector (e.g., 'GPT-3', 'Bert', etc.).
34
+ uri (str): The URI for the connector's API.
35
+ token (str): The access token for the API.
36
+ max_calls_per_second (int): The maximum number of API calls allowed per second.
37
+ max_concurrency (int): The maximum number of concurrent API calls.
38
+ params (str): A string representation of a dictionary containing additional parameters for the connector.
39
+
40
+ Returns:
41
+ None
42
+ """
43
+ try:
44
+ params_dict = literal_eval(args.params)
45
+
46
+ new_endpoint_id = api_create_endpoint(
47
+ args.name,
48
+ args.connector_type,
49
+ args.uri,
50
+ args.token,
51
+ args.max_calls_per_second,
52
+ args.max_concurrency,
53
+ params_dict,
54
+ )
55
+ print(f"[add_endpoint]: Endpoint ({new_endpoint_id}) created.")
56
+ except Exception as e:
57
+ print(f"[add_endpoint]: {str(e)}")
58
+
59
+
60
+ def list_endpoints() -> None:
61
+ """
62
+ List all endpoints.
63
+
64
+ This function retrieves all endpoints by calling the api_get_all_endpoint function from the
65
+ moonshot.api module. It then displays the endpoints using the display_endpoints function.
66
+
67
+ Returns:
68
+ None
69
+ """
70
+ try:
71
+ endpoint_list = api_get_all_endpoint()
72
+ display_endpoints(endpoint_list)
73
+ except Exception as e:
74
+ print(f"[list_endpoints]: {str(e)}")
75
+
76
+
77
+ def list_connector_types() -> None:
78
+ """
79
+ List all connector types.
80
+
81
+ This function retrieves all connector types by calling the api_get_all_connector_type function from the
82
+ moonshot.api module. It then displays the connector types using the display_connector_types function.
83
+
84
+ Returns:
85
+ None
86
+ """
87
+ try:
88
+ connector_type_list = api_get_all_connector_type()
89
+ display_connector_types(connector_type_list)
90
+ except Exception as e:
91
+ print(f"[list_connector_types]: {str(e)}")
92
+
93
+
94
+ def view_endpoint(args) -> None:
95
+ """
96
+ View a specific endpoint.
97
+
98
+ This function retrieves a specific endpoint by calling the api_read_endpoint function from the
99
+ moonshot.api module using the endpoint name provided in the args. It then displays the endpoint
100
+ information using the display_endpoints function.
101
+
102
+ Args:
103
+ args: A namespace object from argparse. It should have the following attribute:
104
+ endpoint (str): The name of the endpoint to view.
105
+
106
+ Returns:
107
+ None
108
+ """
109
+ try:
110
+ endpoint_info = api_read_endpoint(args.endpoint)
111
+ display_endpoints([endpoint_info])
112
+ except Exception as e:
113
+ print(f"[view_endpoint]: {str(e)}")
114
+
115
+
116
+ def update_endpoint(args) -> None:
117
+ """
118
+ Update a specific endpoint.
119
+
120
+ This function updates a specific endpoint by calling the api_update_endpoint function from the
121
+ moonshot.api module using the endpoint name and update values provided in the args.
122
+
123
+ Args:
124
+ args: A namespace object from argparse. It should have the following attributes:
125
+ endpoint (str): The name of the endpoint to update.
126
+ update_kwargs (str): A string representation of a dictionary. Each key-value pair in the dictionary
127
+ represents a field to update in the endpoint and the new value for that field.
128
+
129
+ Returns:
130
+ None
131
+ """
132
+ try:
133
+ endpoint = args.endpoint
134
+ update_values = dict(literal_eval(args.update_kwargs))
135
+ api_update_endpoint(endpoint, **update_values)
136
+ print("[update_endpoint]: Endpoint updated.")
137
+ except Exception as e:
138
+ print(f"[update_endpoint]: {str(e)}")
139
+
140
+
141
+ def delete_endpoint(args) -> None:
142
+ """
143
+ Delete a specific endpoint.
144
+
145
+ This function deletes a specific endpoint by calling the api_delete_endpoint function from the
146
+ moonshot.api module using the endpoint name provided in the args. Before deletion, it asks for
147
+ user confirmation. If the user confirms, the endpoint is deleted; otherwise, the deletion is cancelled.
148
+
149
+ Args:
150
+ args: A namespace object from argparse. It should have the following attribute:
151
+ endpoint (str): The name of the endpoint to delete.
152
+
153
+ Returns:
154
+ None
155
+ """
156
+ # Confirm with the user before deleting an endpoint
157
+ confirmation = console.input(
158
+ "[bold red]Are you sure you want to delete the endpoint (y/N)? [/]"
159
+ )
160
+ if confirmation.lower() != "y":
161
+ console.print("[bold yellow]Endpoint deletion cancelled.[/]")
162
+ return
163
+ try:
164
+ api_delete_endpoint(args.endpoint)
165
+ print("[delete_endpoint]: Endpoint deleted.")
166
+ except Exception as e:
167
+ print(f"[delete_endpoint]: {str(e)}")
168
+
169
+
170
+ # ------------------------------------------------------------------------------
171
+ # Helper functions: Display on cli
172
+ # ------------------------------------------------------------------------------
173
+ def display_connector_types(connector_types):
174
+ """
175
+ Display a list of connector types.
176
+
177
+ This function takes a list of connector types and displays them in a table format. If the list is empty, it prints a
178
+ message indicating that no connector types were found.
179
+
180
+ Args:
181
+ connector_types (list): A list of connector types.
182
+
183
+ Returns:
184
+ None
185
+ """
186
+ if connector_types:
187
+ table = Table(
188
+ title="List of Connector Types",
189
+ show_lines=True,
190
+ expand=True,
191
+ header_style="bold",
192
+ )
193
+ table.add_column("No.", width=2)
194
+ table.add_column("Connector Type", justify="left", width=78)
195
+ for connector_id, connector_type in enumerate(connector_types, 1):
196
+ table.add_section()
197
+ table.add_row(str(connector_id), connector_type)
198
+ console.print(table)
199
+ else:
200
+ console.print("[red]There are no connector types found.[/red]")
201
+
202
+
203
+ def display_endpoints(endpoints_list):
204
+ """
205
+ Display a list of endpoints.
206
+
207
+ This function takes a list of endpoints and displays them in a table format. If the list is empty, it prints a
208
+ message indicating that no endpoints were found.
209
+
210
+ Args:
211
+ endpoints_list (list): A list of endpoints. Each endpoint is a dictionary with keys 'id', 'name',
212
+ 'connector_type', 'uri', 'token', 'max_calls_per_second', 'max_concurrency', 'params', and 'created_date'.
213
+
214
+ Returns:
215
+ None
216
+ """
217
+ if endpoints_list:
218
+ table = Table(
219
+ title="List of Connector Endpoints",
220
+ show_lines=True,
221
+ expand=True,
222
+ header_style="bold",
223
+ )
224
+ table.add_column("No.", justify="left", width=2)
225
+ table.add_column("Id", justify="left", width=10)
226
+ table.add_column("Name", justify="left", width=10)
227
+ table.add_column("Connector Type", justify="left", width=10)
228
+ table.add_column("Uri", justify="left", width=10)
229
+ table.add_column("Token", justify="left", width=10)
230
+ table.add_column("Max Calls Per Second", justify="left", width=5)
231
+ table.add_column("Max concurrency", justify="left", width=5)
232
+ table.add_column("Params", justify="left", width=30)
233
+ table.add_column("Created Date", justify="left", width=8)
234
+
235
+ for endpoint_id, endpoint in enumerate(endpoints_list, 1):
236
+ (
237
+ id,
238
+ name,
239
+ connector_type,
240
+ uri,
241
+ token,
242
+ max_calls_per_second,
243
+ max_concurrency,
244
+ params,
245
+ created_date,
246
+ ) = endpoint.values()
247
+ table.add_section()
248
+ table.add_row(
249
+ str(endpoint_id),
250
+ id,
251
+ name,
252
+ connector_type,
253
+ uri,
254
+ token,
255
+ str(max_calls_per_second),
256
+ str(max_concurrency),
257
+ escape(str(params)),
258
+ created_date,
259
+ )
260
+ console.print(table)
261
+ else:
262
+ console.print("[red]There are no endpoints found.[/red]")
263
+
264
+
265
+ # ------------------------------------------------------------------------------
266
+ # Cmd2 Arguments Parsers
267
+ # ------------------------------------------------------------------------------
268
+ # Add endpoint arguments
269
+ add_endpoint_args = cmd2.Cmd2ArgumentParser(
270
+ description="Add a new endpoint. The 'name' argument will be slugified to create a unique identifier.",
271
+ epilog="Example:\n add_endpoint openai-connector 'OpenAI GPT3.5 Turbo 1106' "
272
+ "MY_URI ADD_YOUR_TOKEN_HERE 1 1 \"{'temperature': 0.5, 'model': 'gpt-3.5-turbo-1106'}\"",
273
+ )
274
+ add_endpoint_args.add_argument(
275
+ "connector_type",
276
+ type=str,
277
+ help="Type of connection for the endpoint",
278
+ )
279
+ add_endpoint_args.add_argument("name", type=str, help="Name of the new endpoint")
280
+ add_endpoint_args.add_argument("uri", type=str, help="URI of the new endpoint")
281
+ add_endpoint_args.add_argument("token", type=str, help="Token of the new endpoint")
282
+ add_endpoint_args.add_argument(
283
+ "max_calls_per_second",
284
+ type=int,
285
+ help="Max calls per second of the new endpoint",
286
+ )
287
+ add_endpoint_args.add_argument(
288
+ "max_concurrency", type=int, help="Max concurrency of the new endpoint"
289
+ )
290
+ add_endpoint_args.add_argument("params", type=str, help="Params of the new endpoint")
291
+
292
+ # Update endpoint arguments
293
+ update_endpoint_args = cmd2.Cmd2ArgumentParser(
294
+ description="Update an endpoint.",
295
+ epilog=(
296
+ "Available keys:\n"
297
+ " name: name of the endpoint\n"
298
+ " uri: URI of the endpoint\n"
299
+ " token: Token of the endpoint\n"
300
+ " max_calls_per_second: Rate limit for max calls per second\n"
301
+ " max_concurrency: Rate limit for max concurrency\n"
302
+ " params: Extra arguments for the endpoint\n\n"
303
+ "Example:\n"
304
+ " update_endpoint openai-gpt4 \"[('name', 'my-special-openai-endpoint'), "
305
+ "('uri', 'my-uri-loc'), ('token', 'my-token-here')]\""
306
+ ),
307
+ )
308
+ update_endpoint_args.add_argument("endpoint", type=str, help="ID of the endpoint. This field is not editable via CLI after creation.")
309
+ update_endpoint_args.add_argument(
310
+ "update_kwargs", type=str, help="Update endpoint key/value"
311
+ )
312
+
313
+ # View endpoint arguments
314
+ view_endpoint_args = cmd2.Cmd2ArgumentParser(
315
+ description="View an endpoint.",
316
+ epilog="Example:\n view_endpoint openai-gpt4",
317
+ )
318
+ view_endpoint_args.add_argument("endpoint", type=str, help="ID of the endpoint")
319
+
320
+ # Delete endpoint arguments
321
+ delete_endpoint_args = cmd2.Cmd2ArgumentParser(
322
+ description="Delete an endpoint.",
323
+ epilog="Example:\n delete_endpoint openai-gpt4",
324
+ )
325
+ delete_endpoint_args.add_argument("endpoint", type=str, help="ID of the endpoint")
@@ -0,0 +1,42 @@
1
+ def display_view_list_format(title: str, items: list) -> str:
2
+ """
3
+ Format a list of items for display.
4
+
5
+ This function takes a title and a list of items and formats them into a string suitable for display.
6
+ Each item in the list is displayed on a new line with an index number. If the list is empty, it returns
7
+ the title with 'nil'.
8
+
9
+ Args:
10
+ title (str): The title to display above the list.
11
+ items (list): A list of items to be formatted.
12
+
13
+ Returns:
14
+ str: The formatted list as a string.
15
+ """
16
+ if items:
17
+ return f"[blue]{title}[/blue]:" + "".join(
18
+ f"\n{i + 1}. {item}" for i, item in enumerate(items)
19
+ )
20
+ else:
21
+ return f"[blue]{title}[/blue]: nil"
22
+
23
+
24
+ def display_view_str_format(title: str, item: str) -> str:
25
+ """
26
+ Format a string item for display with a title.
27
+
28
+ This function takes a title and a string item and formats them into a string suitable for display.
29
+ If the item is not an empty string, it is displayed next to the title with a blue color for the title.
30
+ If the item is an empty string, 'nil' is displayed next to the title.
31
+
32
+ Args:
33
+ title (str): The title to display next to the item.
34
+ item (str): The string item to be formatted.
35
+
36
+ Returns:
37
+ str: The formatted string with the title and item.
38
+ """
39
+ if item:
40
+ return f"[blue]{title}[/blue]: {item}"
41
+ else:
42
+ return f"[blue]{title}[/blue]: nil"
@@ -0,0 +1,94 @@
1
+ import cmd2
2
+ from rich.console import Console
3
+ from rich.table import Table
4
+
5
+ from moonshot.api import api_delete_prompt_template, api_get_all_prompt_template_detail
6
+
7
+ console = Console()
8
+
9
+
10
+ # ------------------------------------------------------------------------------
11
+ # CLI Functions
12
+ # ------------------------------------------------------------------------------
13
+ def list_prompt_templates() -> None:
14
+ """
15
+ List all prompt templates available.
16
+ """
17
+ try:
18
+ prompt_templates = api_get_all_prompt_template_detail()
19
+ display_prompt_templates(prompt_templates)
20
+ except Exception as e:
21
+ print(f"[list_prompt_templates]: {str(e)}")
22
+
23
+
24
+ def delete_prompt_template(args) -> None:
25
+ """
26
+ Deletes a prompt_template after confirming with the user.
27
+
28
+ Args:
29
+ args (object): The arguments object. It should have a 'prompt_template' attribute
30
+ which is the ID of the prompt template to delete.
31
+ """
32
+ # Confirm with the user before deleting a prompt template
33
+ confirmation = console.input(
34
+ "[bold red]Are you sure you want to delete the prompt template (y/N)? [/]"
35
+ )
36
+ if confirmation.lower() != "y":
37
+ console.print("[bold yellow]Prompt template deletion cancelled.[/]")
38
+ return
39
+ try:
40
+ api_delete_prompt_template(args.prompt_template)
41
+ print("[delete_prompt_template]: Prompt template deleted.")
42
+ except Exception as e:
43
+ print(f"[delete_prompt_template]: {str(e)}")
44
+
45
+
46
+ # ------------------------------------------------------------------------------
47
+ # Helper functions: Display on cli
48
+ # ------------------------------------------------------------------------------
49
+ def display_prompt_templates(prompt_templates) -> None:
50
+ """
51
+ Display the list of prompt templates in a formatted table.
52
+
53
+ This function takes a list of prompt templates and displays them in a formatted table.
54
+ Each row in the table represents a prompt template with its ID, name, description, and contents.
55
+ If the list of prompt templates is empty, it prints a message indicating that no prompt templates were found.
56
+
57
+ Args:
58
+ prompt_templates (list): A list of dictionaries, each representing a prompt template.
59
+ """
60
+ table = Table(
61
+ title="List of Prompt Templates",
62
+ show_lines=True,
63
+ expand=True,
64
+ header_style="bold",
65
+ )
66
+ table.add_column("No.", width=2)
67
+ table.add_column("Prompt Template", justify="left", width=50)
68
+ table.add_column("Contains", justify="left", width=48, overflow="fold")
69
+ if prompt_templates:
70
+ for prompt_index, prompt_template in enumerate(prompt_templates, 1):
71
+ (
72
+ id,
73
+ name,
74
+ description,
75
+ contents,
76
+ ) = prompt_template.values()
77
+
78
+ prompt_info = f"[red]id: {id}[/red]\n\n[blue]{name}[/blue]\n{description}"
79
+ table.add_section()
80
+ table.add_row(str(prompt_index), prompt_info, contents)
81
+ console.print(table)
82
+ else:
83
+ console.print("[red]There are no prompt templates found.[/red]")
84
+
85
+
86
+ # Delete prompt template arguments
87
+ delete_prompt_template_args = cmd2.Cmd2ArgumentParser(
88
+ description="Delete a prompt template.",
89
+ epilog="Example:\n delete_prompt_template squad-shifts",
90
+ )
91
+
92
+ delete_prompt_template_args.add_argument(
93
+ "prompt_template", type=str, help="The ID of the prompt template to delete"
94
+ )
File without changes
@@ -0,0 +1,14 @@
1
+ import cmd2
2
+
3
+
4
+ @cmd2.with_default_category("Initialisation")
5
+ class InitialisationCommandSet(cmd2.CommandSet):
6
+ def __init__(self):
7
+ super().__init__()
8
+
9
+ def do_interactive(self, _: cmd2.Statement) -> None:
10
+ """
11
+ Run the interactive shell.
12
+ """
13
+ # To prevent 'interactive is not a recognized command, alias, or macro' from triggering.
14
+ pass
File without changes
@@ -0,0 +1,70 @@
1
+ import cmd2
2
+ from rich.console import Console
3
+ from rich.table import Table
4
+
5
+ from moonshot.api import api_delete_attack_module, api_get_all_attack_module_metadata
6
+
7
+ console = Console()
8
+
9
+
10
+ def list_attack_modules() -> None:
11
+ """
12
+ Retrieves and prints the metadata of all attack modules.
13
+ """
14
+ print("Listing attack modules may take a while...")
15
+ attack_module_metadata_list = api_get_all_attack_module_metadata()
16
+
17
+ if attack_module_metadata_list:
18
+ table = Table(
19
+ title="Attack Module List",
20
+ show_lines=True,
21
+ expand=True,
22
+ header_style="bold",
23
+ )
24
+ table.add_column("No.", width=2)
25
+ table.add_column("Details", justify="left", width=98)
26
+
27
+ for attack_module_index, attack_module_data in enumerate(
28
+ attack_module_metadata_list, 1
29
+ ):
30
+ attack_module_data_str = ""
31
+ for k, v in attack_module_data.items():
32
+ attack_module_data_str += f"[blue]{k.capitalize()}:[/blue] {v}\n\n"
33
+ table.add_row(str(attack_module_index), attack_module_data_str)
34
+
35
+ console.print(table)
36
+ else:
37
+ console.print("[red]There are no attack modules found.[/red]", style="bold")
38
+
39
+
40
+ def delete_attack_module(args) -> None:
41
+ """
42
+ Deletes an attack module after confirming with the user.
43
+
44
+ Args:
45
+ args (object): The arguments object. It should have a 'attack_modulee' attribute
46
+ which is the ID of the attack module to delete.
47
+ """
48
+ # Confirm with the user before deleting an attack module
49
+ confirmation = console.input(
50
+ "[bold red]Are you sure you want to delete the attack module (y/N)? [/]"
51
+ )
52
+ if confirmation.lower() != "y":
53
+ console.print("[bold yellow]Attack module deletion cancelled.[/]")
54
+ return
55
+ try:
56
+ api_delete_attack_module(args.attack_module)
57
+ print("[delete_attack_module]: Attack module deleted.")
58
+ except Exception as e:
59
+ print(f"[delete_attack_module]: {str(e)}")
60
+
61
+
62
+ # Delete attack module arguments
63
+ delete_attack_module_args = cmd2.Cmd2ArgumentParser(
64
+ description="Delete an attack module.",
65
+ epilog="Example:\n delete_attack_module sample_attack_module",
66
+ )
67
+
68
+ delete_attack_module_args.add_argument(
69
+ "attack_module", type=str, help="The ID of the attack module to delete"
70
+ )