tools.py 26 KB

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