tools.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  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. AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER_DATA,
  35. AIOHTTP_CLIENT_SESSION_TOOL_SERVER_SSL,
  36. )
  37. import copy
  38. log = logging.getLogger(__name__)
  39. def get_async_tool_function_and_apply_extra_params(
  40. function: Callable, extra_params: dict
  41. ) -> Callable[..., Awaitable]:
  42. sig = inspect.signature(function)
  43. extra_params = {k: v for k, v in extra_params.items() if k in sig.parameters}
  44. partial_func = partial(function, **extra_params)
  45. if inspect.iscoroutinefunction(function):
  46. update_wrapper(partial_func, function)
  47. return partial_func
  48. else:
  49. # Make it a coroutine function
  50. async def new_function(*args, **kwargs):
  51. return partial_func(*args, **kwargs)
  52. update_wrapper(new_function, function)
  53. return new_function
  54. def get_tools(
  55. request: Request, tool_ids: list[str], user: UserModel, extra_params: dict
  56. ) -> dict[str, dict]:
  57. tools_dict = {}
  58. for tool_id in tool_ids:
  59. tool = Tools.get_tool_by_id(tool_id)
  60. if tool is None:
  61. if tool_id.startswith("server:"):
  62. server_idx = int(tool_id.split(":")[1])
  63. tool_server_connection = (
  64. request.app.state.config.TOOL_SERVER_CONNECTIONS[server_idx]
  65. )
  66. tool_server_data = None
  67. for server in request.app.state.TOOL_SERVERS:
  68. if server["idx"] == server_idx:
  69. tool_server_data = server
  70. break
  71. assert tool_server_data is not None
  72. specs = tool_server_data.get("specs", [])
  73. for spec in specs:
  74. function_name = spec["name"]
  75. auth_type = tool_server_connection.get("auth_type", "bearer")
  76. token = None
  77. if auth_type == "bearer":
  78. token = tool_server_connection.get("key", "")
  79. elif auth_type == "session":
  80. token = request.state.token.credentials
  81. def make_tool_function(function_name, token, tool_server_data):
  82. async def tool_function(**kwargs):
  83. print(
  84. f"Executing tool function {function_name} with params: {kwargs}"
  85. )
  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["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. description = parse_description(docstring)
  228. function_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. description = function_descriptions.get(name, None)
  234. if description:
  235. field_defs[name] = type_hint, Field(default_value, description=description)
  236. else:
  237. field_defs[name] = type_hint, default_value
  238. model = create_model(func.__name__, **field_defs)
  239. model.__doc__ = description
  240. return model
  241. def get_functions_from_tool(tool: object) -> list[Callable]:
  242. return [
  243. getattr(tool, func)
  244. for func in dir(tool)
  245. if callable(
  246. getattr(tool, func)
  247. ) # checks if the attribute is callable (a method or function).
  248. and not func.startswith(
  249. "__"
  250. ) # 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.
  251. and not inspect.isclass(
  252. getattr(tool, func)
  253. ) # ensures that the callable is not a class itself, just a method or function.
  254. ]
  255. def get_tool_specs(tool_module: object) -> list[dict]:
  256. function_models = map(
  257. convert_function_to_pydantic_model, get_functions_from_tool(tool_module)
  258. )
  259. specs = [
  260. convert_pydantic_model_to_openai_function_spec(function_model)
  261. for function_model in function_models
  262. ]
  263. return specs
  264. def resolve_schema(schema, components):
  265. """
  266. Recursively resolves a JSON schema using OpenAPI components.
  267. """
  268. if not schema:
  269. return {}
  270. if "$ref" in schema:
  271. ref_path = schema["$ref"]
  272. ref_parts = ref_path.strip("#/").split("/")
  273. resolved = components
  274. for part in ref_parts[1:]: # Skip the initial 'components'
  275. resolved = resolved.get(part, {})
  276. return resolve_schema(resolved, components)
  277. resolved_schema = copy.deepcopy(schema)
  278. # Recursively resolve inner schemas
  279. if "properties" in resolved_schema:
  280. for prop, prop_schema in resolved_schema["properties"].items():
  281. resolved_schema["properties"][prop] = resolve_schema(
  282. prop_schema, components
  283. )
  284. if "items" in resolved_schema:
  285. resolved_schema["items"] = resolve_schema(resolved_schema["items"], components)
  286. return resolved_schema
  287. def convert_openapi_to_tool_payload(openapi_spec):
  288. """
  289. Converts an OpenAPI specification into a custom tool payload structure.
  290. Args:
  291. openapi_spec (dict): The OpenAPI specification as a Python dict.
  292. Returns:
  293. list: A list of tool payloads.
  294. """
  295. tool_payload = []
  296. for path, methods in openapi_spec.get("paths", {}).items():
  297. for method, operation in methods.items():
  298. tool = {
  299. "type": "function",
  300. "name": operation.get("operationId"),
  301. "description": operation.get(
  302. "description", operation.get("summary", "No description available.")
  303. ),
  304. "parameters": {"type": "object", "properties": {}, "required": []},
  305. }
  306. # Extract path and query parameters
  307. for param in operation.get("parameters", []):
  308. param_name = param["name"]
  309. param_schema = param.get("schema", {})
  310. description = param_schema.get("description", "")
  311. if not description:
  312. description = param.get("description") or ""
  313. if param_schema.get("enum") and isinstance(
  314. param_schema.get("enum"), list
  315. ):
  316. description += (
  317. f". Possible values: {', '.join(param_schema.get('enum'))}"
  318. )
  319. tool["parameters"]["properties"][param_name] = {
  320. "type": param_schema.get("type"),
  321. "description": description,
  322. }
  323. if param.get("required"):
  324. tool["parameters"]["required"].append(param_name)
  325. # Extract and resolve requestBody if available
  326. request_body = operation.get("requestBody")
  327. if request_body:
  328. content = request_body.get("content", {})
  329. json_schema = content.get("application/json", {}).get("schema")
  330. if json_schema:
  331. resolved_schema = resolve_schema(
  332. json_schema, openapi_spec.get("components", {})
  333. )
  334. if resolved_schema.get("properties"):
  335. tool["parameters"]["properties"].update(
  336. resolved_schema["properties"]
  337. )
  338. if "required" in resolved_schema:
  339. tool["parameters"]["required"] = list(
  340. set(
  341. tool["parameters"]["required"]
  342. + resolved_schema["required"]
  343. )
  344. )
  345. elif resolved_schema.get("type") == "array":
  346. tool["parameters"] = resolved_schema # special case for array
  347. tool_payload.append(tool)
  348. return tool_payload
  349. async def get_tool_server_data(token: str, url: str) -> Dict[str, Any]:
  350. headers = {
  351. "Accept": "application/json",
  352. "Content-Type": "application/json",
  353. }
  354. if token:
  355. headers["Authorization"] = f"Bearer {token}"
  356. error = None
  357. try:
  358. timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER_DATA)
  359. async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
  360. async with session.get(
  361. url, headers=headers, ssl=AIOHTTP_CLIENT_SESSION_TOOL_SERVER_SSL
  362. ) as response:
  363. if response.status != 200:
  364. error_body = await response.json()
  365. raise Exception(error_body)
  366. # Check if URL ends with .yaml or .yml to determine format
  367. if url.lower().endswith((".yaml", ".yml")):
  368. text_content = await response.text()
  369. res = yaml.safe_load(text_content)
  370. else:
  371. res = await response.json()
  372. except Exception as err:
  373. log.exception(f"Could not fetch tool server spec from {url}")
  374. if isinstance(err, dict) and "detail" in err:
  375. error = err["detail"]
  376. else:
  377. error = str(err)
  378. raise Exception(error)
  379. data = {
  380. "openapi": res,
  381. "info": res.get("info", {}),
  382. "specs": convert_openapi_to_tool_payload(res),
  383. }
  384. print("Fetched data:", data)
  385. return data
  386. async def get_tool_servers_data(
  387. servers: List[Dict[str, Any]], session_token: Optional[str] = None
  388. ) -> List[Dict[str, Any]]:
  389. # Prepare list of enabled servers along with their original index
  390. server_entries = []
  391. for idx, server in enumerate(servers):
  392. if server.get("config", {}).get("enable"):
  393. url_path = server.get("path", "openapi.json")
  394. full_url = f"{server.get('url')}/{url_path}"
  395. auth_type = server.get("auth_type", "bearer")
  396. token = None
  397. if auth_type == "bearer":
  398. token = server.get("key", "")
  399. elif auth_type == "session":
  400. token = session_token
  401. server_entries.append((idx, server, full_url, token))
  402. # Create async tasks to fetch data
  403. tasks = [get_tool_server_data(token, url) for (_, _, url, token) in server_entries]
  404. # Execute tasks concurrently
  405. responses = await asyncio.gather(*tasks, return_exceptions=True)
  406. # Build final results with index and server metadata
  407. results = []
  408. for (idx, server, url, _), response in zip(server_entries, responses):
  409. if isinstance(response, Exception):
  410. print(f"Failed to connect to {url} OpenAPI tool server")
  411. continue
  412. results.append(
  413. {
  414. "idx": idx,
  415. "url": server.get("url"),
  416. "openapi": response.get("openapi"),
  417. "info": response.get("info"),
  418. "specs": response.get("specs"),
  419. }
  420. )
  421. return results
  422. async def execute_tool_server(
  423. token: str, url: str, name: str, params: Dict[str, Any], server_data: Dict[str, Any]
  424. ) -> Any:
  425. error = None
  426. try:
  427. openapi = server_data.get("openapi", {})
  428. paths = openapi.get("paths", {})
  429. matching_route = None
  430. for route_path, methods in paths.items():
  431. for http_method, operation in methods.items():
  432. if isinstance(operation, dict) and operation.get("operationId") == name:
  433. matching_route = (route_path, methods)
  434. break
  435. if matching_route:
  436. break
  437. if not matching_route:
  438. raise Exception(f"No matching route found for operationId: {name}")
  439. route_path, methods = matching_route
  440. method_entry = None
  441. for http_method, operation in methods.items():
  442. if operation.get("operationId") == name:
  443. method_entry = (http_method.lower(), operation)
  444. break
  445. if not method_entry:
  446. raise Exception(f"No matching method found for operationId: {name}")
  447. http_method, operation = method_entry
  448. path_params = {}
  449. query_params = {}
  450. body_params = {}
  451. for param in operation.get("parameters", []):
  452. param_name = param["name"]
  453. param_in = param["in"]
  454. if param_name in params:
  455. if param_in == "path":
  456. path_params[param_name] = params[param_name]
  457. elif param_in == "query":
  458. query_params[param_name] = params[param_name]
  459. final_url = f"{url}{route_path}"
  460. for key, value in path_params.items():
  461. final_url = final_url.replace(f"{{{key}}}", str(value))
  462. if query_params:
  463. query_string = "&".join(f"{k}={v}" for k, v in query_params.items())
  464. final_url = f"{final_url}?{query_string}"
  465. if operation.get("requestBody", {}).get("content"):
  466. if params:
  467. body_params = params
  468. else:
  469. raise Exception(
  470. f"Request body expected for operation '{name}' but none found."
  471. )
  472. headers = {"Content-Type": "application/json"}
  473. if token:
  474. headers["Authorization"] = f"Bearer {token}"
  475. async with aiohttp.ClientSession(trust_env=True) as session:
  476. request_method = getattr(session, http_method.lower())
  477. if http_method in ["post", "put", "patch"]:
  478. async with request_method(
  479. final_url,
  480. json=body_params,
  481. headers=headers,
  482. ssl=AIOHTTP_CLIENT_SESSION_TOOL_SERVER_SSL,
  483. ) as response:
  484. if response.status >= 400:
  485. text = await response.text()
  486. raise Exception(f"HTTP error {response.status}: {text}")
  487. return await response.json()
  488. else:
  489. async with request_method(
  490. final_url,
  491. headers=headers,
  492. ssl=AIOHTTP_CLIENT_SESSION_TOOL_SERVER_SSL,
  493. ) as response:
  494. if response.status >= 400:
  495. text = await response.text()
  496. raise Exception(f"HTTP error {response.status}: {text}")
  497. return await response.json()
  498. except Exception as err:
  499. error = str(err)
  500. print("API Request Error:", error)
  501. return {"error": error}