選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

api_utils.py 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import asyncio
  17. import functools
  18. import json
  19. import logging
  20. import queue
  21. import random
  22. import threading
  23. import time
  24. from base64 import b64encode
  25. from copy import deepcopy
  26. from functools import wraps
  27. from hmac import HMAC
  28. from io import BytesIO
  29. from typing import Any, Optional, Union, Callable, Coroutine, Type
  30. from urllib.parse import quote, urlencode
  31. from uuid import uuid1
  32. import trio
  33. from api.db.db_models import MCPServer
  34. from rag.utils.mcp_tool_call_conn import MCPToolCallSession, close_multiple_mcp_toolcall_sessions
  35. import requests
  36. from flask import (
  37. Response,
  38. jsonify,
  39. make_response,
  40. send_file,
  41. )
  42. from flask import (
  43. request as flask_request,
  44. )
  45. from itsdangerous import URLSafeTimedSerializer
  46. from peewee import OperationalError
  47. from werkzeug.http import HTTP_STATUS_CODES
  48. from api import settings
  49. from api.constants import REQUEST_MAX_WAIT_SEC, REQUEST_WAIT_SEC
  50. from api.db.db_models import APIToken
  51. from api.db.services.llm_service import LLMService, TenantLLMService
  52. from api.utils import CustomJSONEncoder, get_uuid, json_dumps
  53. requests.models.complexjson.dumps = functools.partial(json.dumps, cls=CustomJSONEncoder)
  54. def request(**kwargs):
  55. sess = requests.Session()
  56. stream = kwargs.pop("stream", sess.stream)
  57. timeout = kwargs.pop("timeout", None)
  58. kwargs["headers"] = {k.replace("_", "-").upper(): v for k, v in kwargs.get("headers", {}).items()}
  59. prepped = requests.Request(**kwargs).prepare()
  60. if settings.CLIENT_AUTHENTICATION and settings.HTTP_APP_KEY and settings.SECRET_KEY:
  61. timestamp = str(round(time() * 1000))
  62. nonce = str(uuid1())
  63. signature = b64encode(
  64. HMAC(
  65. settings.SECRET_KEY.encode("ascii"),
  66. b"\n".join(
  67. [
  68. timestamp.encode("ascii"),
  69. nonce.encode("ascii"),
  70. settings.HTTP_APP_KEY.encode("ascii"),
  71. prepped.path_url.encode("ascii"),
  72. prepped.body if kwargs.get("json") else b"",
  73. urlencode(sorted(kwargs["data"].items()), quote_via=quote, safe="-._~").encode("ascii") if kwargs.get("data") and isinstance(kwargs["data"], dict) else b"",
  74. ]
  75. ),
  76. "sha1",
  77. ).digest()
  78. ).decode("ascii")
  79. prepped.headers.update(
  80. {
  81. "TIMESTAMP": timestamp,
  82. "NONCE": nonce,
  83. "APP-KEY": settings.HTTP_APP_KEY,
  84. "SIGNATURE": signature,
  85. }
  86. )
  87. return sess.send(prepped, stream=stream, timeout=timeout)
  88. def get_exponential_backoff_interval(retries, full_jitter=False):
  89. """Calculate the exponential backoff wait time."""
  90. # Will be zero if factor equals 0
  91. countdown = min(REQUEST_MAX_WAIT_SEC, REQUEST_WAIT_SEC * (2**retries))
  92. # Full jitter according to
  93. # https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
  94. if full_jitter:
  95. countdown = random.randrange(countdown + 1)
  96. # Adjust according to maximum wait time and account for negative values.
  97. return max(0, countdown)
  98. def get_data_error_result(code=settings.RetCode.DATA_ERROR, message="Sorry! Data missing!"):
  99. logging.exception(Exception(message))
  100. result_dict = {"code": code, "message": message}
  101. response = {}
  102. for key, value in result_dict.items():
  103. if value is None and key != "code":
  104. continue
  105. else:
  106. response[key] = value
  107. return jsonify(response)
  108. def server_error_response(e):
  109. logging.exception(e)
  110. try:
  111. if e.code == 401:
  112. return get_json_result(code=401, message=repr(e))
  113. except BaseException:
  114. pass
  115. if len(e.args) > 1:
  116. return get_json_result(code=settings.RetCode.EXCEPTION_ERROR, message=repr(e.args[0]), data=e.args[1])
  117. if repr(e).find("index_not_found_exception") >= 0:
  118. return get_json_result(code=settings.RetCode.EXCEPTION_ERROR, message="No chunk found, please upload file and parse it.")
  119. return get_json_result(code=settings.RetCode.EXCEPTION_ERROR, message=repr(e))
  120. def error_response(response_code, message=None):
  121. if message is None:
  122. message = HTTP_STATUS_CODES.get(response_code, "Unknown Error")
  123. return Response(
  124. json.dumps(
  125. {
  126. "message": message,
  127. "code": response_code,
  128. }
  129. ),
  130. status=response_code,
  131. mimetype="application/json",
  132. )
  133. def validate_request(*args, **kwargs):
  134. def wrapper(func):
  135. @wraps(func)
  136. def decorated_function(*_args, **_kwargs):
  137. input_arguments = flask_request.json or flask_request.form.to_dict()
  138. no_arguments = []
  139. error_arguments = []
  140. for arg in args:
  141. if arg not in input_arguments:
  142. no_arguments.append(arg)
  143. for k, v in kwargs.items():
  144. config_value = input_arguments.get(k, None)
  145. if config_value is None:
  146. no_arguments.append(k)
  147. elif isinstance(v, (tuple, list)):
  148. if config_value not in v:
  149. error_arguments.append((k, set(v)))
  150. elif config_value != v:
  151. error_arguments.append((k, v))
  152. if no_arguments or error_arguments:
  153. error_string = ""
  154. if no_arguments:
  155. error_string += "required argument are missing: {}; ".format(",".join(no_arguments))
  156. if error_arguments:
  157. error_string += "required argument values: {}".format(",".join(["{}={}".format(a[0], a[1]) for a in error_arguments]))
  158. return get_json_result(code=settings.RetCode.ARGUMENT_ERROR, message=error_string)
  159. return func(*_args, **_kwargs)
  160. return decorated_function
  161. return wrapper
  162. def not_allowed_parameters(*params):
  163. def decorator(f):
  164. def wrapper(*args, **kwargs):
  165. input_arguments = flask_request.json or flask_request.form.to_dict()
  166. for param in params:
  167. if param in input_arguments:
  168. return get_json_result(code=settings.RetCode.ARGUMENT_ERROR, message=f"Parameter {param} isn't allowed")
  169. return f(*args, **kwargs)
  170. return wrapper
  171. return decorator
  172. def is_localhost(ip):
  173. return ip in {"127.0.0.1", "::1", "[::1]", "localhost"}
  174. def send_file_in_mem(data, filename):
  175. if not isinstance(data, (str, bytes)):
  176. data = json_dumps(data)
  177. if isinstance(data, str):
  178. data = data.encode("utf-8")
  179. f = BytesIO()
  180. f.write(data)
  181. f.seek(0)
  182. return send_file(f, as_attachment=True, attachment_filename=filename)
  183. def get_json_result(code=settings.RetCode.SUCCESS, message="success", data=None):
  184. response = {"code": code, "message": message, "data": data}
  185. return jsonify(response)
  186. def apikey_required(func):
  187. @wraps(func)
  188. def decorated_function(*args, **kwargs):
  189. token = flask_request.headers.get("Authorization").split()[1]
  190. objs = APIToken.query(token=token)
  191. if not objs:
  192. return build_error_result(message="API-KEY is invalid!", code=settings.RetCode.FORBIDDEN)
  193. kwargs["tenant_id"] = objs[0].tenant_id
  194. return func(*args, **kwargs)
  195. return decorated_function
  196. def build_error_result(code=settings.RetCode.FORBIDDEN, message="success"):
  197. response = {"code": code, "message": message}
  198. response = jsonify(response)
  199. response.status_code = code
  200. return response
  201. def construct_response(code=settings.RetCode.SUCCESS, message="success", data=None, auth=None):
  202. result_dict = {"code": code, "message": message, "data": data}
  203. response_dict = {}
  204. for key, value in result_dict.items():
  205. if value is None and key != "code":
  206. continue
  207. else:
  208. response_dict[key] = value
  209. response = make_response(jsonify(response_dict))
  210. if auth:
  211. response.headers["Authorization"] = auth
  212. response.headers["Access-Control-Allow-Origin"] = "*"
  213. response.headers["Access-Control-Allow-Method"] = "*"
  214. response.headers["Access-Control-Allow-Headers"] = "*"
  215. response.headers["Access-Control-Allow-Headers"] = "*"
  216. response.headers["Access-Control-Expose-Headers"] = "Authorization"
  217. return response
  218. def construct_result(code=settings.RetCode.DATA_ERROR, message="data is missing"):
  219. result_dict = {"code": code, "message": message}
  220. response = {}
  221. for key, value in result_dict.items():
  222. if value is None and key != "code":
  223. continue
  224. else:
  225. response[key] = value
  226. return jsonify(response)
  227. def construct_json_result(code=settings.RetCode.SUCCESS, message="success", data=None):
  228. if data is None:
  229. return jsonify({"code": code, "message": message})
  230. else:
  231. return jsonify({"code": code, "message": message, "data": data})
  232. def construct_error_response(e):
  233. logging.exception(e)
  234. try:
  235. if e.code == 401:
  236. return construct_json_result(code=settings.RetCode.UNAUTHORIZED, message=repr(e))
  237. except BaseException:
  238. pass
  239. if len(e.args) > 1:
  240. return construct_json_result(code=settings.RetCode.EXCEPTION_ERROR, message=repr(e.args[0]), data=e.args[1])
  241. return construct_json_result(code=settings.RetCode.EXCEPTION_ERROR, message=repr(e))
  242. def token_required(func):
  243. @wraps(func)
  244. def decorated_function(*args, **kwargs):
  245. authorization_str = flask_request.headers.get("Authorization")
  246. if not authorization_str:
  247. return get_json_result(data=False, message="`Authorization` can't be empty")
  248. authorization_list = authorization_str.split()
  249. if len(authorization_list) < 2:
  250. return get_json_result(data=False, message="Please check your authorization format.")
  251. token = authorization_list[1]
  252. objs = APIToken.query(token=token)
  253. if not objs:
  254. return get_json_result(data=False, message="Authentication error: API key is invalid!", code=settings.RetCode.AUTHENTICATION_ERROR)
  255. kwargs["tenant_id"] = objs[0].tenant_id
  256. return func(*args, **kwargs)
  257. return decorated_function
  258. def get_result(code=settings.RetCode.SUCCESS, message="", data=None):
  259. if code == 0:
  260. if data is not None:
  261. response = {"code": code, "data": data}
  262. else:
  263. response = {"code": code}
  264. else:
  265. response = {"code": code, "message": message}
  266. return jsonify(response)
  267. def get_error_data_result(
  268. message="Sorry! Data missing!",
  269. code=settings.RetCode.DATA_ERROR,
  270. ):
  271. result_dict = {"code": code, "message": message}
  272. response = {}
  273. for key, value in result_dict.items():
  274. if value is None and key != "code":
  275. continue
  276. else:
  277. response[key] = value
  278. return jsonify(response)
  279. def get_error_argument_result(message="Invalid arguments"):
  280. return get_result(code=settings.RetCode.ARGUMENT_ERROR, message=message)
  281. def get_error_permission_result(message="Permission error"):
  282. return get_result(code=settings.RetCode.PERMISSION_ERROR, message=message)
  283. def get_error_operating_result(message="Operating error"):
  284. return get_result(code=settings.RetCode.OPERATING_ERROR, message=message)
  285. def generate_confirmation_token(tenant_id):
  286. serializer = URLSafeTimedSerializer(tenant_id)
  287. return "ragflow-" + serializer.dumps(get_uuid(), salt=tenant_id)[2:34]
  288. def get_parser_config(chunk_method, parser_config):
  289. if parser_config:
  290. return parser_config
  291. if not chunk_method:
  292. chunk_method = "naive"
  293. key_mapping = {
  294. "naive": {"chunk_token_num": 512, "delimiter": r"\n", "html4excel": False, "layout_recognize": "DeepDOC", "raptor": {"use_raptor": False}},
  295. "qa": {"raptor": {"use_raptor": False}},
  296. "tag": None,
  297. "resume": None,
  298. "manual": {"raptor": {"use_raptor": False}},
  299. "table": None,
  300. "paper": {"raptor": {"use_raptor": False}},
  301. "book": {"raptor": {"use_raptor": False}},
  302. "laws": {"raptor": {"use_raptor": False}},
  303. "presentation": {"raptor": {"use_raptor": False}},
  304. "one": None,
  305. "knowledge_graph": {"chunk_token_num": 8192, "delimiter": r"\n", "entity_types": ["organization", "person", "location", "event", "time"]},
  306. "email": None,
  307. "picture": None,
  308. }
  309. parser_config = key_mapping[chunk_method]
  310. return parser_config
  311. def get_data_openai(
  312. id=None,
  313. created=None,
  314. model=None,
  315. prompt_tokens=0,
  316. completion_tokens=0,
  317. content=None,
  318. finish_reason=None,
  319. object="chat.completion",
  320. param=None,
  321. ):
  322. total_tokens = prompt_tokens + completion_tokens
  323. return {
  324. "id": f"{id}",
  325. "object": object,
  326. "created": int(time.time()) if created else None,
  327. "model": model,
  328. "param": param,
  329. "usage": {
  330. "prompt_tokens": prompt_tokens,
  331. "completion_tokens": completion_tokens,
  332. "total_tokens": total_tokens,
  333. "completion_tokens_details": {"reasoning_tokens": 0, "accepted_prediction_tokens": 0, "rejected_prediction_tokens": 0},
  334. },
  335. "choices": [{"message": {"role": "assistant", "content": content}, "logprobs": None, "finish_reason": finish_reason, "index": 0}],
  336. }
  337. def check_duplicate_ids(ids, id_type="item"):
  338. """
  339. Check for duplicate IDs in a list and return unique IDs and error messages.
  340. Args:
  341. ids (list): List of IDs to check for duplicates
  342. id_type (str): Type of ID for error messages (e.g., 'document', 'dataset', 'chunk')
  343. Returns:
  344. tuple: (unique_ids, error_messages)
  345. - unique_ids (list): List of unique IDs
  346. - error_messages (list): List of error messages for duplicate IDs
  347. """
  348. id_count = {}
  349. duplicate_messages = []
  350. # Count occurrences of each ID
  351. for id_value in ids:
  352. id_count[id_value] = id_count.get(id_value, 0) + 1
  353. # Check for duplicates
  354. for id_value, count in id_count.items():
  355. if count > 1:
  356. duplicate_messages.append(f"Duplicate {id_type} ids: {id_value}")
  357. # Return unique IDs and error messages
  358. return list(set(ids)), duplicate_messages
  359. def verify_embedding_availability(embd_id: str, tenant_id: str) -> tuple[bool, Response | None]:
  360. """
  361. Verifies availability of an embedding model for a specific tenant.
  362. Performs comprehensive verification through:
  363. 1. Identifier Parsing: Decomposes embd_id into name and factory components
  364. 2. System Verification: Checks model registration in LLMService
  365. 3. Tenant Authorization: Validates tenant-specific model assignments
  366. 4. Built-in Model Check: Confirms inclusion in predefined system models
  367. Args:
  368. embd_id (str): Unique identifier for the embedding model in format "model_name@factory"
  369. tenant_id (str): Tenant identifier for access control
  370. Returns:
  371. tuple[bool, Response | None]:
  372. - First element (bool):
  373. - True: Model is available and authorized
  374. - False: Validation failed
  375. - Second element contains:
  376. - None on success
  377. - Error detail dict on failure
  378. Raises:
  379. ValueError: When model identifier format is invalid
  380. OperationalError: When database connection fails (auto-handled)
  381. Examples:
  382. >>> verify_embedding_availability("text-embedding@openai", "tenant_123")
  383. (True, None)
  384. >>> verify_embedding_availability("invalid_model", "tenant_123")
  385. (False, {'code': 101, 'message': "Unsupported model: <invalid_model>"})
  386. """
  387. try:
  388. llm_name, llm_factory = TenantLLMService.split_model_name_and_factory(embd_id)
  389. in_llm_service = bool(LLMService.query(llm_name=llm_name, fid=llm_factory, model_type="embedding"))
  390. tenant_llms = TenantLLMService.get_my_llms(tenant_id=tenant_id)
  391. is_tenant_model = any(llm["llm_name"] == llm_name and llm["llm_factory"] == llm_factory and llm["model_type"] == "embedding" for llm in tenant_llms)
  392. is_builtin_model = embd_id in settings.BUILTIN_EMBEDDING_MODELS
  393. if not (is_builtin_model or is_tenant_model or in_llm_service):
  394. return False, get_error_argument_result(f"Unsupported model: <{embd_id}>")
  395. if not (is_builtin_model or is_tenant_model):
  396. return False, get_error_argument_result(f"Unauthorized model: <{embd_id}>")
  397. except OperationalError as e:
  398. logging.exception(e)
  399. return False, get_error_data_result(message="Database operation failed")
  400. return True, None
  401. def deep_merge(default: dict, custom: dict) -> dict:
  402. """
  403. Recursively merges two dictionaries with priority given to `custom` values.
  404. Creates a deep copy of the `default` dictionary and iteratively merges nested
  405. dictionaries using a stack-based approach. Non-dict values in `custom` will
  406. completely override corresponding entries in `default`.
  407. Args:
  408. default (dict): Base dictionary containing default values.
  409. custom (dict): Dictionary containing overriding values.
  410. Returns:
  411. dict: New merged dictionary combining values from both inputs.
  412. Example:
  413. >>> from copy import deepcopy
  414. >>> default = {"a": 1, "nested": {"x": 10, "y": 20}}
  415. >>> custom = {"b": 2, "nested": {"y": 99, "z": 30}}
  416. >>> deep_merge(default, custom)
  417. {'a': 1, 'b': 2, 'nested': {'x': 10, 'y': 99, 'z': 30}}
  418. >>> deep_merge({"config": {"mode": "auto"}}, {"config": "manual"})
  419. {'config': 'manual'}
  420. Notes:
  421. 1. Merge priority is always given to `custom` values at all nesting levels
  422. 2. Non-dict values (e.g. list, str) in `custom` will replace entire values
  423. in `default`, even if the original value was a dictionary
  424. 3. Time complexity: O(N) where N is total key-value pairs in `custom`
  425. 4. Recommended for configuration merging and nested data updates
  426. """
  427. merged = deepcopy(default)
  428. stack = [(merged, custom)]
  429. while stack:
  430. base_dict, override_dict = stack.pop()
  431. for key, val in override_dict.items():
  432. if key in base_dict and isinstance(val, dict) and isinstance(base_dict[key], dict):
  433. stack.append((base_dict[key], val))
  434. else:
  435. base_dict[key] = val
  436. return merged
  437. def remap_dictionary_keys(source_data: dict, key_aliases: dict = None) -> dict:
  438. """
  439. Transform dictionary keys using a configurable mapping schema.
  440. Args:
  441. source_data: Original dictionary to process
  442. key_aliases: Custom key transformation rules (Optional)
  443. When provided, overrides default key mapping
  444. Format: {<original_key>: <new_key>, ...}
  445. Returns:
  446. dict: New dictionary with transformed keys preserving original values
  447. Example:
  448. >>> input_data = {"old_key": "value", "another_field": 42}
  449. >>> remap_dictionary_keys(input_data, {"old_key": "new_key"})
  450. {'new_key': 'value', 'another_field': 42}
  451. """
  452. DEFAULT_KEY_MAP = {
  453. "chunk_num": "chunk_count",
  454. "doc_num": "document_count",
  455. "parser_id": "chunk_method",
  456. "embd_id": "embedding_model",
  457. }
  458. transformed_data = {}
  459. mapping = key_aliases or DEFAULT_KEY_MAP
  460. for original_key, value in source_data.items():
  461. mapped_key = mapping.get(original_key, original_key)
  462. transformed_data[mapped_key] = value
  463. return transformed_data
  464. def get_mcp_tools(mcp_servers: list[MCPServer], timeout: float | int = 10) -> tuple[dict, str]:
  465. results = {}
  466. tool_call_sessions = []
  467. try:
  468. for mcp_server in mcp_servers:
  469. server_key = mcp_server.id
  470. cached_tools = mcp_server.variables.get("tools", {})
  471. tool_call_session = MCPToolCallSession(mcp_server, mcp_server.variables)
  472. tool_call_sessions.append(tool_call_session)
  473. try:
  474. tools = tool_call_session.get_tools(timeout)
  475. except Exception:
  476. tools = []
  477. results[server_key] = []
  478. for tool in tools:
  479. tool_dict = tool.model_dump()
  480. cached_tool = cached_tools.get(tool_dict["name"], {})
  481. tool_dict["enabled"] = cached_tool.get("enabled", True)
  482. results[server_key].append(tool_dict)
  483. # PERF: blocking call to close sessions — consider moving to background thread or task queue
  484. close_multiple_mcp_toolcall_sessions(tool_call_sessions)
  485. return results, ""
  486. except Exception as e:
  487. return {}, str(e)
  488. TimeoutException = Union[Type[BaseException], BaseException]
  489. OnTimeoutCallback = Union[Callable[..., Any], Coroutine[Any, Any, Any]]
  490. def timeout(
  491. seconds: float |int = None,
  492. attempts: int = 2,
  493. *,
  494. exception: Optional[TimeoutException] = None,
  495. on_timeout: Optional[OnTimeoutCallback] = None
  496. ):
  497. def decorator(func):
  498. @wraps(func)
  499. def wrapper(*args, **kwargs):
  500. result_queue = queue.Queue(maxsize=1)
  501. def target():
  502. try:
  503. result = func(*args, **kwargs)
  504. result_queue.put(result)
  505. except Exception as e:
  506. result_queue.put(e)
  507. thread = threading.Thread(target=target)
  508. thread.daemon = True
  509. thread.start()
  510. for a in range(attempts):
  511. try:
  512. result = result_queue.get(timeout=seconds)
  513. if isinstance(result, Exception):
  514. raise result
  515. return result
  516. except queue.Empty:
  517. pass
  518. raise TimeoutError(f"Function '{func.__name__}' timed out after {seconds} seconds and {attempts} attempts.")
  519. @wraps(func)
  520. async def async_wrapper(*args, **kwargs) -> Any:
  521. if seconds is None:
  522. return await func(*args, **kwargs)
  523. for a in range(attempts):
  524. try:
  525. with trio.fail_after(seconds):
  526. return await func(*args, **kwargs)
  527. except trio.TooSlowError:
  528. if a < attempts -1:
  529. continue
  530. if on_timeout is not None:
  531. if callable(on_timeout):
  532. result = on_timeout()
  533. if isinstance(result, Coroutine):
  534. return await result
  535. return result
  536. return on_timeout
  537. if exception is None:
  538. raise TimeoutError(f"Operation timed out after {seconds} seconds and {attempts} attempts.")
  539. if isinstance(exception, BaseException):
  540. raise exception
  541. if isinstance(exception, type) and issubclass(exception, BaseException):
  542. raise exception(f"Operation timed out after {seconds} seconds and {attempts} attempts.")
  543. raise RuntimeError("Invalid exception type provided")
  544. if asyncio.iscoroutinefunction(func):
  545. return async_wrapper
  546. return wrapper
  547. return decorator