tools.py 28 KB

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