tools.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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. 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. "type": "function",
  303. "name": operation.get("operationId"),
  304. "description": operation.get(
  305. "description",
  306. operation.get("summary", "No description available."),
  307. ),
  308. "parameters": {"type": "object", "properties": {}, "required": []},
  309. }
  310. # Extract path and query parameters
  311. for param in operation.get("parameters", []):
  312. param_name = param["name"]
  313. param_schema = param.get("schema", {})
  314. description = param_schema.get("description", "")
  315. if not description:
  316. description = param.get("description") or ""
  317. if param_schema.get("enum") and isinstance(
  318. param_schema.get("enum"), list
  319. ):
  320. description += (
  321. f". Possible values: {', '.join(param_schema.get('enum'))}"
  322. )
  323. tool["parameters"]["properties"][param_name] = {
  324. "type": param_schema.get("type"),
  325. "description": description,
  326. }
  327. if param.get("required"):
  328. tool["parameters"]["required"].append(param_name)
  329. # Extract and resolve requestBody if available
  330. request_body = operation.get("requestBody")
  331. if request_body:
  332. content = request_body.get("content", {})
  333. json_schema = content.get("application/json", {}).get("schema")
  334. if json_schema:
  335. resolved_schema = resolve_schema(
  336. json_schema, openapi_spec.get("components", {})
  337. )
  338. if resolved_schema.get("properties"):
  339. tool["parameters"]["properties"].update(
  340. resolved_schema["properties"]
  341. )
  342. if "required" in resolved_schema:
  343. tool["parameters"]["required"] = list(
  344. set(
  345. tool["parameters"]["required"]
  346. + resolved_schema["required"]
  347. )
  348. )
  349. elif resolved_schema.get("type") == "array":
  350. tool["parameters"] = (
  351. resolved_schema # special case for array
  352. )
  353. tool_payload.append(tool)
  354. return tool_payload
  355. async def get_tool_server_data(token: str, url: str) -> Dict[str, Any]:
  356. headers = {
  357. "Accept": "application/json",
  358. "Content-Type": "application/json",
  359. }
  360. if token:
  361. headers["Authorization"] = f"Bearer {token}"
  362. error = None
  363. try:
  364. timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER_DATA)
  365. async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
  366. async with session.get(
  367. url, headers=headers, ssl=AIOHTTP_CLIENT_SESSION_TOOL_SERVER_SSL
  368. ) as response:
  369. if response.status != 200:
  370. error_body = await response.json()
  371. raise Exception(error_body)
  372. # Check if URL ends with .yaml or .yml to determine format
  373. if url.lower().endswith((".yaml", ".yml")):
  374. text_content = await response.text()
  375. res = yaml.safe_load(text_content)
  376. else:
  377. res = await response.json()
  378. except Exception as err:
  379. log.exception(f"Could not fetch tool server spec from {url}")
  380. if isinstance(err, dict) and "detail" in err:
  381. error = err["detail"]
  382. else:
  383. error = str(err)
  384. raise Exception(error)
  385. data = {
  386. "openapi": res,
  387. "info": res.get("info", {}),
  388. "specs": convert_openapi_to_tool_payload(res),
  389. }
  390. print("Fetched data:", data)
  391. return data
  392. async def get_tool_servers_data(
  393. servers: List[Dict[str, Any]], session_token: Optional[str] = None
  394. ) -> List[Dict[str, Any]]:
  395. # Prepare list of enabled servers along with their original index
  396. server_entries = []
  397. for idx, server in enumerate(servers):
  398. if server.get("config", {}).get("enable"):
  399. url_path = server.get("path", "openapi.json")
  400. full_url = f"{server.get('url')}/{url_path}"
  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, token))
  408. # Create async tasks to fetch data
  409. tasks = [get_tool_server_data(token, url) for (_, _, url, token) in server_entries]
  410. # Execute tasks concurrently
  411. responses = await asyncio.gather(*tasks, return_exceptions=True)
  412. # Build final results with index and server metadata
  413. results = []
  414. for (idx, server, url, _), response in zip(server_entries, responses):
  415. if isinstance(response, Exception):
  416. print(f"Failed to connect to {url} OpenAPI tool server")
  417. continue
  418. results.append(
  419. {
  420. "idx": idx,
  421. "url": server.get("url"),
  422. "openapi": response.get("openapi"),
  423. "info": response.get("info"),
  424. "specs": response.get("specs"),
  425. }
  426. )
  427. return results
  428. async def execute_tool_server(
  429. token: str, url: str, name: str, params: Dict[str, Any], server_data: Dict[str, Any]
  430. ) -> Any:
  431. error = None
  432. try:
  433. openapi = server_data.get("openapi", {})
  434. paths = openapi.get("paths", {})
  435. matching_route = None
  436. for route_path, methods in paths.items():
  437. for http_method, operation in methods.items():
  438. if isinstance(operation, dict) and operation.get("operationId") == name:
  439. matching_route = (route_path, methods)
  440. break
  441. if matching_route:
  442. break
  443. if not matching_route:
  444. raise Exception(f"No matching route found for operationId: {name}")
  445. route_path, methods = matching_route
  446. method_entry = None
  447. for http_method, operation in methods.items():
  448. if operation.get("operationId") == name:
  449. method_entry = (http_method.lower(), operation)
  450. break
  451. if not method_entry:
  452. raise Exception(f"No matching method found for operationId: {name}")
  453. http_method, operation = method_entry
  454. path_params = {}
  455. query_params = {}
  456. body_params = {}
  457. for param in operation.get("parameters", []):
  458. param_name = param["name"]
  459. param_in = param["in"]
  460. if param_name in params:
  461. if param_in == "path":
  462. path_params[param_name] = params[param_name]
  463. elif param_in == "query":
  464. query_params[param_name] = params[param_name]
  465. final_url = f"{url}{route_path}"
  466. for key, value in path_params.items():
  467. final_url = final_url.replace(f"{{{key}}}", str(value))
  468. if query_params:
  469. query_string = "&".join(f"{k}={v}" for k, v in query_params.items())
  470. final_url = f"{final_url}?{query_string}"
  471. if operation.get("requestBody", {}).get("content"):
  472. if params:
  473. body_params = params
  474. else:
  475. raise Exception(
  476. f"Request body expected for operation '{name}' but none found."
  477. )
  478. headers = {"Content-Type": "application/json"}
  479. if token:
  480. headers["Authorization"] = f"Bearer {token}"
  481. async with aiohttp.ClientSession(trust_env=True) as session:
  482. request_method = getattr(session, http_method.lower())
  483. if http_method in ["post", "put", "patch"]:
  484. async with request_method(
  485. final_url,
  486. json=body_params,
  487. headers=headers,
  488. ssl=AIOHTTP_CLIENT_SESSION_TOOL_SERVER_SSL,
  489. ) as response:
  490. if response.status >= 400:
  491. text = await response.text()
  492. raise Exception(f"HTTP error {response.status}: {text}")
  493. return await response.json()
  494. else:
  495. async with request_method(
  496. final_url,
  497. headers=headers,
  498. ssl=AIOHTTP_CLIENT_SESSION_TOOL_SERVER_SSL,
  499. ) as response:
  500. if response.status >= 400:
  501. text = await response.text()
  502. raise Exception(f"HTTP error {response.status}: {text}")
  503. return await response.json()
  504. except Exception as err:
  505. error = str(err)
  506. print("API Request Error:", error)
  507. return {"error": error}