execute<T> method

Future<T> execute<T>(
  1. Future<T> action(
    1. AIProvider provider
    )
)

Executes action with automatic fallback to the next provider on failure.

Returns the result from the first successful provider. Throws the last error if all providers fail.

Implementation

Future<T> execute<T>(
  Future<T> Function(AIProvider provider) action,
) async {
  AIError? lastError;

  for (final provider in providers) {
    final breaker = circuitBreakers[provider.name];

    try {
      if (breaker != null) {
        return await breaker.execute(() => action(provider));
      }
      return await action(provider);
    } on AIError catch (e) {
      lastError = e;
      // If the error is not retryable (e.g., content filter, auth),
      // don't try the next provider
      if (!e.isRetryable) {
        rethrow;
      }
      // Otherwise, continue to the next provider
      continue;
    }
  }

  throw lastError ??
      AIUnknownError(
        provider: 'FallbackChain',
        message: 'No providers available',
      );
}