1
0

tools.py 24 KB

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