1
0

tools.py 28 KB

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