tools.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. if callable.__doc__ and callable.__doc__.strip() != "":
  59. s = re.split(":(param|return)", callable.__doc__, 1)
  60. spec["description"] = s[0]
  61. else:
  62. spec["description"] = function_name
  63. # TODO: This needs to be a pydantic model
  64. tool_dict = {
  65. "toolkit_id": tool_id,
  66. "callable": callable,
  67. "spec": spec,
  68. "pydantic_model": function_to_pydantic_model(callable),
  69. "file_handler": hasattr(module, "file_handler") and module.file_handler,
  70. "citation": hasattr(module, "citation") and module.citation,
  71. }
  72. # TODO: if collision, prepend toolkit name
  73. if function_name in tools_dict:
  74. log.warning(f"Tool {function_name} already exists in another tools!")
  75. log.warning(f"Collision between {tools} and {tool_id}.")
  76. log.warning(f"Discarding {tools}.{function_name}")
  77. else:
  78. tools_dict[function_name] = tool_dict
  79. return tools_dict
  80. def parse_description(docstring: str | None) -> str:
  81. """
  82. Parse a function's docstring to extract the description.
  83. Args:
  84. docstring (str): The docstring to parse.
  85. Returns:
  86. str: The description.
  87. """
  88. if not docstring:
  89. return ""
  90. lines = [line.strip() for line in docstring.strip().split("\n")]
  91. description_lines: list[str] = []
  92. for line in lines:
  93. if re.match(r":param", line) or re.match(r":return", line):
  94. break
  95. description_lines.append(line)
  96. return "\n".join(description_lines)
  97. def parse_docstring(docstring):
  98. """
  99. Parse a function's docstring to extract parameter descriptions in reST format.
  100. Args:
  101. docstring (str): The docstring to parse.
  102. Returns:
  103. dict: A dictionary where keys are parameter names and values are descriptions.
  104. """
  105. if not docstring:
  106. return {}
  107. # Regex to match `:param name: description` format
  108. param_pattern = re.compile(r":param (\w+):\s*(.+)")
  109. param_descriptions = {}
  110. for line in docstring.splitlines():
  111. match = param_pattern.match(line.strip())
  112. if not match:
  113. continue
  114. param_name, param_description = match.groups()
  115. if param_name.startswith("__"):
  116. continue
  117. param_descriptions[param_name] = param_description
  118. return param_descriptions
  119. def function_to_pydantic_model(func: Callable) -> type[BaseModel]:
  120. """
  121. Converts a Python function's type hints and docstring to a Pydantic model,
  122. including support for nested types, default values, and descriptions.
  123. Args:
  124. func: The function whose type hints and docstring should be converted.
  125. model_name: The name of the generated Pydantic model.
  126. Returns:
  127. A Pydantic model class.
  128. """
  129. type_hints = get_type_hints(func)
  130. signature = inspect.signature(func)
  131. parameters = signature.parameters
  132. docstring = func.__doc__
  133. descriptions = parse_docstring(docstring)
  134. tool_description = parse_description(docstring)
  135. field_defs = {}
  136. for name, param in parameters.items():
  137. type_hint = type_hints.get(name, Any)
  138. default_value = param.default if param.default is not param.empty else ...
  139. description = descriptions.get(name, None)
  140. if not description:
  141. field_defs[name] = type_hint, default_value
  142. continue
  143. field_defs[name] = type_hint, Field(default_value, description=description)
  144. model = create_model(func.__name__, **field_defs)
  145. model.__doc__ = tool_description
  146. return model
  147. def get_callable_attributes(tool: object) -> list[Callable]:
  148. return [
  149. getattr(tool, func)
  150. for func in dir(tool)
  151. if callable(getattr(tool, func))
  152. and not func.startswith("__")
  153. and not inspect.isclass(getattr(tool, func))
  154. ]
  155. def get_tools_specs(tool_class: object) -> list[dict]:
  156. function_list = get_callable_attributes(tool_class)
  157. models = map(function_to_pydantic_model, function_list)
  158. return [convert_to_openai_function(tool) for tool in models]