Spaces:
Sleeping
Sleeping
File size: 9,589 Bytes
d8d14f1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 |
import json
import os
import time
import uuid
from typing import Any, Callable, List
from pydantic import (
BaseModel,
Field,
constr,
)
from pydantic.v1 import validator
from swarms.telemetry.capture_sys_data import (
capture_system_data,
log_agent_data,
)
from swarms.tools.base_tool import BaseTool
from swarms.utils.loguru_logger import initialize_logger
logger = initialize_logger("prompt")
class Prompt(BaseModel):
"""
A class representing a prompt with content, edit history, and version control.
This version is enhanced for production use, with thread-safety, logging, and additional functionality.
Autosaving is now added to save the prompt to a specified folder within the WORKSPACE_DIR.
Attributes:
id (UUID): A unique identifier for the prompt.
content (str): The main content of the prompt.
created_at (datetime): The timestamp when the prompt was created.
last_modified_at (datetime): The timestamp when the prompt was last modified.
edit_count (int): The number of times the prompt has been edited.
edit_history (List[str]): A list of all versions of the prompt, including current and previous versions.
autosave (bool): Flag to enable or disable autosaving.
autosave_folder (str): The folder path within WORKSPACE_DIR where the prompt will be autosaved.
"""
id: str = Field(
default=uuid.uuid4().hex,
description="Unique identifier for the prompt",
)
name: str = Field(
default="prompt", description="Name of your prompt"
)
description: str = Field(
default="Simple Prompt",
description="The description of the prompt",
)
content: constr(min_length=1, strip_whitespace=True) = Field(
..., description="The main content of the prompt"
)
created_at: str = Field(
default_factory=lambda: time.strftime("%Y-%m-%d %H:%M:%S"),
description="Time when the prompt was created",
)
last_modified_at: str = Field(
default_factory=lambda: time.strftime("%Y-%m-%d %H:%M:%S"),
description="Time when the prompt was last modified",
)
edit_count: int = Field(
default=0,
description="The number of times the prompt has been edited",
)
edit_history: List[str] = Field(
default_factory=list,
description="The history of edits, storing all prompt versions",
)
autosave: bool = Field(
default=False,
description="Flag to enable or disable autosaving",
)
autosave_folder: str = Field(
default="prompts",
description="The folder path within WORKSPACE_DIR where the prompt will be autosaved",
)
auto_generate_prompt: bool = Field(
default=False,
description="Flag to enable or disable auto-generating the prompt",
)
parent_folder: str = Field(
default=os.getenv("WORKSPACE_DIR"),
description="The folder where the autosave folder is in",
)
llm: Any = None
@validator("edit_history", pre=True, always=True)
def initialize_history(cls, v, values):
"""
Initializes the edit history by storing the first version of the prompt.
"""
if not v:
return [
values["content"]
] # Store initial version in history
return v
def __init__(self, **data):
super().__init__(**data)
if self.autosave:
self._autosave()
if self.auto_generate_prompt and self.llm:
self.auto_generate_prompt()
def edit_prompt(self, new_content: str) -> None:
"""
Edits the prompt content and updates the version control.
This method is thread-safe to prevent concurrent access issues.
If autosave is enabled, it saves the prompt to the specified folder.
Args:
new_content (str): The updated content of the prompt.
Raises:
ValueError: If the new content is identical to the current content.
"""
if new_content == self.content:
logger.warning(
f"Edit attempt failed: new content is identical to current content for prompt {self.id}"
)
raise ValueError(
"New content must be different from the current content."
)
# logger.info(
# f"Editing prompt {self.id}. Current content: '{self.content}'"
# )
self.edit_history.append(new_content)
self.content = new_content
self.edit_count += 1
self.last_modified_at = time.strftime("%Y-%m-%d %H:%M:%S")
# logger.debug(
# f"Prompt {self.id} updated. Edit count: {self.edit_count}. New content: '{self.content}'"
# )
if self.autosave:
self._autosave()
def log_telemetry(self):
system_data = capture_system_data()
merged_data = {**system_data, **self.model_dump()}
log_agent_data(merged_data)
def rollback(self, version: int) -> None:
"""
Rolls back the prompt to a previous version based on the version index.
This method is thread-safe to prevent concurrent access issues.
If autosave is enabled, it saves the prompt to the specified folder after rollback.
Args:
version (int): The version index to roll back to (0 is the first version).
Raises:
IndexError: If the version number is out of range.
"""
if version < 0 or version >= len(self.edit_history):
logger.error(
f"Rollback failed: invalid version {version} for prompt {self.id}"
)
raise IndexError("Invalid version number for rollback.")
# logger.info(
# f"Rolling back prompt {self.id} to version {version}."
# )
self.content = self.edit_history[version]
self.edit_count = version
self.last_modified_at = time.strftime("%Y-%m-%d %H:%M:%S")
# logger.debug(
# f"Prompt {self.id} rolled back to version {version}. Current content: '{self.content}'"
# )
self.log_telemetry()
if self.autosave:
self._autosave()
def return_json(self):
return self.model_dump_json(indent=4)
def get_prompt(self) -> str:
"""
Returns the current prompt content as a string.
Returns:
str: The current prompt content.
"""
# logger.debug(f"Returning prompt {self.id} as a string.")
self.log_telemetry()
return self.content
def save_to_storage(self) -> None:
"""
Placeholder method for saving the prompt to persistent storage.
In a production environment, this would integrate with a database or file system.
Raises:
NotImplementedError: This method is a placeholder for storage integration.
"""
# logger.info(f"Saving prompt {self.id} to persistent storage.")
raise NotImplementedError(
"Persistent storage integration is required."
)
def load_from_storage(
self, prompt_id: str = uuid.uuid4().hex
) -> None:
"""
Placeholder method for loading the prompt from persistent storage by its ID.
In a production environment, this would integrate with a database or file system.
Args:
prompt_id (UUID): The unique identifier of the prompt to load.
Raises:
NotImplementedError: This method is a placeholder for storage integration.
"""
# logger.info(
# f"Loading prompt {prompt_id} from persistent storage."
# )
raise NotImplementedError(
"Persistent storage integration is required."
)
def add_tools(self, tools: List[Callable]) -> str:
tools_prompt = BaseTool(
tools=tools, tool_system_prompt=None
).convert_tool_into_openai_schema()
self.content += "\n"
self.content += "\n"
self.content += tools_prompt
def _autosave(self) -> None:
"""
Autosaves the prompt to a specified folder within WORKSPACE_DIR.
"""
workspace_dir = os.getenv("WORKSPACE_DIR")
if not workspace_dir:
logger.error(
"WORKSPACE_DIR environment variable is not set."
)
return
autosave_path = os.path.join(
workspace_dir, self.autosave_folder
)
if not os.path.exists(autosave_path):
os.makedirs(autosave_path)
file_path = os.path.join(
autosave_path, f"prompt-id-{self.id}.json"
)
with open(file_path, "w") as file:
json.dump(self.model_dump(), file)
# logger.info(f"Autosaved prompt {self.id} to {file_path}.")
# return "Prompt autosaved successfully."
# def auto_generate_prompt(self):
# logger.info(f"Auto-generating prompt for {self.name}")
# task = self.name + " " + self.description + " " + self.content
# prompt = auto_generate_prompt(task, llm=self.llm, max_tokens=4000, use_second_sys_prompt=True)
# logger.info("Generated prompt successfully, updating content")
# self.edit_prompt(prompt)
# logger.info("Prompt content updated")
# return "Prompt auto-generated successfully."
class Config:
"""Pydantic configuration for better JSON serialization."""
use_enum_values = True
arbitrary_types_allowed = True
|