tools.py 25 KB

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