tools.py 26 KB

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