misc.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. import hashlib
  2. import re
  3. import threading
  4. import time
  5. import uuid
  6. import logging
  7. from datetime import timedelta
  8. from pathlib import Path
  9. from typing import Callable, Optional
  10. import json
  11. import collections.abc
  12. from open_webui.env import SRC_LOG_LEVELS
  13. log = logging.getLogger(__name__)
  14. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  15. def deep_update(d, u):
  16. for k, v in u.items():
  17. if isinstance(v, collections.abc.Mapping):
  18. d[k] = deep_update(d.get(k, {}), v)
  19. else:
  20. d[k] = v
  21. return d
  22. def get_message_list(messages_map, message_id):
  23. """
  24. Reconstructs a list of messages in order up to the specified message_id.
  25. :param message_id: ID of the message to reconstruct the chain
  26. :param messages: Message history dict containing all messages
  27. :return: List of ordered messages starting from the root to the given message
  28. """
  29. # Handle case where messages is None
  30. if not messages_map:
  31. return [] # Return empty list instead of None to prevent iteration errors
  32. # Find the message by its id
  33. current_message = messages_map.get(message_id)
  34. if not current_message:
  35. return [] # Return empty list instead of None to prevent iteration errors
  36. # Reconstruct the chain by following the parentId links
  37. message_list = []
  38. while current_message:
  39. message_list.insert(
  40. 0, current_message
  41. ) # Insert the message at the beginning of the list
  42. parent_id = current_message.get("parentId") # Use .get() for safety
  43. current_message = messages_map.get(parent_id) if parent_id else None
  44. return message_list
  45. def get_messages_content(messages: list[dict]) -> str:
  46. return "\n".join(
  47. [
  48. f"{message['role'].upper()}: {get_content_from_message(message)}"
  49. for message in messages
  50. ]
  51. )
  52. def get_last_user_message_item(messages: list[dict]) -> Optional[dict]:
  53. for message in reversed(messages):
  54. if message["role"] == "user":
  55. return message
  56. return None
  57. def get_content_from_message(message: dict) -> Optional[str]:
  58. if isinstance(message.get("content"), list):
  59. for item in message["content"]:
  60. if item["type"] == "text":
  61. return item["text"]
  62. else:
  63. return message.get("content")
  64. return None
  65. def get_last_user_message(messages: list[dict]) -> Optional[str]:
  66. message = get_last_user_message_item(messages)
  67. if message is None:
  68. return None
  69. return get_content_from_message(message)
  70. def get_last_assistant_message_item(messages: list[dict]) -> Optional[dict]:
  71. for message in reversed(messages):
  72. if message["role"] == "assistant":
  73. return message
  74. return None
  75. def get_last_assistant_message(messages: list[dict]) -> Optional[str]:
  76. for message in reversed(messages):
  77. if message["role"] == "assistant":
  78. return get_content_from_message(message)
  79. return None
  80. def get_system_message(messages: list[dict]) -> Optional[dict]:
  81. for message in messages:
  82. if message["role"] == "system":
  83. return message
  84. return None
  85. def remove_system_message(messages: list[dict]) -> list[dict]:
  86. return [message for message in messages if message["role"] != "system"]
  87. def pop_system_message(messages: list[dict]) -> tuple[Optional[dict], list[dict]]:
  88. return get_system_message(messages), remove_system_message(messages)
  89. def prepend_to_first_user_message_content(
  90. content: str, messages: list[dict]
  91. ) -> list[dict]:
  92. for message in messages:
  93. if message["role"] == "user":
  94. if isinstance(message["content"], list):
  95. for item in message["content"]:
  96. if item["type"] == "text":
  97. item["text"] = f"{content}\n{item['text']}"
  98. else:
  99. message["content"] = f"{content}\n{message['content']}"
  100. break
  101. return messages
  102. def add_or_update_system_message(
  103. content: str, messages: list[dict], append: bool = False
  104. ):
  105. """
  106. Adds a new system message at the beginning of the messages list
  107. or updates the existing system message at the beginning.
  108. :param msg: The message to be added or appended.
  109. :param messages: The list of message dictionaries.
  110. :return: The updated list of message dictionaries.
  111. """
  112. if messages and messages[0].get("role") == "system":
  113. if append:
  114. messages[0]["content"] = f"{messages[0]['content']}\n{content}"
  115. else:
  116. messages[0]["content"] = f"{content}\n{messages[0]['content']}"
  117. else:
  118. # Insert at the beginning
  119. messages.insert(0, {"role": "system", "content": content})
  120. return messages
  121. def add_or_update_user_message(content: str, messages: list[dict]):
  122. """
  123. Adds a new user message at the end of the messages list
  124. or updates the existing user message at the end.
  125. :param msg: The message to be added or appended.
  126. :param messages: The list of message dictionaries.
  127. :return: The updated list of message dictionaries.
  128. """
  129. if messages and messages[-1].get("role") == "user":
  130. messages[-1]["content"] = f"{messages[-1]['content']}\n{content}"
  131. else:
  132. # Insert at the end
  133. messages.append({"role": "user", "content": content})
  134. return messages
  135. def append_or_update_assistant_message(content: str, messages: list[dict]):
  136. """
  137. Adds a new assistant message at the end of the messages list
  138. or updates the existing assistant message at the end.
  139. :param msg: The message to be added or appended.
  140. :param messages: The list of message dictionaries.
  141. :return: The updated list of message dictionaries.
  142. """
  143. if messages and messages[-1].get("role") == "assistant":
  144. messages[-1]["content"] = f"{messages[-1]['content']}\n{content}"
  145. else:
  146. # Insert at the end
  147. messages.append({"role": "assistant", "content": content})
  148. return messages
  149. def openai_chat_message_template(model: str):
  150. return {
  151. "id": f"{model}-{str(uuid.uuid4())}",
  152. "created": int(time.time()),
  153. "model": model,
  154. "choices": [{"index": 0, "logprobs": None, "finish_reason": None}],
  155. }
  156. def openai_chat_chunk_message_template(
  157. model: str,
  158. content: Optional[str] = None,
  159. reasoning_content: Optional[str] = None,
  160. tool_calls: Optional[list[dict]] = None,
  161. usage: Optional[dict] = None,
  162. ) -> dict:
  163. template = openai_chat_message_template(model)
  164. template["object"] = "chat.completion.chunk"
  165. template["choices"][0]["index"] = 0
  166. template["choices"][0]["delta"] = {}
  167. if content:
  168. template["choices"][0]["delta"]["content"] = content
  169. if reasoning_content:
  170. template["choices"][0]["delta"]["reasoning_content"] = reasoning_content
  171. if tool_calls:
  172. template["choices"][0]["delta"]["tool_calls"] = tool_calls
  173. if not content and not reasoning_content and not tool_calls:
  174. template["choices"][0]["finish_reason"] = "stop"
  175. if usage:
  176. template["usage"] = usage
  177. return template
  178. def openai_chat_completion_message_template(
  179. model: str,
  180. message: Optional[str] = None,
  181. reasoning_content: Optional[str] = None,
  182. tool_calls: Optional[list[dict]] = None,
  183. usage: Optional[dict] = None,
  184. ) -> dict:
  185. template = openai_chat_message_template(model)
  186. template["object"] = "chat.completion"
  187. if message is not None:
  188. template["choices"][0]["message"] = {
  189. "role": "assistant",
  190. "content": message,
  191. **({"reasoning_content": reasoning_content} if reasoning_content else {}),
  192. **({"tool_calls": tool_calls} if tool_calls else {}),
  193. }
  194. template["choices"][0]["finish_reason"] = "stop"
  195. if usage:
  196. template["usage"] = usage
  197. return template
  198. def get_gravatar_url(email):
  199. # Trim leading and trailing whitespace from
  200. # an email address and force all characters
  201. # to lower case
  202. address = str(email).strip().lower()
  203. # Create a SHA256 hash of the final string
  204. hash_object = hashlib.sha256(address.encode())
  205. hash_hex = hash_object.hexdigest()
  206. # Grab the actual image URL
  207. return f"https://www.gravatar.com/avatar/{hash_hex}?d=mp"
  208. def calculate_sha256(file_path, chunk_size):
  209. # Compute SHA-256 hash of a file efficiently in chunks
  210. sha256 = hashlib.sha256()
  211. with open(file_path, "rb") as f:
  212. while chunk := f.read(chunk_size):
  213. sha256.update(chunk)
  214. return sha256.hexdigest()
  215. def calculate_sha256_string(string):
  216. # Create a new SHA-256 hash object
  217. sha256_hash = hashlib.sha256()
  218. # Update the hash object with the bytes of the input string
  219. sha256_hash.update(string.encode("utf-8"))
  220. # Get the hexadecimal representation of the hash
  221. hashed_string = sha256_hash.hexdigest()
  222. return hashed_string
  223. def validate_email_format(email: str) -> bool:
  224. if email.endswith("@localhost"):
  225. return True
  226. return bool(re.match(r"[^@]+@[^@]+\.[^@]+", email))
  227. def sanitize_filename(file_name):
  228. # Convert to lowercase
  229. lower_case_file_name = file_name.lower()
  230. # Remove special characters using regular expression
  231. sanitized_file_name = re.sub(r"[^\w\s]", "", lower_case_file_name)
  232. # Replace spaces with dashes
  233. final_file_name = re.sub(r"\s+", "-", sanitized_file_name)
  234. return final_file_name
  235. def extract_folders_after_data_docs(path):
  236. # Convert the path to a Path object if it's not already
  237. path = Path(path)
  238. # Extract parts of the path
  239. parts = path.parts
  240. # Find the index of '/data/docs' in the path
  241. try:
  242. index_data_docs = parts.index("data") + 1
  243. index_docs = parts.index("docs", index_data_docs) + 1
  244. except ValueError:
  245. return []
  246. # Exclude the filename and accumulate folder names
  247. tags = []
  248. folders = parts[index_docs:-1]
  249. for idx, _ in enumerate(folders):
  250. tags.append("/".join(folders[: idx + 1]))
  251. return tags
  252. def parse_duration(duration: str) -> Optional[timedelta]:
  253. if duration == "-1" or duration == "0":
  254. return None
  255. # Regular expression to find number and unit pairs
  256. pattern = r"(-?\d+(\.\d+)?)(ms|s|m|h|d|w)"
  257. matches = re.findall(pattern, duration)
  258. if not matches:
  259. raise ValueError("Invalid duration string")
  260. total_duration = timedelta()
  261. for number, _, unit in matches:
  262. number = float(number)
  263. if unit == "ms":
  264. total_duration += timedelta(milliseconds=number)
  265. elif unit == "s":
  266. total_duration += timedelta(seconds=number)
  267. elif unit == "m":
  268. total_duration += timedelta(minutes=number)
  269. elif unit == "h":
  270. total_duration += timedelta(hours=number)
  271. elif unit == "d":
  272. total_duration += timedelta(days=number)
  273. elif unit == "w":
  274. total_duration += timedelta(weeks=number)
  275. return total_duration
  276. def parse_ollama_modelfile(model_text):
  277. parameters_meta = {
  278. "mirostat": int,
  279. "mirostat_eta": float,
  280. "mirostat_tau": float,
  281. "num_ctx": int,
  282. "repeat_last_n": int,
  283. "repeat_penalty": float,
  284. "temperature": float,
  285. "seed": int,
  286. "tfs_z": float,
  287. "num_predict": int,
  288. "top_k": int,
  289. "top_p": float,
  290. "num_keep": int,
  291. "typical_p": float,
  292. "presence_penalty": float,
  293. "frequency_penalty": float,
  294. "penalize_newline": bool,
  295. "numa": bool,
  296. "num_batch": int,
  297. "num_gpu": int,
  298. "main_gpu": int,
  299. "low_vram": bool,
  300. "f16_kv": bool,
  301. "vocab_only": bool,
  302. "use_mmap": bool,
  303. "use_mlock": bool,
  304. "num_thread": int,
  305. }
  306. data = {"base_model_id": None, "params": {}}
  307. # Parse base model
  308. base_model_match = re.search(
  309. r"^FROM\s+(\w+)", model_text, re.MULTILINE | re.IGNORECASE
  310. )
  311. if base_model_match:
  312. data["base_model_id"] = base_model_match.group(1)
  313. # Parse template
  314. template_match = re.search(
  315. r'TEMPLATE\s+"""(.+?)"""', model_text, re.DOTALL | re.IGNORECASE
  316. )
  317. if template_match:
  318. data["params"] = {"template": template_match.group(1).strip()}
  319. # Parse stops
  320. stops = re.findall(r'PARAMETER stop "(.*?)"', model_text, re.IGNORECASE)
  321. if stops:
  322. data["params"]["stop"] = stops
  323. # Parse other parameters from the provided list
  324. for param, param_type in parameters_meta.items():
  325. param_match = re.search(rf"PARAMETER {param} (.+)", model_text, re.IGNORECASE)
  326. if param_match:
  327. value = param_match.group(1)
  328. try:
  329. if param_type is int:
  330. value = int(value)
  331. elif param_type is float:
  332. value = float(value)
  333. elif param_type is bool:
  334. value = value.lower() == "true"
  335. except Exception as e:
  336. log.exception(f"Failed to parse parameter {param}: {e}")
  337. continue
  338. data["params"][param] = value
  339. # Parse adapter
  340. adapter_match = re.search(r"ADAPTER (.+)", model_text, re.IGNORECASE)
  341. if adapter_match:
  342. data["params"]["adapter"] = adapter_match.group(1)
  343. # Parse system description
  344. system_desc_match = re.search(
  345. r'SYSTEM\s+"""(.+?)"""', model_text, re.DOTALL | re.IGNORECASE
  346. )
  347. system_desc_match_single = re.search(
  348. r"SYSTEM\s+([^\n]+)", model_text, re.IGNORECASE
  349. )
  350. if system_desc_match:
  351. data["params"]["system"] = system_desc_match.group(1).strip()
  352. elif system_desc_match_single:
  353. data["params"]["system"] = system_desc_match_single.group(1).strip()
  354. # Parse messages
  355. messages = []
  356. message_matches = re.findall(r"MESSAGE (\w+) (.+)", model_text, re.IGNORECASE)
  357. for role, content in message_matches:
  358. messages.append({"role": role, "content": content})
  359. if messages:
  360. data["params"]["messages"] = messages
  361. return data
  362. def convert_logit_bias_input_to_json(user_input):
  363. logit_bias_pairs = user_input.split(",")
  364. logit_bias_json = {}
  365. for pair in logit_bias_pairs:
  366. token, bias = pair.split(":")
  367. token = str(token.strip())
  368. bias = int(bias.strip())
  369. bias = 100 if bias > 100 else -100 if bias < -100 else bias
  370. logit_bias_json[token] = bias
  371. return json.dumps(logit_bias_json)
  372. def freeze(value):
  373. """
  374. Freeze a value to make it hashable.
  375. """
  376. if isinstance(value, dict):
  377. return frozenset((k, freeze(v)) for k, v in value.items())
  378. elif isinstance(value, list):
  379. return tuple(freeze(v) for v in value)
  380. return value
  381. def throttle(interval: float = 10.0):
  382. """
  383. Decorator to prevent a function from being called more than once within a specified duration.
  384. If the function is called again within the duration, it returns None. To avoid returning
  385. different types, the return type of the function should be Optional[T].
  386. :param interval: Duration in seconds to wait before allowing the function to be called again.
  387. """
  388. def decorator(func):
  389. last_calls = {}
  390. lock = threading.Lock()
  391. def wrapper(*args, **kwargs):
  392. if interval is None:
  393. return func(*args, **kwargs)
  394. key = (args, freeze(kwargs))
  395. now = time.time()
  396. if now - last_calls.get(key, 0) < interval:
  397. return None
  398. with lock:
  399. if now - last_calls.get(key, 0) < interval:
  400. return None
  401. last_calls[key] = now
  402. return func(*args, **kwargs)
  403. return wrapper
  404. return decorator