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.
- aiverify_moonshot-0.4.0.dist-info/METADATA +249 -0
- aiverify_moonshot-0.4.0.dist-info/RECORD +163 -0
- aiverify_moonshot-0.4.0.dist-info/WHEEL +4 -0
- aiverify_moonshot-0.4.0.dist-info/licenses/AUTHORS.md +5 -0
- aiverify_moonshot-0.4.0.dist-info/licenses/LICENSE.md +201 -0
- aiverify_moonshot-0.4.0.dist-info/licenses/NOTICES.md +3340 -0
- moonshot/__init__.py +0 -0
- moonshot/__main__.py +198 -0
- moonshot/api.py +155 -0
- moonshot/integrations/__init__.py +0 -0
- moonshot/integrations/cli/__init__.py +0 -0
- moonshot/integrations/cli/__main__.py +25 -0
- moonshot/integrations/cli/active_session_cfg.py +1 -0
- moonshot/integrations/cli/benchmark/__init__.py +0 -0
- moonshot/integrations/cli/benchmark/benchmark.py +186 -0
- moonshot/integrations/cli/benchmark/cookbook.py +545 -0
- moonshot/integrations/cli/benchmark/datasets.py +164 -0
- moonshot/integrations/cli/benchmark/metrics.py +141 -0
- moonshot/integrations/cli/benchmark/recipe.py +598 -0
- moonshot/integrations/cli/benchmark/result.py +216 -0
- moonshot/integrations/cli/benchmark/run.py +140 -0
- moonshot/integrations/cli/benchmark/runner.py +174 -0
- moonshot/integrations/cli/cli.py +64 -0
- moonshot/integrations/cli/common/__init__.py +0 -0
- moonshot/integrations/cli/common/common.py +72 -0
- moonshot/integrations/cli/common/connectors.py +325 -0
- moonshot/integrations/cli/common/display_helper.py +42 -0
- moonshot/integrations/cli/common/prompt_template.py +94 -0
- moonshot/integrations/cli/initialisation/__init__.py +0 -0
- moonshot/integrations/cli/initialisation/initialisation.py +14 -0
- moonshot/integrations/cli/redteam/__init__.py +0 -0
- moonshot/integrations/cli/redteam/attack_module.py +70 -0
- moonshot/integrations/cli/redteam/context_strategy.py +147 -0
- moonshot/integrations/cli/redteam/prompt_template.py +67 -0
- moonshot/integrations/cli/redteam/redteam.py +90 -0
- moonshot/integrations/cli/redteam/session.py +467 -0
- moonshot/integrations/web_api/.env.dev +7 -0
- moonshot/integrations/web_api/__init__.py +0 -0
- moonshot/integrations/web_api/__main__.py +56 -0
- moonshot/integrations/web_api/app.py +125 -0
- moonshot/integrations/web_api/container.py +146 -0
- moonshot/integrations/web_api/log/.gitkeep +0 -0
- moonshot/integrations/web_api/logging_conf.py +114 -0
- moonshot/integrations/web_api/routes/__init__.py +0 -0
- moonshot/integrations/web_api/routes/attack_modules.py +66 -0
- moonshot/integrations/web_api/routes/benchmark.py +116 -0
- moonshot/integrations/web_api/routes/benchmark_result.py +175 -0
- moonshot/integrations/web_api/routes/context_strategy.py +129 -0
- moonshot/integrations/web_api/routes/cookbook.py +225 -0
- moonshot/integrations/web_api/routes/dataset.py +120 -0
- moonshot/integrations/web_api/routes/endpoint.py +282 -0
- moonshot/integrations/web_api/routes/metric.py +78 -0
- moonshot/integrations/web_api/routes/prompt_template.py +128 -0
- moonshot/integrations/web_api/routes/recipe.py +219 -0
- moonshot/integrations/web_api/routes/redteam.py +609 -0
- moonshot/integrations/web_api/routes/runner.py +239 -0
- moonshot/integrations/web_api/schemas/__init__.py +0 -0
- moonshot/integrations/web_api/schemas/benchmark_runner_dto.py +13 -0
- moonshot/integrations/web_api/schemas/cookbook_create_dto.py +19 -0
- moonshot/integrations/web_api/schemas/cookbook_response_model.py +9 -0
- moonshot/integrations/web_api/schemas/dataset_response_dto.py +9 -0
- moonshot/integrations/web_api/schemas/endpoint_create_dto.py +21 -0
- moonshot/integrations/web_api/schemas/endpoint_response_model.py +11 -0
- moonshot/integrations/web_api/schemas/prompt_response_model.py +14 -0
- moonshot/integrations/web_api/schemas/prompt_template_response_model.py +10 -0
- moonshot/integrations/web_api/schemas/recipe_create_dto.py +32 -0
- moonshot/integrations/web_api/schemas/recipe_response_model.py +7 -0
- moonshot/integrations/web_api/schemas/session_create_dto.py +16 -0
- moonshot/integrations/web_api/schemas/session_prompt_dto.py +7 -0
- moonshot/integrations/web_api/schemas/session_response_model.py +38 -0
- moonshot/integrations/web_api/services/__init__.py +0 -0
- moonshot/integrations/web_api/services/attack_module_service.py +34 -0
- moonshot/integrations/web_api/services/auto_red_team_test_manager.py +86 -0
- moonshot/integrations/web_api/services/auto_red_team_test_state.py +57 -0
- moonshot/integrations/web_api/services/base_service.py +8 -0
- moonshot/integrations/web_api/services/benchmark_result_service.py +25 -0
- moonshot/integrations/web_api/services/benchmark_test_manager.py +106 -0
- moonshot/integrations/web_api/services/benchmark_test_state.py +56 -0
- moonshot/integrations/web_api/services/benchmarking_service.py +31 -0
- moonshot/integrations/web_api/services/context_strategy_service.py +22 -0
- moonshot/integrations/web_api/services/cookbook_service.py +194 -0
- moonshot/integrations/web_api/services/dataset_service.py +20 -0
- moonshot/integrations/web_api/services/endpoint_service.py +65 -0
- moonshot/integrations/web_api/services/metric_service.py +14 -0
- moonshot/integrations/web_api/services/prompt_template_service.py +39 -0
- moonshot/integrations/web_api/services/recipe_service.py +155 -0
- moonshot/integrations/web_api/services/runner_service.py +147 -0
- moonshot/integrations/web_api/services/session_service.py +350 -0
- moonshot/integrations/web_api/services/utils/exceptions_handler.py +41 -0
- moonshot/integrations/web_api/services/utils/results_formatter.py +47 -0
- moonshot/integrations/web_api/status_updater/interface/benchmark_progress_callback.py +14 -0
- moonshot/integrations/web_api/status_updater/interface/redteam_progress_callback.py +14 -0
- moonshot/integrations/web_api/status_updater/moonshot_ui_webhook.py +72 -0
- moonshot/integrations/web_api/types/types.py +99 -0
- moonshot/src/__init__.py +0 -0
- moonshot/src/api/__init__.py +0 -0
- moonshot/src/api/api_connector.py +58 -0
- moonshot/src/api/api_connector_endpoint.py +162 -0
- moonshot/src/api/api_context_strategy.py +57 -0
- moonshot/src/api/api_cookbook.py +160 -0
- moonshot/src/api/api_dataset.py +46 -0
- moonshot/src/api/api_environment_variables.py +17 -0
- moonshot/src/api/api_metrics.py +51 -0
- moonshot/src/api/api_prompt_template.py +43 -0
- moonshot/src/api/api_recipe.py +182 -0
- moonshot/src/api/api_red_teaming.py +59 -0
- moonshot/src/api/api_result.py +84 -0
- moonshot/src/api/api_run.py +74 -0
- moonshot/src/api/api_runner.py +132 -0
- moonshot/src/api/api_session.py +290 -0
- moonshot/src/configs/__init__.py +0 -0
- moonshot/src/configs/env_variables.py +187 -0
- moonshot/src/connectors/__init__.py +0 -0
- moonshot/src/connectors/connector.py +327 -0
- moonshot/src/connectors/connector_prompt_arguments.py +17 -0
- moonshot/src/connectors_endpoints/__init__.py +0 -0
- moonshot/src/connectors_endpoints/connector_endpoint.py +211 -0
- moonshot/src/connectors_endpoints/connector_endpoint_arguments.py +54 -0
- moonshot/src/cookbooks/__init__.py +0 -0
- moonshot/src/cookbooks/cookbook.py +225 -0
- moonshot/src/cookbooks/cookbook_arguments.py +34 -0
- moonshot/src/datasets/__init__.py +0 -0
- moonshot/src/datasets/dataset.py +255 -0
- moonshot/src/datasets/dataset_arguments.py +50 -0
- moonshot/src/metrics/__init__.py +0 -0
- moonshot/src/metrics/metric.py +192 -0
- moonshot/src/metrics/metric_interface.py +95 -0
- moonshot/src/prompt_templates/__init__.py +0 -0
- moonshot/src/prompt_templates/prompt_template.py +103 -0
- moonshot/src/recipes/__init__.py +0 -0
- moonshot/src/recipes/recipe.py +340 -0
- moonshot/src/recipes/recipe_arguments.py +111 -0
- moonshot/src/redteaming/__init__.py +0 -0
- moonshot/src/redteaming/attack/__init__.py +0 -0
- moonshot/src/redteaming/attack/attack_module.py +618 -0
- moonshot/src/redteaming/attack/attack_module_arguments.py +44 -0
- moonshot/src/redteaming/attack/context_strategy.py +131 -0
- moonshot/src/redteaming/context_strategy/__init__.py +0 -0
- moonshot/src/redteaming/context_strategy/context_strategy_interface.py +46 -0
- moonshot/src/redteaming/session/__init__.py +0 -0
- moonshot/src/redteaming/session/chat.py +209 -0
- moonshot/src/redteaming/session/red_teaming_progress.py +128 -0
- moonshot/src/redteaming/session/red_teaming_type.py +6 -0
- moonshot/src/redteaming/session/session.py +775 -0
- moonshot/src/results/__init__.py +0 -0
- moonshot/src/results/result.py +119 -0
- moonshot/src/results/result_arguments.py +44 -0
- moonshot/src/runners/__init__.py +0 -0
- moonshot/src/runners/runner.py +476 -0
- moonshot/src/runners/runner_arguments.py +46 -0
- moonshot/src/runners/runner_type.py +6 -0
- moonshot/src/runs/__init__.py +0 -0
- moonshot/src/runs/run.py +344 -0
- moonshot/src/runs/run_arguments.py +162 -0
- moonshot/src/runs/run_progress.py +145 -0
- moonshot/src/runs/run_status.py +10 -0
- moonshot/src/storage/__init__.py +0 -0
- moonshot/src/storage/db_interface.py +128 -0
- moonshot/src/storage/io_interface.py +31 -0
- moonshot/src/storage/storage.py +525 -0
- moonshot/src/utils/__init__.py +0 -0
- moonshot/src/utils/import_modules.py +96 -0
- moonshot/src/utils/timeit.py +25 -0
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from pydantic import validate_call
|
|
6
|
+
|
|
7
|
+
from moonshot.src.configs.env_variables import EnvVariables
|
|
8
|
+
from moonshot.src.metrics.metric_interface import MetricInterface
|
|
9
|
+
from moonshot.src.storage.storage import Storage
|
|
10
|
+
from moonshot.src.utils.import_modules import get_instance
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Metric:
|
|
14
|
+
cache_name = "cache"
|
|
15
|
+
cache_extension = "json"
|
|
16
|
+
|
|
17
|
+
@classmethod
|
|
18
|
+
def load(cls, met_id: str) -> Metric:
|
|
19
|
+
"""
|
|
20
|
+
Retrieves a metric instance by its ID.
|
|
21
|
+
|
|
22
|
+
This method attempts to load a metric instance using the provided ID. If the metric instance is found,
|
|
23
|
+
it is returned. If the metric instance does not exist, a RuntimeError is raised.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
met_id (str): The unique identifier of the metric to be retrieved.
|
|
27
|
+
|
|
28
|
+
Returns:
|
|
29
|
+
Metric: The retrieved metric instance.
|
|
30
|
+
|
|
31
|
+
Raises:
|
|
32
|
+
RuntimeError: If the metric instance does not exist.
|
|
33
|
+
"""
|
|
34
|
+
metric_instance = get_instance(
|
|
35
|
+
met_id,
|
|
36
|
+
Storage.get_filepath(EnvVariables.METRICS.name, met_id, "py"),
|
|
37
|
+
)
|
|
38
|
+
if metric_instance:
|
|
39
|
+
return metric_instance()
|
|
40
|
+
else:
|
|
41
|
+
raise RuntimeError(f"Unable to get defined metric instance - {met_id}")
|
|
42
|
+
|
|
43
|
+
@staticmethod
|
|
44
|
+
@validate_call
|
|
45
|
+
def delete(met_id: str) -> bool:
|
|
46
|
+
"""
|
|
47
|
+
Deletes a metric identified by its unique metric ID.
|
|
48
|
+
|
|
49
|
+
This method attempts to delete the metric with the given ID from the storage. If the deletion is successful,
|
|
50
|
+
it returns True. If an exception occurs during the deletion process, it prints an error message and re-raises
|
|
51
|
+
the exception.
|
|
52
|
+
|
|
53
|
+
Args:
|
|
54
|
+
met_id (str): The unique identifier of the metric to be deleted.
|
|
55
|
+
|
|
56
|
+
Returns:
|
|
57
|
+
bool: True if the metric was successfully deleted.
|
|
58
|
+
|
|
59
|
+
Raises:
|
|
60
|
+
Exception: If an error occurs during the deletion process.
|
|
61
|
+
"""
|
|
62
|
+
try:
|
|
63
|
+
Storage.delete_object(EnvVariables.METRICS.name, met_id, "py")
|
|
64
|
+
return True
|
|
65
|
+
|
|
66
|
+
except Exception as e:
|
|
67
|
+
print(f"Failed to delete metric: {str(e)}")
|
|
68
|
+
raise e
|
|
69
|
+
|
|
70
|
+
@staticmethod
|
|
71
|
+
def get_cache_information() -> dict:
|
|
72
|
+
"""
|
|
73
|
+
Retrieves cache information from the storage.
|
|
74
|
+
|
|
75
|
+
This method attempts to read the cache information from the storage and return it as a dictionary.
|
|
76
|
+
If the cache information does not exist or an error occurs, it returns an empty dictionary.
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
dict: A dictionary containing the cache information or an empty dictionary if an error occurs
|
|
80
|
+
or if the cache information does not exist.
|
|
81
|
+
|
|
82
|
+
Raises:
|
|
83
|
+
Exception: If there's an error during the retrieval process, it is logged and an
|
|
84
|
+
empty dictionary is returned.
|
|
85
|
+
"""
|
|
86
|
+
try:
|
|
87
|
+
# Retrieve cache information from the storage and return it as a dictionary
|
|
88
|
+
cache_info = Storage.read_object(
|
|
89
|
+
EnvVariables.METRICS.name, Metric.cache_name, Metric.cache_extension
|
|
90
|
+
)
|
|
91
|
+
return cache_info if cache_info else {}
|
|
92
|
+
except Exception:
|
|
93
|
+
print(
|
|
94
|
+
f"No previous cache information because {Metric.cache_name} is not found."
|
|
95
|
+
)
|
|
96
|
+
return {}
|
|
97
|
+
|
|
98
|
+
@staticmethod
|
|
99
|
+
def write_cache_information(cache_info: dict) -> None:
|
|
100
|
+
"""
|
|
101
|
+
Writes the updated cache information to the storage.
|
|
102
|
+
|
|
103
|
+
Args:
|
|
104
|
+
cache_info (dict): The cache information to be written.
|
|
105
|
+
"""
|
|
106
|
+
try:
|
|
107
|
+
Storage.create_object(
|
|
108
|
+
obj_type=EnvVariables.METRICS.name,
|
|
109
|
+
obj_id=Metric.cache_name,
|
|
110
|
+
obj_info=cache_info,
|
|
111
|
+
obj_extension=Metric.cache_extension,
|
|
112
|
+
)
|
|
113
|
+
except Exception as e:
|
|
114
|
+
print(f"Failed to write cache information: {str(e)}")
|
|
115
|
+
raise e
|
|
116
|
+
|
|
117
|
+
@staticmethod
|
|
118
|
+
def get_available_items() -> tuple[list[str], list[dict]]:
|
|
119
|
+
"""
|
|
120
|
+
Retrieves a list of available metric names and their corresponding information.
|
|
121
|
+
|
|
122
|
+
This method scans the storage for metric objects, filters out any system or cache-related entries,
|
|
123
|
+
and compiles a list of metric names and their detailed information. It also checks the cache for
|
|
124
|
+
any updates and writes back to the cache if necessary.
|
|
125
|
+
|
|
126
|
+
Returns:
|
|
127
|
+
tuple[list[str], list[dict]]: A tuple containing two lists, one with the names of the metrics
|
|
128
|
+
and the other with the corresponding metric information dictionaries.
|
|
129
|
+
"""
|
|
130
|
+
try:
|
|
131
|
+
retn_mets = []
|
|
132
|
+
retn_mets_ids = []
|
|
133
|
+
met_cache_info = Metric.get_cache_information()
|
|
134
|
+
cache_needs_update = False # Initialize a flag to track cache updates
|
|
135
|
+
mets = Storage.get_objects(EnvVariables.METRICS.name, "py")
|
|
136
|
+
|
|
137
|
+
for met in mets:
|
|
138
|
+
if "__" in met or MetricInterface.config_name in met:
|
|
139
|
+
continue
|
|
140
|
+
|
|
141
|
+
met_name = Path(met).stem
|
|
142
|
+
met_info, cache_updated = Metric._get_or_update_metrics_info(
|
|
143
|
+
met_name, met_cache_info
|
|
144
|
+
)
|
|
145
|
+
if cache_updated:
|
|
146
|
+
cache_needs_update = True # Set the flag if any cache was updated
|
|
147
|
+
|
|
148
|
+
retn_mets.append(met_info)
|
|
149
|
+
retn_mets_ids.append(met_name)
|
|
150
|
+
|
|
151
|
+
if cache_needs_update: # Check the flag after the loop
|
|
152
|
+
Metric.write_cache_information(met_cache_info)
|
|
153
|
+
|
|
154
|
+
return retn_mets_ids, retn_mets
|
|
155
|
+
|
|
156
|
+
except Exception as e:
|
|
157
|
+
print(f"Failed to get available metrics: {str(e)}")
|
|
158
|
+
raise e
|
|
159
|
+
|
|
160
|
+
@staticmethod
|
|
161
|
+
def _get_or_update_metrics_info(
|
|
162
|
+
met_name: str, met_cache_info: dict
|
|
163
|
+
) -> tuple[dict, bool]:
|
|
164
|
+
"""
|
|
165
|
+
Retrieves or updates the metric information from the cache.
|
|
166
|
+
|
|
167
|
+
This method checks if the metric information is already available in the cache and if the file hash matches
|
|
168
|
+
the one stored in the cache. If it does, the information is retrieved from the cache. If not, the metric
|
|
169
|
+
information is read from the storage, the cache is updated with the new information and the new file hash,
|
|
170
|
+
and a flag is set to indicate that the cache has been updated.
|
|
171
|
+
|
|
172
|
+
Args:
|
|
173
|
+
met_name (str): The name of the metric.
|
|
174
|
+
met_cache_info (dict): A dictionary containing the cached metric information.
|
|
175
|
+
|
|
176
|
+
Returns:
|
|
177
|
+
tuple[dict, bool]: A tuple containing the dictionary with the metric information
|
|
178
|
+
and a boolean indicating whether the cache was updated or not.
|
|
179
|
+
"""
|
|
180
|
+
file_hash = Storage.get_file_hash(EnvVariables.METRICS.name, met_name, "py")
|
|
181
|
+
cache_updated = False
|
|
182
|
+
|
|
183
|
+
if met_name in met_cache_info and file_hash == met_cache_info[met_name]["hash"]:
|
|
184
|
+
met_metadata = met_cache_info[met_name].copy()
|
|
185
|
+
met_metadata.pop("hash", None)
|
|
186
|
+
else:
|
|
187
|
+
met_metadata = Metric.load(met_name).get_metadata() # type: ignore ; ducktyping
|
|
188
|
+
met_cache_info[met_name] = met_metadata.copy()
|
|
189
|
+
met_cache_info[met_name]["hash"] = file_hash
|
|
190
|
+
cache_updated = True
|
|
191
|
+
|
|
192
|
+
return met_metadata, cache_updated
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
from abc import abstractmethod
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
from moonshot.src.configs.env_variables import EnvVariables
|
|
5
|
+
from moonshot.src.storage.storage import Storage
|
|
6
|
+
from moonshot.src.utils.timeit import timeit
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class MetricInterface:
|
|
10
|
+
config_name = "metrics_config"
|
|
11
|
+
config_extension = "json"
|
|
12
|
+
|
|
13
|
+
@abstractmethod
|
|
14
|
+
@timeit
|
|
15
|
+
def get_metadata(self) -> dict | None:
|
|
16
|
+
"""
|
|
17
|
+
Abstract method to retrieve metadata from a metric class.
|
|
18
|
+
|
|
19
|
+
Returns:
|
|
20
|
+
dict | None: Returns a dictionary containing the metadata of the metric class, or None if the operation was
|
|
21
|
+
unsuccessful.
|
|
22
|
+
"""
|
|
23
|
+
pass
|
|
24
|
+
|
|
25
|
+
@abstractmethod
|
|
26
|
+
async def get_results(
|
|
27
|
+
self, prompts: Any, predicted_results: Any, targets: Any, *args, **kwargs
|
|
28
|
+
) -> dict:
|
|
29
|
+
"""
|
|
30
|
+
Abstract method to compute metrics based on model predictions.
|
|
31
|
+
|
|
32
|
+
This method is intended to be implemented by subclasses to calculate specific
|
|
33
|
+
metrics (e.g., accuracy, BLEU score) based on the inputs provided.
|
|
34
|
+
It should handle any necessary preprocessing of inputs, computation of the metric, and formatting of the output.
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
prompts (Any): The input prompts used to generate the predictions.
|
|
38
|
+
The exact type and format will depend on the specific implementation and the nature of the
|
|
39
|
+
task (e.g., text, images).
|
|
40
|
+
|
|
41
|
+
predicted_results (Any): The model's predictions in response to the prompts.
|
|
42
|
+
The type and format should align with the prompts and the expected output of the model.
|
|
43
|
+
|
|
44
|
+
targets (Any): The ground truth targets against which the predicted results will be evaluated.
|
|
45
|
+
|
|
46
|
+
*args: Variable length argument list for additional parameters that might be required for specific metric
|
|
47
|
+
computations.
|
|
48
|
+
|
|
49
|
+
**kwargs: Arbitrary keyword arguments for additional options or configuration settings that might be
|
|
50
|
+
required for specific metric computations.
|
|
51
|
+
|
|
52
|
+
Returns:
|
|
53
|
+
dict: A dictionary containing the computed metric(s). The keys should clearly indicate the metric being
|
|
54
|
+
reported, and the values should be the corresponding metric values.
|
|
55
|
+
"""
|
|
56
|
+
pass
|
|
57
|
+
|
|
58
|
+
def get_metrics_configuration(self, met_id: str) -> dict:
|
|
59
|
+
"""
|
|
60
|
+
Retrieves the configuration for a specific metric by its identifier.
|
|
61
|
+
|
|
62
|
+
Args:
|
|
63
|
+
met_id (str): The identifier for the metric configuration to retrieve.
|
|
64
|
+
|
|
65
|
+
Returns:
|
|
66
|
+
dict: The metric configuration as a dictionary. Returns an empty dict if the configuration is not found.
|
|
67
|
+
|
|
68
|
+
Raises:
|
|
69
|
+
Exception: If reading the metrics configuration fails or if the configuration cannot be created.
|
|
70
|
+
"""
|
|
71
|
+
try:
|
|
72
|
+
obj_results = Storage.read_object(
|
|
73
|
+
EnvVariables.METRICS.name, "metrics_config", "json"
|
|
74
|
+
)
|
|
75
|
+
return obj_results.get(met_id, {})
|
|
76
|
+
|
|
77
|
+
except Exception as e:
|
|
78
|
+
print(f"[MetricInterface] Failed to read metrics configuration: {str(e)}")
|
|
79
|
+
print("Attempting to create empty metrics configuration...")
|
|
80
|
+
try:
|
|
81
|
+
Storage.create_object(
|
|
82
|
+
obj_type=EnvVariables.METRICS.name,
|
|
83
|
+
obj_id="metrics_config",
|
|
84
|
+
obj_info={},
|
|
85
|
+
obj_extension="json",
|
|
86
|
+
)
|
|
87
|
+
# After creation, attempt to read it again to ensure it was created successfully
|
|
88
|
+
obj_results = Storage.read_object(
|
|
89
|
+
EnvVariables.METRICS.name, "metrics_config", "json"
|
|
90
|
+
)
|
|
91
|
+
return obj_results.get(met_id, {})
|
|
92
|
+
except Exception as e:
|
|
93
|
+
raise Exception(
|
|
94
|
+
f"[MetricInterface] Failed to create metrics configuration: {str(e)}"
|
|
95
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
|
|
3
|
+
from jinja2 import Template
|
|
4
|
+
|
|
5
|
+
from moonshot.src.configs.env_variables import EnvVariables
|
|
6
|
+
from moonshot.src.storage.storage import Storage
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class PromptTemplate:
|
|
10
|
+
def __init__(self):
|
|
11
|
+
pass
|
|
12
|
+
|
|
13
|
+
@staticmethod
|
|
14
|
+
def get_all_prompt_template_names() -> list[str]:
|
|
15
|
+
"""
|
|
16
|
+
Retrieve the names of all prompt templates available.
|
|
17
|
+
|
|
18
|
+
Returns:
|
|
19
|
+
list: A list of prompt template names.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
filepaths = []
|
|
23
|
+
prompt_template_files = Storage.get_objects(
|
|
24
|
+
EnvVariables.PROMPT_TEMPLATES.name, "json"
|
|
25
|
+
)
|
|
26
|
+
for prompt_template in prompt_template_files:
|
|
27
|
+
filepaths.append(Path(prompt_template).stem)
|
|
28
|
+
return filepaths
|
|
29
|
+
|
|
30
|
+
@staticmethod
|
|
31
|
+
def get_all_prompt_template_details() -> list[dict]:
|
|
32
|
+
"""
|
|
33
|
+
Retrieve details of all prompt templates available.
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
list[dict]: A list of dictionaries containing the details of each prompt template.
|
|
37
|
+
"""
|
|
38
|
+
list_of_pt_names = PromptTemplate.get_all_prompt_template_names()
|
|
39
|
+
list_of_pt_contents = []
|
|
40
|
+
|
|
41
|
+
for pt_name in list_of_pt_names:
|
|
42
|
+
pt_contents = Storage.read_object(
|
|
43
|
+
EnvVariables.PROMPT_TEMPLATES.name, pt_name, "json"
|
|
44
|
+
)
|
|
45
|
+
id = pt_name
|
|
46
|
+
name = pt_contents["name"]
|
|
47
|
+
description = pt_contents["description"]
|
|
48
|
+
template = pt_contents["template"]
|
|
49
|
+
list_of_pt_contents.append(
|
|
50
|
+
{
|
|
51
|
+
"id": id,
|
|
52
|
+
"name": name,
|
|
53
|
+
"description": description,
|
|
54
|
+
"template": template,
|
|
55
|
+
}
|
|
56
|
+
)
|
|
57
|
+
return list_of_pt_contents
|
|
58
|
+
|
|
59
|
+
@staticmethod
|
|
60
|
+
def delete(pt_id: str) -> bool:
|
|
61
|
+
"""
|
|
62
|
+
Deletes a prompt template identified by its unique ID.
|
|
63
|
+
|
|
64
|
+
This method attempts to delete the prompt template with the given ID from the storage.
|
|
65
|
+
If the deletion is successful, it returns True. If an exception occurs during the deletion
|
|
66
|
+
process, it prints an error message and re-raises the exception.
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
pt_id (str): The unique identifier of the prompt template to be deleted.
|
|
70
|
+
|
|
71
|
+
Returns:
|
|
72
|
+
bool: True if the prompt template was successfully deleted.
|
|
73
|
+
|
|
74
|
+
Raises:
|
|
75
|
+
Exception: If an error occurs during the deletion process.
|
|
76
|
+
"""
|
|
77
|
+
try:
|
|
78
|
+
Storage.delete_object(EnvVariables.PROMPT_TEMPLATES.name, pt_id, "json")
|
|
79
|
+
return True
|
|
80
|
+
|
|
81
|
+
except Exception as e:
|
|
82
|
+
print(f"Failed to delete prompt template: {str(e)}")
|
|
83
|
+
raise e
|
|
84
|
+
|
|
85
|
+
@staticmethod
|
|
86
|
+
def process_prompt_pt(user_prompt: str, prompt_template_name: str) -> str:
|
|
87
|
+
"""
|
|
88
|
+
Process a user prompt using a specified prompt template.
|
|
89
|
+
|
|
90
|
+
Args:
|
|
91
|
+
user_prompt (str): The user prompt to process.
|
|
92
|
+
prompt_template (str): The name of the prompt template to use.
|
|
93
|
+
|
|
94
|
+
Returns:
|
|
95
|
+
str: The processed user prompt based on the template.
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
prompt_template_file = Storage.read_object(
|
|
99
|
+
EnvVariables.PROMPT_TEMPLATES.name, prompt_template_name, "json"
|
|
100
|
+
)
|
|
101
|
+
template = prompt_template_file["template"]
|
|
102
|
+
jinja_template = Template(template)
|
|
103
|
+
return jinja_template.render({"prompt": user_prompt})
|
|
File without changes
|