You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # Copyright (c) 2024 Microsoft Corporation.
  2. # Licensed under the MIT License
  3. """
  4. Reference:
  5. - [graphrag](https://github.com/microsoft/graphrag)
  6. """
  7. import html
  8. import re
  9. from collections.abc import Callable
  10. from typing import Any
  11. ErrorHandlerFn = Callable[[BaseException | None, str | None, dict | None], None]
  12. def perform_variable_replacements(
  13. input: str, history: list[dict] | None = None, variables: dict | None = None
  14. ) -> str:
  15. """Perform variable replacements on the input string and in a chat log."""
  16. if history is None:
  17. history = []
  18. if variables is None:
  19. variables = {}
  20. result = input
  21. def replace_all(input: str) -> str:
  22. result = input
  23. for k, v in variables.items():
  24. result = result.replace(f"{{{k}}}", v)
  25. return result
  26. result = replace_all(result)
  27. for i, entry in enumerate(history):
  28. if entry.get("role") == "system":
  29. entry["content"] = replace_all(entry.get("content") or "")
  30. return result
  31. def clean_str(input: Any) -> str:
  32. """Clean an input string by removing HTML escapes, control characters, and other unwanted characters."""
  33. # If we get non-string input, just give it back
  34. if not isinstance(input, str):
  35. return input
  36. result = html.unescape(input.strip())
  37. # https://stackoverflow.com/questions/4324790/removing-control-characters-from-a-string-in-python
  38. return re.sub(r"[\"\x00-\x1f\x7f-\x9f]", "", result)
  39. def dict_has_keys_with_types(
  40. data: dict, expected_fields: list[tuple[str, type]]
  41. ) -> bool:
  42. """Return True if the given dictionary has the given keys with the given types."""
  43. for field, field_type in expected_fields:
  44. if field not in data:
  45. return False
  46. value = data[field]
  47. if not isinstance(value, field_type):
  48. return False
  49. return True