tools.py 23 KB

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