tools.py 26 KB

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