tools.py 6.9 KB

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