tools.py 19 KB

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