executeWithRetry method

Future<T?> executeWithRetry(
  1. Future<T> fn(), {
  2. int maxAttempts = 3,
  3. Duration delayMs = const Duration(milliseconds: 1000),
  4. double estimatedCost = 0.0,
})

Execute with retry logic

Implementation

Future<T?> executeWithRetry(
  Future<T> Function() fn, {
  int maxAttempts = 3,
  Duration delayMs = const Duration(milliseconds: 1000),
  double estimatedCost = 0.0,
}) async {
  Exception? lastError;

  for (int attempt = 0; attempt < maxAttempts; attempt++) {
    try {
      return await execute(fn, estimatedCost: estimatedCost);
    } catch (e) {
      lastError = e is Exception ? e : Exception(e.toString());

      if (attempt < maxAttempts - 1) {
        await Future.delayed(
          Duration(milliseconds: delayMs.inMilliseconds * (attempt + 1)),
        );
      }
    }
  }

  if (lastError != null) {
    _setState(AIState.error(lastError));
  }

  return null;
}