misc.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. import hashlib
  2. import re
  3. import time
  4. import uuid
  5. from datetime import timedelta
  6. from pathlib import Path
  7. from typing import Callable, Optional
  8. def get_message_list(messages, message_id):
  9. """
  10. Reconstructs a list of messages in order up to the specified message_id.
  11. :param message_id: ID of the message to reconstruct the chain
  12. :param messages: Message history dict containing all messages
  13. :return: List of ordered messages starting from the root to the given message
  14. """
  15. # Find the message by its id
  16. current_message = messages.get(message_id)
  17. if not current_message:
  18. return f"Message ID {message_id} not found in the history."
  19. # Reconstruct the chain by following the parentId links
  20. message_list = []
  21. while current_message:
  22. message_list.insert(
  23. 0, current_message
  24. ) # Insert the message at the beginning of the list
  25. parent_id = current_message["parentId"]
  26. current_message = messages.get(parent_id) if parent_id else None
  27. return message_list
  28. def get_messages_content(messages: list[dict]) -> str:
  29. return "\n".join(
  30. [
  31. f"{message['role'].upper()}: {get_content_from_message(message)}"
  32. for message in messages
  33. ]
  34. )
  35. def get_last_user_message_item(messages: list[dict]) -> Optional[dict]:
  36. for message in reversed(messages):
  37. if message["role"] == "user":
  38. return message
  39. return None
  40. def get_content_from_message(message: dict) -> Optional[str]:
  41. if isinstance(message["content"], list):
  42. for item in message["content"]:
  43. if item["type"] == "text":
  44. return item["text"]
  45. else:
  46. return message["content"]
  47. return None
  48. def get_last_user_message(messages: list[dict]) -> Optional[str]:
  49. message = get_last_user_message_item(messages)
  50. if message is None:
  51. return None
  52. return get_content_from_message(message)
  53. def get_last_assistant_message_item(messages: list[dict]) -> Optional[dict]:
  54. for message in reversed(messages):
  55. if message["role"] == "assistant":
  56. return message
  57. return None
  58. def get_last_assistant_message(messages: list[dict]) -> Optional[str]:
  59. for message in reversed(messages):
  60. if message["role"] == "assistant":
  61. return get_content_from_message(message)
  62. return None
  63. def get_system_message(messages: list[dict]) -> Optional[dict]:
  64. for message in messages:
  65. if message["role"] == "system":
  66. return message
  67. return None
  68. def remove_system_message(messages: list[dict]) -> list[dict]:
  69. return [message for message in messages if message["role"] != "system"]
  70. def pop_system_message(messages: list[dict]) -> tuple[Optional[dict], list[dict]]:
  71. return get_system_message(messages), remove_system_message(messages)
  72. def prepend_to_first_user_message_content(
  73. content: str, messages: list[dict]
  74. ) -> list[dict]:
  75. for message in messages:
  76. if message["role"] == "user":
  77. if isinstance(message["content"], list):
  78. for item in message["content"]:
  79. if item["type"] == "text":
  80. item["text"] = f"{content}\n{item['text']}"
  81. else:
  82. message["content"] = f"{content}\n{message['content']}"
  83. break
  84. return messages
  85. def add_or_update_system_message(content: str, messages: list[dict]):
  86. """
  87. Adds a new system message at the beginning of the messages list
  88. or updates the existing system message at the beginning.
  89. :param msg: The message to be added or appended.
  90. :param messages: The list of message dictionaries.
  91. :return: The updated list of message dictionaries.
  92. """
  93. if messages and messages[0].get("role") == "system":
  94. messages[0]["content"] = f"{content}\n{messages[0]['content']}"
  95. else:
  96. # Insert at the beginning
  97. messages.insert(0, {"role": "system", "content": content})
  98. return messages
  99. def openai_chat_message_template(model: str):
  100. return {
  101. "id": f"{model}-{str(uuid.uuid4())}",
  102. "created": int(time.time()),
  103. "model": model,
  104. "choices": [{"index": 0, "logprobs": None, "finish_reason": None}],
  105. }
  106. def openai_chat_chunk_message_template(
  107. model: str, message: Optional[str] = None, usage: Optional[dict] = None
  108. ) -> dict:
  109. template = openai_chat_message_template(model)
  110. template["object"] = "chat.completion.chunk"
  111. if message:
  112. template["choices"][0]["delta"] = {"content": message}
  113. else:
  114. template["choices"][0]["finish_reason"] = "stop"
  115. template["choices"][0]["delta"] = {}
  116. if usage:
  117. template["usage"] = usage
  118. return template
  119. def openai_chat_completion_message_template(
  120. model: str, message: Optional[str] = None, usage: Optional[dict] = None
  121. ) -> dict:
  122. template = openai_chat_message_template(model)
  123. template["object"] = "chat.completion"
  124. if message is not None:
  125. template["choices"][0]["message"] = {"content": message, "role": "assistant"}
  126. template["choices"][0]["finish_reason"] = "stop"
  127. if usage:
  128. template["usage"] = usage
  129. return template
  130. def get_gravatar_url(email):
  131. # Trim leading and trailing whitespace from
  132. # an email address and force all characters
  133. # to lower case
  134. address = str(email).strip().lower()
  135. # Create a SHA256 hash of the final string
  136. hash_object = hashlib.sha256(address.encode())
  137. hash_hex = hash_object.hexdigest()
  138. # Grab the actual image URL
  139. return f"https://www.gravatar.com/avatar/{hash_hex}?d=mp"
  140. def calculate_sha256(file):
  141. sha256 = hashlib.sha256()
  142. # Read the file in chunks to efficiently handle large files
  143. for chunk in iter(lambda: file.read(8192), b""):
  144. sha256.update(chunk)
  145. return sha256.hexdigest()
  146. def calculate_sha256_string(string):
  147. # Create a new SHA-256 hash object
  148. sha256_hash = hashlib.sha256()
  149. # Update the hash object with the bytes of the input string
  150. sha256_hash.update(string.encode("utf-8"))
  151. # Get the hexadecimal representation of the hash
  152. hashed_string = sha256_hash.hexdigest()
  153. return hashed_string
  154. def validate_email_format(email: str) -> bool:
  155. if email.endswith("@localhost"):
  156. return True
  157. return bool(re.match(r"[^@]+@[^@]+\.[^@]+", email))
  158. def sanitize_filename(file_name):
  159. # Convert to lowercase
  160. lower_case_file_name = file_name.lower()
  161. # Remove special characters using regular expression
  162. sanitized_file_name = re.sub(r"[^\w\s]", "", lower_case_file_name)
  163. # Replace spaces with dashes
  164. final_file_name = re.sub(r"\s+", "-", sanitized_file_name)
  165. return final_file_name
  166. def extract_folders_after_data_docs(path):
  167. # Convert the path to a Path object if it's not already
  168. path = Path(path)
  169. # Extract parts of the path
  170. parts = path.parts
  171. # Find the index of '/data/docs' in the path
  172. try:
  173. index_data_docs = parts.index("data") + 1
  174. index_docs = parts.index("docs", index_data_docs) + 1
  175. except ValueError:
  176. return []
  177. # Exclude the filename and accumulate folder names
  178. tags = []
  179. folders = parts[index_docs:-1]
  180. for idx, _ in enumerate(folders):
  181. tags.append("/".join(folders[: idx + 1]))
  182. return tags
  183. def parse_duration(duration: str) -> Optional[timedelta]:
  184. if duration == "-1" or duration == "0":
  185. return None
  186. # Regular expression to find number and unit pairs
  187. pattern = r"(-?\d+(\.\d+)?)(ms|s|m|h|d|w)"
  188. matches = re.findall(pattern, duration)
  189. if not matches:
  190. raise ValueError("Invalid duration string")
  191. total_duration = timedelta()
  192. for number, _, unit in matches:
  193. number = float(number)
  194. if unit == "ms":
  195. total_duration += timedelta(milliseconds=number)
  196. elif unit == "s":
  197. total_duration += timedelta(seconds=number)
  198. elif unit == "m":
  199. total_duration += timedelta(minutes=number)
  200. elif unit == "h":
  201. total_duration += timedelta(hours=number)
  202. elif unit == "d":
  203. total_duration += timedelta(days=number)
  204. elif unit == "w":
  205. total_duration += timedelta(weeks=number)
  206. return total_duration
  207. def parse_ollama_modelfile(model_text):
  208. parameters_meta = {
  209. "mirostat": int,
  210. "mirostat_eta": float,
  211. "mirostat_tau": float,
  212. "num_ctx": int,
  213. "repeat_last_n": int,
  214. "repeat_penalty": float,
  215. "temperature": float,
  216. "seed": int,
  217. "tfs_z": float,
  218. "num_predict": int,
  219. "top_k": int,
  220. "top_p": float,
  221. "num_keep": int,
  222. "typical_p": float,
  223. "presence_penalty": float,
  224. "frequency_penalty": float,
  225. "penalize_newline": bool,
  226. "numa": bool,
  227. "num_batch": int,
  228. "num_gpu": int,
  229. "main_gpu": int,
  230. "low_vram": bool,
  231. "f16_kv": bool,
  232. "vocab_only": bool,
  233. "use_mmap": bool,
  234. "use_mlock": bool,
  235. "num_thread": int,
  236. }
  237. data = {"base_model_id": None, "params": {}}
  238. # Parse base model
  239. base_model_match = re.search(
  240. r"^FROM\s+(\w+)", model_text, re.MULTILINE | re.IGNORECASE
  241. )
  242. if base_model_match:
  243. data["base_model_id"] = base_model_match.group(1)
  244. # Parse template
  245. template_match = re.search(
  246. r'TEMPLATE\s+"""(.+?)"""', model_text, re.DOTALL | re.IGNORECASE
  247. )
  248. if template_match:
  249. data["params"] = {"template": template_match.group(1).strip()}
  250. # Parse stops
  251. stops = re.findall(r'PARAMETER stop "(.*?)"', model_text, re.IGNORECASE)
  252. if stops:
  253. data["params"]["stop"] = stops
  254. # Parse other parameters from the provided list
  255. for param, param_type in parameters_meta.items():
  256. param_match = re.search(rf"PARAMETER {param} (.+)", model_text, re.IGNORECASE)
  257. if param_match:
  258. value = param_match.group(1)
  259. try:
  260. if param_type is int:
  261. value = int(value)
  262. elif param_type is float:
  263. value = float(value)
  264. elif param_type is bool:
  265. value = value.lower() == "true"
  266. except Exception as e:
  267. print(e)
  268. continue
  269. data["params"][param] = value
  270. # Parse adapter
  271. adapter_match = re.search(r"ADAPTER (.+)", model_text, re.IGNORECASE)
  272. if adapter_match:
  273. data["params"]["adapter"] = adapter_match.group(1)
  274. # Parse system description
  275. system_desc_match = re.search(
  276. r'SYSTEM\s+"""(.+?)"""', model_text, re.DOTALL | re.IGNORECASE
  277. )
  278. system_desc_match_single = re.search(
  279. r"SYSTEM\s+([^\n]+)", model_text, re.IGNORECASE
  280. )
  281. if system_desc_match:
  282. data["params"]["system"] = system_desc_match.group(1).strip()
  283. elif system_desc_match_single:
  284. data["params"]["system"] = system_desc_match_single.group(1).strip()
  285. # Parse messages
  286. messages = []
  287. message_matches = re.findall(r"MESSAGE (\w+) (.+)", model_text, re.IGNORECASE)
  288. for role, content in message_matches:
  289. messages.append({"role": role, "content": content})
  290. if messages:
  291. data["params"]["messages"] = messages
  292. return data