tools.py 23 KB

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