1
0

tools.py 25 KB

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