tools.py 22 KB

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