tools.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. import inspect
  2. import logging
  3. import re
  4. from typing import Any, Awaitable, Callable, get_type_hints
  5. from functools import update_wrapper, partial
  6. from fastapi import Request
  7. from pydantic import BaseModel, Field, create_model
  8. from langchain_core.utils.function_calling import convert_to_openai_function
  9. from open_webui.models.tools import Tools
  10. from open_webui.models.users import UserModel
  11. from open_webui.utils.plugin import load_tools_module_by_id
  12. log = logging.getLogger(__name__)
  13. def apply_extra_params_to_tool_function(
  14. function: Callable, extra_params: dict
  15. ) -> Callable[..., Awaitable]:
  16. sig = inspect.signature(function)
  17. extra_params = {k: v for k, v in extra_params.items() if k in sig.parameters}
  18. partial_func = partial(function, **extra_params)
  19. if inspect.iscoroutinefunction(function):
  20. update_wrapper(partial_func, function)
  21. return partial_func
  22. async def new_function(*args, **kwargs):
  23. return partial_func(*args, **kwargs)
  24. update_wrapper(new_function, function)
  25. return new_function
  26. # Mutation on extra_params
  27. def get_tools(
  28. request: Request, tool_ids: list[str], user: UserModel, extra_params: dict
  29. ) -> dict[str, dict]:
  30. tools_dict = {}
  31. for tool_id in tool_ids:
  32. tools = Tools.get_tool_by_id(tool_id)
  33. if tools is None:
  34. continue
  35. module = request.app.state.TOOLS.get(tool_id, None)
  36. if module is None:
  37. module, _ = load_tools_module_by_id(tool_id)
  38. request.app.state.TOOLS[tool_id] = module
  39. extra_params["__id__"] = tool_id
  40. if hasattr(module, "valves") and hasattr(module, "Valves"):
  41. valves = Tools.get_tool_valves_by_id(tool_id) or {}
  42. module.valves = module.Valves(**valves)
  43. if hasattr(module, "UserValves"):
  44. extra_params["__user__"]["valves"] = module.UserValves( # type: ignore
  45. **Tools.get_user_valves_by_id_and_user_id(tool_id, user.id)
  46. )
  47. for spec in tools.specs:
  48. # Remove internal parameters
  49. spec["parameters"]["properties"] = {
  50. key: val
  51. for key, val in spec["parameters"]["properties"].items()
  52. if not key.startswith("__")
  53. }
  54. function_name = spec["name"]
  55. # convert to function that takes only model params and inserts custom params
  56. original_func = getattr(module, function_name)
  57. callable = apply_extra_params_to_tool_function(original_func, extra_params)
  58. # TODO: This needs to be a pydantic model
  59. tool_dict = {
  60. "toolkit_id": tool_id,
  61. "callable": callable,
  62. "spec": spec,
  63. "pydantic_model": function_to_pydantic_model(callable),
  64. "file_handler": hasattr(module, "file_handler") and module.file_handler,
  65. "citation": hasattr(module, "citation") and module.citation,
  66. }
  67. # TODO: if collision, prepend toolkit name
  68. if function_name in tools_dict:
  69. log.warning(f"Tool {function_name} already exists in another tools!")
  70. log.warning(f"Collision between {tools} and {tool_id}.")
  71. log.warning(f"Discarding {tools}.{function_name}")
  72. else:
  73. tools_dict[function_name] = tool_dict
  74. return tools_dict
  75. def parse_description(docstring: str | None) -> str:
  76. """
  77. Parse a function's docstring to extract the description.
  78. Args:
  79. docstring (str): The docstring to parse.
  80. Returns:
  81. str: The description.
  82. """
  83. if not docstring:
  84. return ""
  85. lines = [line.strip() for line in docstring.strip().split("\n")]
  86. description_lines: list[str] = []
  87. for line in lines:
  88. if re.match(r":param", line) or re.match(r":return", line):
  89. break
  90. description_lines.append(line)
  91. return "\n".join(description_lines)
  92. def parse_docstring(docstring):
  93. """
  94. Parse a function's docstring to extract parameter descriptions in reST format.
  95. Args:
  96. docstring (str): The docstring to parse.
  97. Returns:
  98. dict: A dictionary where keys are parameter names and values are descriptions.
  99. """
  100. if not docstring:
  101. return {}
  102. # Regex to match `:param name: description` format
  103. param_pattern = re.compile(r":param (\w+):\s*(.+)")
  104. param_descriptions = {}
  105. for line in docstring.splitlines():
  106. match = param_pattern.match(line.strip())
  107. if not match:
  108. continue
  109. param_name, param_description = match.groups()
  110. if param_name.startswith("__"):
  111. continue
  112. param_descriptions[param_name] = param_description
  113. return param_descriptions
  114. def function_to_pydantic_model(func: Callable) -> type[BaseModel]:
  115. """
  116. Converts a Python function's type hints and docstring to a Pydantic model,
  117. including support for nested types, default values, and descriptions.
  118. Args:
  119. func: The function whose type hints and docstring should be converted.
  120. model_name: The name of the generated Pydantic model.
  121. Returns:
  122. A Pydantic model class.
  123. """
  124. type_hints = get_type_hints(func)
  125. signature = inspect.signature(func)
  126. parameters = signature.parameters
  127. docstring = func.__doc__
  128. descriptions = parse_docstring(docstring)
  129. tool_description = parse_description(docstring)
  130. field_defs = {}
  131. for name, param in parameters.items():
  132. type_hint = type_hints.get(name, Any)
  133. default_value = param.default if param.default is not param.empty else ...
  134. description = descriptions.get(name, None)
  135. if not description:
  136. field_defs[name] = type_hint, default_value
  137. continue
  138. field_defs[name] = type_hint, Field(default_value, description=description)
  139. model = create_model(func.__name__, **field_defs)
  140. model.__doc__ = tool_description
  141. return model
  142. def get_callable_attributes(tool: object) -> list[Callable]:
  143. return [
  144. getattr(tool, func)
  145. for func in dir(tool)
  146. if callable(getattr(tool, func))
  147. and not func.startswith("__")
  148. and not inspect.isclass(getattr(tool, func))
  149. ]
  150. def get_tools_specs(tool_class: object) -> list[dict]:
  151. function_list = get_callable_attributes(tool_class)
  152. models = map(function_to_pydantic_model, function_list)
  153. return [convert_to_openai_function(tool) for tool in models]