tools.py 22 KB

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