tools.py 19 KB

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