tools.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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("summary", "No description available."),
  268. "parameters": {"type": "object", "properties": {}, "required": []},
  269. }
  270. # Extract path and query parameters
  271. for param in operation.get("parameters", []):
  272. param_name = param["name"]
  273. param_schema = param.get("schema", {})
  274. tool["parameters"]["properties"][param_name] = {
  275. "type": param_schema.get("type"),
  276. "description": param_schema.get("description", ""),
  277. }
  278. if param.get("required"):
  279. tool["parameters"]["required"].append(param_name)
  280. # Extract and resolve requestBody if available
  281. request_body = operation.get("requestBody")
  282. if request_body:
  283. content = request_body.get("content", {})
  284. json_schema = content.get("application/json", {}).get("schema")
  285. if json_schema:
  286. resolved_schema = resolve_schema(
  287. json_schema, openapi_spec.get("components", {})
  288. )
  289. if resolved_schema.get("properties"):
  290. tool["parameters"]["properties"].update(
  291. resolved_schema["properties"]
  292. )
  293. if "required" in resolved_schema:
  294. tool["parameters"]["required"] = list(
  295. set(
  296. tool["parameters"]["required"]
  297. + resolved_schema["required"]
  298. )
  299. )
  300. elif resolved_schema.get("type") == "array":
  301. tool["parameters"] = resolved_schema # special case for array
  302. tool_payload.append(tool)
  303. return tool_payload
  304. async def get_tool_server_data(token: str, url: str) -> Dict[str, Any]:
  305. headers = {
  306. "Accept": "application/json",
  307. "Content-Type": "application/json",
  308. }
  309. if token:
  310. headers["Authorization"] = f"Bearer {token}"
  311. error = None
  312. try:
  313. async with aiohttp.ClientSession() as session:
  314. async with session.get(url, headers=headers) as response:
  315. if response.status != 200:
  316. error_body = await response.json()
  317. raise Exception(error_body)
  318. res = await response.json()
  319. except Exception as err:
  320. print("Error:", err)
  321. if isinstance(err, dict) and "detail" in err:
  322. error = err["detail"]
  323. else:
  324. error = str(err)
  325. raise Exception(error)
  326. data = {
  327. "openapi": res,
  328. "info": res.get("info", {}),
  329. "specs": convert_openapi_to_tool_payload(res),
  330. }
  331. print("Fetched data:", data)
  332. return data
  333. async def get_tool_servers_data(
  334. servers: List[Dict[str, Any]], session_token: Optional[str] = None
  335. ) -> List[Dict[str, Any]]:
  336. # Prepare list of enabled servers along with their original index
  337. server_entries = []
  338. for idx, server in enumerate(servers):
  339. if server.get("config", {}).get("enable"):
  340. url_path = server.get("path", "openapi.json")
  341. full_url = f"{server.get('url')}/{url_path}"
  342. auth_type = server.get("auth_type", "bearer")
  343. token = None
  344. if auth_type == "bearer":
  345. token = server.get("key", "")
  346. elif auth_type == "session":
  347. token = session_token
  348. server_entries.append((idx, server, full_url, token))
  349. # Create async tasks to fetch data
  350. tasks = [get_tool_server_data(token, url) for (_, _, url, token) in server_entries]
  351. # Execute tasks concurrently
  352. responses = await asyncio.gather(*tasks, return_exceptions=True)
  353. # Build final results with index and server metadata
  354. results = []
  355. for (idx, server, url, _), response in zip(server_entries, responses):
  356. if isinstance(response, Exception):
  357. print(f"Failed to connect to {url} OpenAPI tool server")
  358. continue
  359. results.append(
  360. {
  361. "idx": idx,
  362. "url": server.get("url"),
  363. "openapi": response.get("openapi"),
  364. "info": response.get("info"),
  365. "specs": response.get("specs"),
  366. }
  367. )
  368. return results
  369. async def execute_tool_server(
  370. token: str, url: str, name: str, params: Dict[str, Any], server_data: Dict[str, Any]
  371. ) -> Any:
  372. error = None
  373. try:
  374. openapi = server_data.get("openapi", {})
  375. paths = openapi.get("paths", {})
  376. matching_route = None
  377. for route_path, methods in paths.items():
  378. for http_method, operation in methods.items():
  379. if isinstance(operation, dict) and operation.get("operationId") == name:
  380. matching_route = (route_path, methods)
  381. break
  382. if matching_route:
  383. break
  384. if not matching_route:
  385. raise Exception(f"No matching route found for operationId: {name}")
  386. route_path, methods = matching_route
  387. method_entry = None
  388. for http_method, operation in methods.items():
  389. if operation.get("operationId") == name:
  390. method_entry = (http_method.lower(), operation)
  391. break
  392. if not method_entry:
  393. raise Exception(f"No matching method found for operationId: {name}")
  394. http_method, operation = method_entry
  395. path_params = {}
  396. query_params = {}
  397. body_params = {}
  398. for param in operation.get("parameters", []):
  399. param_name = param["name"]
  400. param_in = param["in"]
  401. if param_name in params:
  402. if param_in == "path":
  403. path_params[param_name] = params[param_name]
  404. elif param_in == "query":
  405. query_params[param_name] = params[param_name]
  406. final_url = f"{url}{route_path}"
  407. for key, value in path_params.items():
  408. final_url = final_url.replace(f"{{{key}}}", str(value))
  409. if query_params:
  410. query_string = "&".join(f"{k}={v}" for k, v in query_params.items())
  411. final_url = f"{final_url}?{query_string}"
  412. if operation.get("requestBody", {}).get("content"):
  413. if params:
  414. body_params = params
  415. else:
  416. raise Exception(
  417. f"Request body expected for operation '{name}' but none found."
  418. )
  419. headers = {"Content-Type": "application/json"}
  420. if token:
  421. headers["Authorization"] = f"Bearer {token}"
  422. async with aiohttp.ClientSession() as session:
  423. request_method = getattr(session, http_method.lower())
  424. if http_method in ["post", "put", "patch"]:
  425. async with request_method(
  426. final_url, json=body_params, headers=headers
  427. ) as response:
  428. if response.status >= 400:
  429. text = await response.text()
  430. raise Exception(f"HTTP error {response.status}: {text}")
  431. return await response.json()
  432. else:
  433. async with request_method(final_url, headers=headers) as response:
  434. if response.status >= 400:
  435. text = await response.text()
  436. raise Exception(f"HTTP error {response.status}: {text}")
  437. return await response.json()
  438. except Exception as err:
  439. error = str(err)
  440. print("API Request Error:", error)
  441. return {"error": error}