tools.py 24 KB

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