helper.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. from __future__ import annotations
  2. import random
  3. import string
  4. from ..typing import Messages, Cookies
  5. def format_prompt(messages: Messages, add_special_tokens=False) -> str:
  6. """
  7. Format a series of messages into a single string, optionally adding special tokens.
  8. Args:
  9. messages (Messages): A list of message dictionaries, each containing 'role' and 'content'.
  10. add_special_tokens (bool): Whether to add special formatting tokens.
  11. Returns:
  12. str: A formatted string containing all messages.
  13. """
  14. if not add_special_tokens and len(messages) <= 1:
  15. return messages[0]["content"]
  16. formatted = "\n".join([
  17. f'{message["role"].capitalize()}: {message["content"]}'
  18. for message in messages
  19. ])
  20. return f"{formatted}\nAssistant:"
  21. def get_random_string(length: int = 10) -> str:
  22. """
  23. Generate a random string of specified length, containing lowercase letters and digits.
  24. Args:
  25. length (int, optional): Length of the random string to generate. Defaults to 10.
  26. Returns:
  27. str: A random string of the specified length.
  28. """
  29. return ''.join(
  30. random.choice(string.ascii_lowercase + string.digits)
  31. for _ in range(length)
  32. )
  33. def get_random_hex(length: int = 32) -> str:
  34. """
  35. Generate a random hexadecimal string with n length.
  36. Returns:
  37. str: A random hexadecimal string of n characters.
  38. """
  39. return ''.join(
  40. random.choice("abcdef" + string.digits)
  41. for _ in range(length)
  42. )
  43. def filter_none(**kwargs) -> dict:
  44. return {
  45. key: value
  46. for key, value in kwargs.items()
  47. if value is not None
  48. }
  49. def format_cookies(cookies: Cookies) -> str:
  50. return "; ".join([f"{k}={v}" for k, v in cookies.items()])