tools.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. import inspect
  2. import logging
  3. from typing import Awaitable, Callable, get_type_hints
  4. from open_webui.apps.webui.models.tools import Tools
  5. from open_webui.apps.webui.models.users import UserModel
  6. from open_webui.apps.webui.utils import load_tools_module_by_id
  7. from open_webui.utils.schemas import json_schema_to_model
  8. log = logging.getLogger(__name__)
  9. def apply_extra_params_to_tool_function(
  10. function: Callable, extra_params: dict
  11. ) -> Callable[..., Awaitable]:
  12. sig = inspect.signature(function)
  13. extra_params = {
  14. key: value for key, value in extra_params.items() if key in sig.parameters
  15. }
  16. is_coroutine = inspect.iscoroutinefunction(function)
  17. async def new_function(**kwargs):
  18. extra_kwargs = kwargs | extra_params
  19. if is_coroutine:
  20. return await function(**extra_kwargs)
  21. return function(**extra_kwargs)
  22. return new_function
  23. # Mutation on extra_params
  24. def get_tools(
  25. webui_app, tool_ids: list[str], user: UserModel, extra_params: dict
  26. ) -> dict[str, dict]:
  27. tools = {}
  28. for tool_id in tool_ids:
  29. toolkit = Tools.get_tool_by_id(tool_id)
  30. if toolkit is None:
  31. continue
  32. module = webui_app.state.TOOLS.get(tool_id, None)
  33. if module is None:
  34. module, _ = load_tools_module_by_id(tool_id)
  35. webui_app.state.TOOLS[tool_id] = module
  36. extra_params["__id__"] = tool_id
  37. if hasattr(module, "valves") and hasattr(module, "Valves"):
  38. valves = Tools.get_tool_valves_by_id(tool_id) or {}
  39. module.valves = module.Valves(**valves)
  40. if hasattr(module, "UserValves"):
  41. extra_params["__user__"]["valves"] = module.UserValves( # type: ignore
  42. **Tools.get_user_valves_by_id_and_user_id(tool_id, user.id)
  43. )
  44. for spec in toolkit.specs:
  45. # TODO: Fix hack for OpenAI API
  46. for val in spec.get("parameters", {}).get("properties", {}).values():
  47. if val["type"] == "str":
  48. val["type"] = "string"
  49. function_name = spec["name"]
  50. # convert to function that takes only model params and inserts custom params
  51. original_func = getattr(module, function_name)
  52. callable = apply_extra_params_to_tool_function(original_func, extra_params)
  53. if hasattr(original_func, "__doc__"):
  54. callable.__doc__ = original_func.__doc__
  55. # TODO: This needs to be a pydantic model
  56. tool_dict = {
  57. "toolkit_id": tool_id,
  58. "callable": callable,
  59. "spec": spec,
  60. "pydantic_model": json_schema_to_model(spec),
  61. "file_handler": hasattr(module, "file_handler") and module.file_handler,
  62. "citation": hasattr(module, "citation") and module.citation,
  63. }
  64. # TODO: if collision, prepend toolkit name
  65. if function_name in tools:
  66. log.warning(f"Tool {function_name} already exists in another toolkit!")
  67. log.warning(f"Collision between {toolkit} and {tool_id}.")
  68. log.warning(f"Discarding {toolkit}.{function_name}")
  69. else:
  70. tools[function_name] = tool_dict
  71. return tools
  72. def doc_to_dict(docstring):
  73. lines = docstring.split("\n")
  74. description = lines[1].strip()
  75. param_dict = {}
  76. for line in lines:
  77. if ":param" in line:
  78. line = line.replace(":param", "").strip()
  79. param, desc = line.split(":", 1)
  80. param_dict[param.strip()] = desc.strip()
  81. ret_dict = {"description": description, "params": param_dict}
  82. return ret_dict
  83. def get_tools_specs(tools) -> list[dict]:
  84. function_list = [
  85. {"name": func, "function": getattr(tools, func)}
  86. for func in dir(tools)
  87. if callable(getattr(tools, func))
  88. and not func.startswith("__")
  89. and not inspect.isclass(getattr(tools, func))
  90. ]
  91. specs = []
  92. for function_item in function_list:
  93. function_name = function_item["name"]
  94. function = function_item["function"]
  95. function_doc = doc_to_dict(function.__doc__ or function_name)
  96. specs.append(
  97. {
  98. "name": function_name,
  99. # TODO: multi-line desc?
  100. "description": function_doc.get("description", function_name),
  101. "parameters": {
  102. "type": "object",
  103. "properties": {
  104. param_name: {
  105. "type": param_annotation.__name__.lower(),
  106. **(
  107. {
  108. "enum": (
  109. str(param_annotation.__args__)
  110. if hasattr(param_annotation, "__args__")
  111. else None
  112. )
  113. }
  114. if hasattr(param_annotation, "__args__")
  115. else {}
  116. ),
  117. "description": function_doc.get("params", {}).get(
  118. param_name, param_name
  119. ),
  120. }
  121. for param_name, param_annotation in get_type_hints(
  122. function
  123. ).items()
  124. if param_name != "return"
  125. and not (
  126. param_name.startswith("__") and param_name.endswith("__")
  127. )
  128. },
  129. "required": [
  130. name
  131. for name, param in inspect.signature(
  132. function
  133. ).parameters.items()
  134. if param.default is param.empty
  135. and not (name.startswith("__") and name.endswith("__"))
  136. ],
  137. },
  138. }
  139. )
  140. return specs