tools.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. import inspect
  2. import logging
  3. import re
  4. import inspect
  5. import aiohttp
  6. import asyncio
  7. from typing import Any, Awaitable, Callable, get_type_hints, Dict, List, Union, Optional
  8. from functools import update_wrapper, partial
  9. from fastapi import Request
  10. from pydantic import BaseModel, Field, create_model
  11. from langchain_core.utils.function_calling import convert_to_openai_function
  12. from open_webui.models.tools import Tools
  13. from open_webui.models.users import UserModel
  14. from open_webui.utils.plugin import load_tools_module_by_id
  15. import copy
  16. log = logging.getLogger(__name__)
  17. def apply_extra_params_to_tool_function(
  18. function: Callable, extra_params: dict
  19. ) -> Callable[..., Awaitable]:
  20. sig = inspect.signature(function)
  21. extra_params = {k: v for k, v in extra_params.items() if k in sig.parameters}
  22. partial_func = partial(function, **extra_params)
  23. if inspect.iscoroutinefunction(function):
  24. update_wrapper(partial_func, function)
  25. return partial_func
  26. async def new_function(*args, **kwargs):
  27. return partial_func(*args, **kwargs)
  28. update_wrapper(new_function, function)
  29. return new_function
  30. # Mutation on extra_params
  31. def get_tools(
  32. request: Request, tool_ids: list[str], user: UserModel, extra_params: dict
  33. ) -> dict[str, dict]:
  34. tools_dict = {}
  35. for tool_id in tool_ids:
  36. tools = Tools.get_tool_by_id(tool_id)
  37. if tools is None:
  38. if tool_id.startswith("server:"):
  39. server_idx = int(tool_id.split(":")[1])
  40. tool_server_data = request.app.state.TOOL_SERVERS[server_idx]
  41. tool_dict = {
  42. "spec": spec,
  43. "callable": callable,
  44. "toolkit_id": tool_id,
  45. # Misc info
  46. "metadata": {
  47. "file_handler": hasattr(module, "file_handler")
  48. and module.file_handler,
  49. "citation": hasattr(module, "citation") and module.citation,
  50. },
  51. }
  52. else:
  53. module = request.app.state.TOOLS.get(tool_id, None)
  54. if module is None:
  55. module, _ = load_tools_module_by_id(tool_id)
  56. request.app.state.TOOLS[tool_id] = module
  57. extra_params["__id__"] = tool_id
  58. if hasattr(module, "valves") and hasattr(module, "Valves"):
  59. valves = Tools.get_tool_valves_by_id(tool_id) or {}
  60. module.valves = module.Valves(**valves)
  61. if hasattr(module, "UserValves"):
  62. extra_params["__user__"]["valves"] = module.UserValves( # type: ignore
  63. **Tools.get_user_valves_by_id_and_user_id(tool_id, user.id)
  64. )
  65. for spec in tools.specs:
  66. # TODO: Fix hack for OpenAI API
  67. # Some times breaks OpenAI but others don't. Leaving the comment
  68. for val in spec.get("parameters", {}).get("properties", {}).values():
  69. if val["type"] == "str":
  70. val["type"] = "string"
  71. # Remove internal parameters
  72. spec["parameters"]["properties"] = {
  73. key: val
  74. for key, val in spec["parameters"]["properties"].items()
  75. if not key.startswith("__")
  76. }
  77. function_name = spec["name"]
  78. # convert to function that takes only model params and inserts custom params
  79. original_func = getattr(module, function_name)
  80. callable = apply_extra_params_to_tool_function(
  81. original_func, extra_params
  82. )
  83. if callable.__doc__ and callable.__doc__.strip() != "":
  84. s = re.split(":(param|return)", callable.__doc__, 1)
  85. spec["description"] = s[0]
  86. else:
  87. spec["description"] = function_name
  88. tool_dict = {
  89. "spec": spec,
  90. "callable": callable,
  91. "toolkit_id": tool_id,
  92. # Misc info
  93. "metadata": {
  94. "file_handler": hasattr(module, "file_handler")
  95. and module.file_handler,
  96. "citation": hasattr(module, "citation") and module.citation,
  97. },
  98. }
  99. # TODO: if collision, prepend toolkit name
  100. if function_name in tools_dict:
  101. log.warning(
  102. f"Tool {function_name} already exists in another tools!"
  103. )
  104. log.warning(f"Collision between {tools} and {tool_id}.")
  105. log.warning(f"Discarding {tools}.{function_name}")
  106. else:
  107. tools_dict[function_name] = tool_dict
  108. return tools_dict
  109. def parse_description(docstring: str | None) -> str:
  110. """
  111. Parse a function's docstring to extract the description.
  112. Args:
  113. docstring (str): The docstring to parse.
  114. Returns:
  115. str: The description.
  116. """
  117. if not docstring:
  118. return ""
  119. lines = [line.strip() for line in docstring.strip().split("\n")]
  120. description_lines: list[str] = []
  121. for line in lines:
  122. if re.match(r":param", line) or re.match(r":return", line):
  123. break
  124. description_lines.append(line)
  125. return "\n".join(description_lines)
  126. def parse_docstring(docstring):
  127. """
  128. Parse a function's docstring to extract parameter descriptions in reST format.
  129. Args:
  130. docstring (str): The docstring to parse.
  131. Returns:
  132. dict: A dictionary where keys are parameter names and values are descriptions.
  133. """
  134. if not docstring:
  135. return {}
  136. # Regex to match `:param name: description` format
  137. param_pattern = re.compile(r":param (\w+):\s*(.+)")
  138. param_descriptions = {}
  139. for line in docstring.splitlines():
  140. match = param_pattern.match(line.strip())
  141. if not match:
  142. continue
  143. param_name, param_description = match.groups()
  144. if param_name.startswith("__"):
  145. continue
  146. param_descriptions[param_name] = param_description
  147. return param_descriptions
  148. def function_to_pydantic_model(func: Callable) -> type[BaseModel]:
  149. """
  150. Converts a Python function's type hints and docstring to a Pydantic model,
  151. including support for nested types, default values, and descriptions.
  152. Args:
  153. func: The function whose type hints and docstring should be converted.
  154. model_name: The name of the generated Pydantic model.
  155. Returns:
  156. A Pydantic model class.
  157. """
  158. type_hints = get_type_hints(func)
  159. signature = inspect.signature(func)
  160. parameters = signature.parameters
  161. docstring = func.__doc__
  162. descriptions = parse_docstring(docstring)
  163. tool_description = parse_description(docstring)
  164. field_defs = {}
  165. for name, param in parameters.items():
  166. type_hint = type_hints.get(name, Any)
  167. default_value = param.default if param.default is not param.empty else ...
  168. description = descriptions.get(name, None)
  169. if not description:
  170. field_defs[name] = type_hint, default_value
  171. continue
  172. field_defs[name] = type_hint, Field(default_value, description=description)
  173. model = create_model(func.__name__, **field_defs)
  174. model.__doc__ = tool_description
  175. return model
  176. def get_callable_attributes(tool: object) -> list[Callable]:
  177. return [
  178. getattr(tool, func)
  179. for func in dir(tool)
  180. if callable(getattr(tool, func))
  181. and not func.startswith("__")
  182. and not inspect.isclass(getattr(tool, func))
  183. ]
  184. def get_tools_specs(tool_class: object) -> list[dict]:
  185. function_list = get_callable_attributes(tool_class)
  186. function_model_list = map(function_to_pydantic_model, function_list)
  187. return [
  188. convert_to_openai_function(function_model)
  189. for function_model in function_model_list
  190. ]
  191. def resolve_schema(schema, components):
  192. """
  193. Recursively resolves a JSON schema using OpenAPI components.
  194. """
  195. if not schema:
  196. return {}
  197. if "$ref" in schema:
  198. ref_path = schema["$ref"]
  199. ref_parts = ref_path.strip("#/").split("/")
  200. resolved = components
  201. for part in ref_parts[1:]: # Skip the initial 'components'
  202. resolved = resolved.get(part, {})
  203. return resolve_schema(resolved, components)
  204. resolved_schema = copy.deepcopy(schema)
  205. # Recursively resolve inner schemas
  206. if "properties" in resolved_schema:
  207. for prop, prop_schema in resolved_schema["properties"].items():
  208. resolved_schema["properties"][prop] = resolve_schema(
  209. prop_schema, components
  210. )
  211. if "items" in resolved_schema:
  212. resolved_schema["items"] = resolve_schema(resolved_schema["items"], components)
  213. return resolved_schema
  214. def convert_openapi_to_tool_payload(openapi_spec):
  215. """
  216. Converts an OpenAPI specification into a custom tool payload structure.
  217. Args:
  218. openapi_spec (dict): The OpenAPI specification as a Python dict.
  219. Returns:
  220. list: A list of tool payloads.
  221. """
  222. tool_payload = []
  223. for path, methods in openapi_spec.get("paths", {}).items():
  224. for method, operation in methods.items():
  225. tool = {
  226. "type": "function",
  227. "name": operation.get("operationId"),
  228. "description": operation.get("summary", "No description available."),
  229. "parameters": {"type": "object", "properties": {}, "required": []},
  230. }
  231. # Extract path and query parameters
  232. for param in operation.get("parameters", []):
  233. param_name = param["name"]
  234. param_schema = param.get("schema", {})
  235. tool["parameters"]["properties"][param_name] = {
  236. "type": param_schema.get("type"),
  237. "description": param_schema.get("description", ""),
  238. }
  239. if param.get("required"):
  240. tool["parameters"]["required"].append(param_name)
  241. # Extract and resolve requestBody if available
  242. request_body = operation.get("requestBody")
  243. if request_body:
  244. content = request_body.get("content", {})
  245. json_schema = content.get("application/json", {}).get("schema")
  246. if json_schema:
  247. resolved_schema = resolve_schema(
  248. json_schema, openapi_spec.get("components", {})
  249. )
  250. if resolved_schema.get("properties"):
  251. tool["parameters"]["properties"].update(
  252. resolved_schema["properties"]
  253. )
  254. if "required" in resolved_schema:
  255. tool["parameters"]["required"] = list(
  256. set(
  257. tool["parameters"]["required"]
  258. + resolved_schema["required"]
  259. )
  260. )
  261. elif resolved_schema.get("type") == "array":
  262. tool["parameters"] = resolved_schema # special case for array
  263. tool_payload.append(tool)
  264. return tool_payload
  265. async def get_tool_server_data(token: str, url: str) -> Dict[str, Any]:
  266. headers = {
  267. "Accept": "application/json",
  268. "Content-Type": "application/json",
  269. }
  270. if token:
  271. headers["Authorization"] = f"Bearer {token}"
  272. error = None
  273. try:
  274. async with aiohttp.ClientSession() as session:
  275. async with session.get(url, headers=headers) as response:
  276. if response.status != 200:
  277. error_body = await response.json()
  278. raise Exception(error_body)
  279. res = await response.json()
  280. except Exception as err:
  281. print("Error:", err)
  282. if isinstance(err, dict) and "detail" in err:
  283. error = err["detail"]
  284. else:
  285. error = str(err)
  286. raise Exception(error)
  287. data = {
  288. "openapi": res,
  289. "info": res.get("info", {}),
  290. "specs": convert_openapi_to_tool_payload(res),
  291. }
  292. print("Fetched data:", data)
  293. return data
  294. async def get_tool_servers_data(
  295. servers: List[Dict[str, Any]], session_token: Optional[str] = None
  296. ) -> List[Dict[str, Any]]:
  297. # Prepare list of enabled servers along with their original index
  298. server_entries = []
  299. for idx, server in enumerate(servers):
  300. if server.get("config", {}).get("enable"):
  301. url_path = server.get("path", "openapi.json")
  302. full_url = f"{server.get('url')}/{url_path}"
  303. auth_type = server.get("auth_type", "bearer")
  304. token = None
  305. if auth_type == "bearer":
  306. token = server.get("key", "")
  307. elif auth_type == "session":
  308. token = session_token
  309. server_entries.append((idx, server, full_url, token))
  310. # Create async tasks to fetch data
  311. tasks = [get_tool_server_data(token, url) for (_, _, url, token) in server_entries]
  312. # Execute tasks concurrently
  313. responses = await asyncio.gather(*tasks, return_exceptions=True)
  314. # Build final results with index and server metadata
  315. results = []
  316. for (idx, server, url, _), response in zip(server_entries, responses):
  317. if isinstance(response, Exception):
  318. print(f"Failed to connect to {url} OpenAPI tool server")
  319. continue
  320. results.append(
  321. {
  322. "idx": idx,
  323. "url": server.get("url"),
  324. "openapi": response.get("openapi"),
  325. "info": response.get("info"),
  326. "specs": response.get("specs"),
  327. }
  328. )
  329. return results
  330. async def execute_tool_server(
  331. token: str, url: str, name: str, params: Dict[str, Any], server_data: Dict[str, Any]
  332. ) -> Any:
  333. error = None
  334. try:
  335. openapi = server_data.get("openapi", {})
  336. paths = openapi.get("paths", {})
  337. matching_route = None
  338. for route_path, methods in paths.items():
  339. for http_method, operation in methods.items():
  340. if isinstance(operation, dict) and operation.get("operationId") == name:
  341. matching_route = (route_path, methods)
  342. break
  343. if matching_route:
  344. break
  345. if not matching_route:
  346. raise Exception(f"No matching route found for operationId: {name}")
  347. route_path, methods = matching_route
  348. method_entry = None
  349. for http_method, operation in methods.items():
  350. if operation.get("operationId") == name:
  351. method_entry = (http_method.lower(), operation)
  352. break
  353. if not method_entry:
  354. raise Exception(f"No matching method found for operationId: {name}")
  355. http_method, operation = method_entry
  356. path_params = {}
  357. query_params = {}
  358. body_params = {}
  359. for param in operation.get("parameters", []):
  360. param_name = param["name"]
  361. param_in = param["in"]
  362. if param_name in params:
  363. if param_in == "path":
  364. path_params[param_name] = params[param_name]
  365. elif param_in == "query":
  366. query_params[param_name] = params[param_name]
  367. final_url = f"{url}{route_path}"
  368. for key, value in path_params.items():
  369. final_url = final_url.replace(f"{{{key}}}", str(value))
  370. if query_params:
  371. query_string = "&".join(f"{k}={v}" for k, v in query_params.items())
  372. final_url = f"{final_url}?{query_string}"
  373. if operation.get("requestBody", {}).get("content"):
  374. if params:
  375. body_params = params
  376. else:
  377. raise Exception(
  378. f"Request body expected for operation '{name}' but none found."
  379. )
  380. headers = {"Content-Type": "application/json"}
  381. if token:
  382. headers["Authorization"] = f"Bearer {token}"
  383. async with aiohttp.ClientSession() as session:
  384. request_method = getattr(session, http_method.lower())
  385. if http_method in ["post", "put", "patch"]:
  386. async with request_method(
  387. final_url, json=body_params, headers=headers
  388. ) as response:
  389. if response.status >= 400:
  390. text = await response.text()
  391. raise Exception(f"HTTP error {response.status}: {text}")
  392. return await response.json()
  393. else:
  394. async with request_method(final_url, headers=headers) as response:
  395. if response.status >= 400:
  396. text = await response.text()
  397. raise Exception(f"HTTP error {response.status}: {text}")
  398. return await response.json()
  399. except Exception as err:
  400. error = str(err)
  401. print("API Request Error:", error)
  402. return {"error": error}