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,106 @@
1
+ import asyncio
2
+ import uuid
3
+ from typing import Any
4
+
5
+ from dependency_injector.wiring import inject
6
+
7
+ from moonshot.src.runners.runner import Runner
8
+
9
+ from ..schemas.benchmark_runner_dto import BenchmarkRunnerDTO
10
+ from ..services.base_service import BaseService
11
+ from ..services.benchmark_test_state import BenchmarkTestState
12
+ from ..services.runner_service import RunnerService
13
+ from ..status_updater.interface.benchmark_progress_callback import (
14
+ InterfaceBenchmarkProgressCallback,
15
+ )
16
+ from ..types.types import BenchmarkCollectionType, TestRunProgress
17
+
18
+
19
+ class BenchmarkTestManager(BaseService):
20
+ @inject
21
+ def __init__(
22
+ self,
23
+ benchmark_test_state: BenchmarkTestState,
24
+ progress_status_updater: InterfaceBenchmarkProgressCallback,
25
+ runner_service: RunnerService,
26
+ ) -> None:
27
+ self.benchmark_test_state = benchmark_test_state
28
+ self.progress_status_updater = progress_status_updater
29
+ self.runner_service = runner_service
30
+ super().__init__()
31
+
32
+ def generate_unique_task_id(self) -> str:
33
+ unique_id = str(uuid.uuid4())
34
+ return f"task_{unique_id}"
35
+
36
+ def add_task(
37
+ self, executor_id: str, task: asyncio.Task[Any], moonshot_runner: Runner
38
+ ) -> None:
39
+ self.benchmark_test_state.add_task(executor_id, task, moonshot_runner)
40
+
41
+ def remove_task(self, executor_id: str) -> None:
42
+ self.benchmark_test_state.remove_task(executor_id)
43
+
44
+ async def cancel_task(self, executor_id: str) -> None:
45
+ await self.benchmark_test_state.cancel_task(executor_id)
46
+
47
+ def update_progress_status(self, updates: TestRunProgress):
48
+ self.benchmark_test_state.update_progress_status(updates)
49
+
50
+ def on_task_completed(self, task: asyncio.Task[Any]) -> None:
51
+ self.logger.debug(f"Task {task.get_name()} has completed")
52
+
53
+ async def run_test(
54
+ self,
55
+ benchmark_input_data: BenchmarkRunnerDTO,
56
+ benchmark_type: BenchmarkCollectionType,
57
+ moonshot_runner: Runner,
58
+ ) -> None:
59
+ try:
60
+ if benchmark_type == BenchmarkCollectionType.COOKBOOK:
61
+ async_run = moonshot_runner.run_cookbooks(
62
+ cookbooks=benchmark_input_data.inputs,
63
+ num_of_prompts=benchmark_input_data.num_of_prompts,
64
+ random_seed=benchmark_input_data.random_seed,
65
+ system_prompt=benchmark_input_data.system_prompt,
66
+ )
67
+ else:
68
+ async_run = moonshot_runner.run_recipes(
69
+ recipes=benchmark_input_data.inputs,
70
+ num_of_prompts=benchmark_input_data.num_of_prompts,
71
+ random_seed=benchmark_input_data.random_seed,
72
+ system_prompt=benchmark_input_data.system_prompt,
73
+ )
74
+ except Exception as e:
75
+ self.logger.error(f"Failed to execute benchmark - {e}")
76
+ raise Exception(f"Unexpected error in core library - {e}")
77
+
78
+ await async_run
79
+ async_run.close()
80
+
81
+ async def schedule_test_task(
82
+ self, input_data: BenchmarkRunnerDTO, benchmark_type: BenchmarkCollectionType
83
+ ) -> str:
84
+ task_id = self.generate_unique_task_id()
85
+ runner = self.runner_service.create_runner(
86
+ input_data.run_name,
87
+ input_data.endpoints,
88
+ input_data.description,
89
+ self.progress_status_updater.on_progress_update,
90
+ )
91
+ benchmark_coroutine = self.run_test(input_data, benchmark_type, runner)
92
+
93
+ task = asyncio.create_task(benchmark_coroutine, name=task_id)
94
+
95
+ def on_executor_completion(task: asyncio.Task[Any]):
96
+ if task.exception():
97
+ self.logger.error(
98
+ f"Executor {task.get_name()} has failed - {task.exception()}"
99
+ )
100
+ else:
101
+ self.logger.debug(f"Executor {task.get_name()} has completed")
102
+
103
+ task.add_done_callback(on_executor_completion)
104
+
105
+ self.add_task(runner.id, task, runner)
106
+ return runner.id
@@ -0,0 +1,56 @@
1
+ import asyncio
2
+ from typing import Any, TypedDict
3
+
4
+ from moonshot.integrations.web_api.services.base_service import BaseService
5
+ from moonshot.integrations.web_api.types.types import TestRunProgress
6
+ from moonshot.src.runners.runner import Runner
7
+
8
+
9
+ class BenchmarkTaskInfo(TypedDict):
10
+ async_task: asyncio.Task[Any]
11
+ moonshot_runner: Runner
12
+ status: TestRunProgress | None
13
+
14
+
15
+ class BenchmarkTestState(BaseService):
16
+ state: dict[str, BenchmarkTaskInfo] = {}
17
+
18
+ def add_task(
19
+ self, id: str, task: asyncio.Task[Any], moonshot_runner: Runner
20
+ ) -> None:
21
+ self.state[id] = {
22
+ "async_task": task,
23
+ "moonshot_runner": moonshot_runner,
24
+ "status": None,
25
+ }
26
+
27
+ def remove_task(self, id: str) -> BenchmarkTaskInfo:
28
+ return self.state.pop(id)
29
+
30
+ async def cancel_task(self, id: str) -> None:
31
+ task_info = self.state[id]
32
+ if task_info and not task_info["async_task"].done():
33
+ if task_info["moonshot_runner"]:
34
+ await task_info["moonshot_runner"].cancel()
35
+ task_info["async_task"].cancel()
36
+ self.logger.debug(f"Task {id} has been cancelled")
37
+ else:
38
+ self.logger.debug(f"Task {id} is already completed or does not exist.")
39
+
40
+ def update_progress_status(self, updates: TestRunProgress) -> None:
41
+ self.state[updates["current_runner_id"]]["status"] = updates
42
+
43
+ def get_state(self) -> dict[str, BenchmarkTaskInfo]:
44
+ return self.state
45
+
46
+ def get_progress_status(self, id: str) -> TestRunProgress | None:
47
+ if id in self.state:
48
+ return self.state[id]["status"]
49
+ return None
50
+
51
+ def get_all_progress_status(self) -> dict[str, TestRunProgress]:
52
+ return {
53
+ id: task_info["status"]
54
+ for id, task_info in self.state.items()
55
+ if task_info["status"] is not None
56
+ }
@@ -0,0 +1,31 @@
1
+ from dependency_injector.wiring import inject
2
+
3
+ from ..schemas.benchmark_runner_dto import BenchmarkRunnerDTO
4
+ from ..services.base_service import BaseService
5
+ from ..services.benchmark_test_manager import BenchmarkTestManager
6
+ from ..services.utils.exceptions_handler import exception_handler
7
+ from ..types.types import BenchmarkCollectionType
8
+
9
+
10
+ class BenchmarkingService(BaseService):
11
+ @inject
12
+ def __init__(self, benchmark_test_manager: BenchmarkTestManager) -> None:
13
+ self.benchmark_test_manager = benchmark_test_manager
14
+
15
+ @exception_handler
16
+ async def execute_cookbook(self, cookbook_executor_data: BenchmarkRunnerDTO) -> str:
17
+ id = await self.benchmark_test_manager.schedule_test_task(
18
+ cookbook_executor_data, BenchmarkCollectionType.COOKBOOK
19
+ )
20
+ return id
21
+
22
+ @exception_handler
23
+ async def execute_recipe(self, recipe_executor_data: BenchmarkRunnerDTO):
24
+ id = await self.benchmark_test_manager.schedule_test_task(
25
+ recipe_executor_data, BenchmarkCollectionType.RECIPE
26
+ )
27
+ return id
28
+
29
+ @exception_handler
30
+ async def cancel_executor(self, executor_id: str) -> None:
31
+ await self.benchmark_test_manager.cancel_task(executor_id)
@@ -0,0 +1,22 @@
1
+ from typing import Any
2
+
3
+ from .... import api as moonshot_api
4
+ from ..services.utils.exceptions_handler import exception_handler
5
+ from .base_service import BaseService
6
+
7
+
8
+ class ContextStrategyService(BaseService):
9
+
10
+ @exception_handler
11
+ def get_ctx_strategy(self) -> list[dict]:
12
+ strategies = moonshot_api.api_get_all_context_strategy_metadata()
13
+ return strategies
14
+
15
+ @exception_handler
16
+ def get_ctx_strategy_name(self) -> list[str]:
17
+ strategies = moonshot_api.api_get_all_context_strategies()
18
+ return strategies
19
+
20
+ @exception_handler
21
+ def delete_ctx_strategy(self, ctx_strategy_name: str) -> None:
22
+ moonshot_api.api_delete_context_strategy(ctx_strategy_name)
@@ -0,0 +1,194 @@
1
+ from moonshot.src.cookbooks.cookbook_arguments import CookbookArguments as Cookbook
2
+ from moonshot.src.recipes.recipe_arguments import RecipeArguments as Recipe
3
+
4
+ from .... import api as moonshot_api
5
+ from ..schemas.cookbook_create_dto import CookbookCreateDTO, CookbookUpdateDTO
6
+ from ..schemas.cookbook_response_model import CookbookResponseModel
7
+ from ..services.base_service import BaseService
8
+ from ..services.recipe_service import get_total_prompt_in_recipe
9
+ from ..services.utils.exceptions_handler import exception_handler
10
+
11
+
12
+ class CookbookService(BaseService):
13
+ @exception_handler
14
+ def create_cookbook(self, cookbook_data: CookbookCreateDTO) -> None:
15
+ """
16
+ Create a new cookbook with the given data.
17
+
18
+ Args:
19
+ cookbook_data (CookbookCreateDTO): Data transfer object containing cookbook details.
20
+ """
21
+ moonshot_api.api_create_cookbook(
22
+ name=cookbook_data.name,
23
+ description=cookbook_data.description,
24
+ recipes=cookbook_data.recipes,
25
+ )
26
+
27
+ @exception_handler
28
+ def get_all_cookbooks(
29
+ self,
30
+ tags: str,
31
+ categories: str,
32
+ count: bool,
33
+ ids: str | None = None,
34
+ categories_excluded: str | None = None,
35
+ ) -> list[CookbookResponseModel]:
36
+ """
37
+ Retrieve all cookbooks, optionally filtered by tags and categories, and with prompt counts.
38
+
39
+ Args:
40
+ ids (str): Filter cookbooks by IDs.
41
+ tags (str): Filter cookbooks by tags.
42
+ categories (str): Filter cookbooks by categories.
43
+ count (bool): Include the total prompt count in each cookbook.
44
+
45
+ Returns:
46
+ list[CookbookResponseModel]: A list of cookbook response models.
47
+ """
48
+ cookbooks_list: list[CookbookResponseModel] = []
49
+
50
+ if ids:
51
+ cookbook_ids = ids.split(",")
52
+ cookbooks = [
53
+ moonshot_api.api_read_cookbook(cookbook_id)
54
+ for cookbook_id in cookbook_ids
55
+ ]
56
+ else:
57
+ cookbooks = moonshot_api.api_get_all_cookbook()
58
+
59
+ for cookbook_dict in cookbooks:
60
+ cookbook = CookbookResponseModel(**cookbook_dict)
61
+
62
+ if not tags and not categories:
63
+ if cookbook not in cookbooks_list:
64
+ cookbooks_list.append(cookbook)
65
+ if count:
66
+ cookbook.total_prompt_in_cookbook = (
67
+ get_total_prompt_in_cookbook(cookbook)
68
+ )
69
+
70
+ if tags and cookbooks_recipe_has_tags(tags, cookbook):
71
+ if cookbook not in cookbooks_list:
72
+ cookbooks_list.append(cookbook)
73
+ if count:
74
+ cookbook.total_prompt_in_cookbook = (
75
+ get_total_prompt_in_cookbook(cookbook)
76
+ )
77
+
78
+ if categories and cookbooks_recipe_has_categories(categories, cookbook):
79
+ if cookbook not in cookbooks_list:
80
+ cookbooks_list.append(cookbook)
81
+ if count:
82
+ cookbook.total_prompt_in_cookbook = (
83
+ get_total_prompt_in_cookbook(cookbook)
84
+ )
85
+
86
+ if categories_excluded and cookbooks_recipe_has_categories(
87
+ categories_excluded, cookbook
88
+ ):
89
+ cookbooks_list.remove(cookbook)
90
+
91
+ return cookbooks_list
92
+
93
+ @exception_handler
94
+ def get_all_cookbooks_names(self) -> list[str]:
95
+ """
96
+ Retrieve the names of all cookbooks.
97
+
98
+ Returns:
99
+ list[str]: A list of cookbook names.
100
+ """
101
+ cookbooks = moonshot_api.api_get_all_cookbook_name()
102
+ return cookbooks
103
+
104
+ @exception_handler
105
+ def update_cookbook(
106
+ self, cookbook_data: CookbookUpdateDTO, cookbook_id: str
107
+ ) -> None:
108
+ """
109
+ Update an existing cookbook with new data.
110
+
111
+ Args:
112
+ cookbook_data (CookbookCreateDTO): Data transfer object containing new cookbook details.
113
+ cookbook_id (str): The ID of the cookbook to update.
114
+ """
115
+ update_data = {
116
+ k: v
117
+ for k, v in cookbook_data.to_dict().items()
118
+ if v is not None and k != "id"
119
+ }
120
+ moonshot_api.api_update_cookbook(cb_id=cookbook_id, **update_data)
121
+
122
+ @exception_handler
123
+ def delete_cookbook(self, cookbook_id: str) -> None:
124
+ """
125
+ Delete a cookbook by its ID.
126
+
127
+ Args:
128
+ cookbook_id (str): The ID of the cookbook to delete.
129
+ """
130
+ moonshot_api.api_delete_cookbook(cookbook_id)
131
+
132
+
133
+ @staticmethod
134
+ def get_total_prompt_in_cookbook(cookbook: Cookbook) -> int:
135
+ """
136
+ Calculate the total number of prompts in a cookbook.
137
+
138
+ This function sums up the total prompts for each recipe in the cookbook.
139
+
140
+ Args:
141
+ cookbook (Cookbook): The cookbook object containing the recipe IDs.
142
+
143
+ Returns:
144
+ int: The total count of prompts within the cookbook.
145
+ """
146
+ recipes = moonshot_api.api_read_recipes(cookbook.recipes)
147
+ return sum(get_total_prompt_in_recipe(Recipe(**recipe)) for recipe in recipes)
148
+
149
+
150
+ @staticmethod
151
+ def cookbooks_recipe_has_tags(tags: str, cookbook: Cookbook) -> bool:
152
+ """
153
+ Check if any recipe in a cookbook has the specified tags.
154
+
155
+ Args:
156
+ tags (str): The tags to check for in the cookbook's recipes.
157
+ cookbook (Cookbook): The cookbook object containing the recipe IDs.
158
+
159
+ Returns:
160
+ bool: True if any recipe in the cookbook has the specified tags, False otherwise.
161
+ """
162
+ recipe_ids = cookbook.recipes
163
+ recipes = moonshot_api.api_read_recipes(recipe_ids)
164
+ for recipe in recipes:
165
+ recipe = Recipe(**recipe)
166
+ if tags in recipe.tags:
167
+ return True
168
+ return False
169
+
170
+
171
+ @staticmethod
172
+ def cookbooks_recipe_has_categories(categories: str, cookbook: Cookbook) -> bool:
173
+ """
174
+ Check if any recipe in a cookbook has the specified categories.
175
+
176
+ Args:
177
+ categories (str): The categories to check for in the cookbook's recipes.
178
+ cookbook (Cookbook): The cookbook object containing the recipe IDs.
179
+ exclude_categories (str): The categories to exclude
180
+
181
+ Returns:
182
+ bool: True if any recipe in the cookbook has the specified categories, False otherwise.
183
+ """
184
+ recipe_ids = cookbook.recipes
185
+ categories_list = [category.lower() for category in categories.split(",")]
186
+ recipes = moonshot_api.api_read_recipes(recipe_ids)
187
+ for recipe in recipes:
188
+ recipe = Recipe(**recipe)
189
+ if any(
190
+ category in [rcat.lower() for rcat in recipe.categories]
191
+ for category in categories_list
192
+ ):
193
+ return True
194
+ return False
@@ -0,0 +1,20 @@
1
+ from .... import api as moonshot_api
2
+ from ..schemas.dataset_response_dto import DatasetResponseDTO
3
+ from ..services.base_service import BaseService
4
+ from ..services.utils.exceptions_handler import exception_handler
5
+
6
+
7
+ class DatasetService(BaseService):
8
+ @exception_handler
9
+ def get_all_datasets(self) -> list[DatasetResponseDTO]:
10
+ datasets = moonshot_api.api_get_all_datasets()
11
+ return [DatasetResponseDTO.model_validate(dataset) for dataset in datasets]
12
+
13
+ @exception_handler
14
+ def get_all_datasets_name(self) -> list[str] | None:
15
+ datasets = moonshot_api.api_get_all_datasets_name()
16
+ return datasets
17
+
18
+ @exception_handler
19
+ def delete_dataset(self, dataset_id: str) -> None:
20
+ moonshot_api.api_delete_dataset(dataset_id)
@@ -0,0 +1,65 @@
1
+ from .... import api as moonshot_api
2
+ from ..schemas.endpoint_create_dto import EndpointUpdateDTO
3
+ from ..schemas.endpoint_response_model import EndpointDataModel
4
+ from .base_service import BaseService
5
+ from .utils.exceptions_handler import exception_handler
6
+
7
+
8
+ class EndpointService(BaseService):
9
+ @exception_handler
10
+ def add_endpoint(self, endpoint_data: EndpointDataModel) -> None:
11
+ moonshot_api.api_create_endpoint(
12
+ name=endpoint_data.name,
13
+ connector_type=endpoint_data.connector_type,
14
+ uri=endpoint_data.uri,
15
+ token=endpoint_data.token,
16
+ max_calls_per_second=endpoint_data.max_calls_per_second,
17
+ max_concurrency=endpoint_data.max_concurrency,
18
+ params=endpoint_data.params,
19
+ )
20
+
21
+ @exception_handler
22
+ def get_all_endpoints(self) -> list[EndpointDataModel | None]:
23
+ filtered_endpoints = []
24
+ endpoints = moonshot_api.api_get_all_endpoint()
25
+ for endpoint in endpoints:
26
+ filtered_endpoints.append(EndpointDataModel.model_validate(endpoint))
27
+
28
+ filtered_endpoints.sort(
29
+ key=lambda endpoint: endpoint.created_date, reverse=True
30
+ )
31
+
32
+ return [
33
+ EndpointDataModel.model_validate(endpoint)
34
+ for endpoint in filtered_endpoints
35
+ ]
36
+
37
+ @exception_handler
38
+ def get_endpoint(self, endpoint_id: str) -> EndpointDataModel | None:
39
+ endpoint = moonshot_api.api_read_endpoint(endpoint_id)
40
+ return EndpointDataModel.model_validate(endpoint)
41
+
42
+ @exception_handler
43
+ def get_all_endpoints_names(self) -> list[str]:
44
+ endpoints_names = moonshot_api.api_get_all_endpoint_name()
45
+ return endpoints_names
46
+
47
+ @exception_handler
48
+ def update_endpoint(
49
+ self, endpoint_id: str, endpoint_data: EndpointUpdateDTO
50
+ ) -> None:
51
+ update_data = {
52
+ k: v
53
+ for k, v in endpoint_data.to_dict().items()
54
+ if v is not None and k != "id"
55
+ }
56
+ moonshot_api.api_update_endpoint(ep_id=endpoint_id, **update_data)
57
+
58
+ @exception_handler
59
+ def delete_endpoint(self, endpoint_id: str) -> None:
60
+ moonshot_api.api_delete_endpoint(endpoint_id)
61
+
62
+ @exception_handler
63
+ def get_all_connectors(self) -> list[str]:
64
+ connectors = moonshot_api.api_get_all_connector_type()
65
+ return connectors
@@ -0,0 +1,14 @@
1
+ from .... import api as moonshot_api
2
+ from ..services.base_service import BaseService
3
+ from ..services.utils.exceptions_handler import exception_handler
4
+
5
+
6
+ class MetricService(BaseService):
7
+ @exception_handler
8
+ def get_all_metric(self) -> list[dict]:
9
+ metrics = moonshot_api.api_get_all_metric()
10
+ return metrics
11
+
12
+ @exception_handler
13
+ def delete_metric(self, metric_id: str) -> None:
14
+ moonshot_api.api_delete_metric(metric_id)
@@ -0,0 +1,39 @@
1
+ from typing import Any
2
+
3
+ from .... import api as moonshot_api
4
+ from ..services.utils.exceptions_handler import exception_handler
5
+ from .base_service import BaseService
6
+
7
+
8
+ class PromptTemplateService(BaseService):
9
+ @exception_handler
10
+ def get_prompt_templates(self) -> list[dict[str, Any]]:
11
+ """
12
+ Retrieve all prompt templates with their details.
13
+
14
+ Returns:
15
+ list[dict[str, Any]]: A list of dictionaries containing the details of each prompt template.
16
+ """
17
+ templates = moonshot_api.api_get_all_prompt_template_detail()
18
+ return templates
19
+
20
+ @exception_handler
21
+ def get_prompt_templates_name(self) -> list[str]:
22
+ """
23
+ Retrieve the names of all prompt templates.
24
+
25
+ Returns:
26
+ list[str]: A list of names of all prompt templates.
27
+ """
28
+ templates = moonshot_api.api_get_all_prompt_template_name()
29
+ return templates
30
+
31
+ @exception_handler
32
+ def delete_prompt_template(self, pt_id: str):
33
+ """
34
+ Delete a prompt template by its identifier.
35
+
36
+ Args:
37
+ pt_id (str): The unique identifier of the prompt template to be deleted.
38
+ """
39
+ moonshot_api.api_delete_prompt_template(pt_id)