tools.py 20 KB

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