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.

position_helper.py 4.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. import os
  2. from collections import OrderedDict
  3. from collections.abc import Callable
  4. from typing import TypeVar
  5. from configs import dify_config
  6. from core.tools.utils.yaml_utils import load_yaml_file
  7. def get_position_map(folder_path: str, *, file_name: str = "_position.yaml") -> dict[str, int]:
  8. """
  9. Get the mapping from name to index from a YAML file
  10. :param folder_path:
  11. :param file_name: the YAML file name, default to '_position.yaml'
  12. :return: a dict with name as key and index as value
  13. """
  14. position_file_path = os.path.join(folder_path, file_name)
  15. yaml_content = load_yaml_file(file_path=position_file_path, default_value=[])
  16. positions = [item.strip() for item in yaml_content if item and isinstance(item, str) and item.strip()]
  17. return {name: index for index, name in enumerate(positions)}
  18. def get_tool_position_map(folder_path: str, file_name: str = "_position.yaml") -> dict[str, int]:
  19. """
  20. Get the mapping for tools from name to index from a YAML file.
  21. :param folder_path:
  22. :param file_name: the YAML file name, default to '_position.yaml'
  23. :return: a dict with name as key and index as value
  24. """
  25. position_map = get_position_map(folder_path, file_name=file_name)
  26. return pin_position_map(
  27. position_map,
  28. pin_list=dify_config.POSITION_TOOL_PINS_LIST,
  29. )
  30. def get_provider_position_map(folder_path: str, file_name: str = "_position.yaml") -> dict[str, int]:
  31. """
  32. Get the mapping for providers from name to index from a YAML file.
  33. :param folder_path:
  34. :param file_name: the YAML file name, default to '_position.yaml'
  35. :return: a dict with name as key and index as value
  36. """
  37. position_map = get_position_map(folder_path, file_name=file_name)
  38. return pin_position_map(
  39. position_map,
  40. pin_list=dify_config.POSITION_PROVIDER_PINS_LIST,
  41. )
  42. def pin_position_map(original_position_map: dict[str, int], pin_list: list[str]) -> dict[str, int]:
  43. """
  44. Pin the items in the pin list to the beginning of the position map.
  45. Overall logic: exclude > include > pin
  46. :param original_position_map: the position map to be sorted and filtered
  47. :param pin_list: the list of pins to be put at the beginning
  48. :return: the sorted position map
  49. """
  50. positions = sorted(original_position_map.keys(), key=lambda x: original_position_map[x])
  51. # Add pins to position map
  52. position_map = {name: idx for idx, name in enumerate(pin_list)}
  53. # Add remaining positions to position map
  54. start_idx = len(position_map)
  55. for name in positions:
  56. if name not in position_map:
  57. position_map[name] = start_idx
  58. start_idx += 1
  59. return position_map
  60. T = TypeVar("T")
  61. def is_filtered(
  62. include_set: set[str],
  63. exclude_set: set[str],
  64. data: T,
  65. name_func: Callable[[T], str],
  66. ) -> bool:
  67. """
  68. Check if the object should be filtered out.
  69. Overall logic: exclude > include > pin
  70. :param include_set: the set of names to be included
  71. :param exclude_set: the set of names to be excluded
  72. :param name_func: the function to get the name of the object
  73. :param data: the data to be filtered
  74. :return: True if the object should be filtered out, False otherwise
  75. """
  76. if not data:
  77. return False
  78. if not include_set and not exclude_set:
  79. return False
  80. name = name_func(data)
  81. if name in exclude_set: # exclude_set is prioritized
  82. return True
  83. if include_set and name not in include_set: # filter out only if include_set is not empty
  84. return True
  85. return False
  86. def sort_by_position_map(
  87. position_map: dict[str, int],
  88. data: list[T],
  89. name_func: Callable[[T], str],
  90. ):
  91. """
  92. Sort the objects by the position map.
  93. If the name of the object is not in the position map, it will be put at the end.
  94. :param position_map: the map holding positions in the form of {name: index}
  95. :param name_func: the function to get the name of the object
  96. :param data: the data to be sorted
  97. :return: the sorted objects
  98. """
  99. if not position_map or not data:
  100. return data
  101. return sorted(data, key=lambda x: position_map.get(name_func(x), float("inf")))
  102. def sort_to_dict_by_position_map(
  103. position_map: dict[str, int],
  104. data: list[T],
  105. name_func: Callable[[T], str],
  106. ):
  107. """
  108. Sort the objects into a ordered dict by the position map.
  109. If the name of the object is not in the position map, it will be put at the end.
  110. :param position_map: the map holding positions in the form of {name: index}
  111. :param name_func: the function to get the name of the object
  112. :param data: the data to be sorted
  113. :return: an OrderedDict with the sorted pairs of name and object
  114. """
  115. sorted_items = sort_by_position_map(position_map, data, name_func)
  116. return OrderedDict((name_func(item), item) for item in sorted_items)