tools.py 29 KB

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