10. Manejo de Errores en Aplicaciones de IA con .NET

Aprende a manejar errores en servicios de IA con .NET: fallos de red, timeouts, rate limiting 429, validación de respuestas y patrones de retry con Polly.

Introducción

Las aplicaciones de IA enfrentan errores únicos: rate limits, timeouts, respuestas inesperadas del modelo, y fallos de red. Este tutorial cubre estrategias robustas de manejo de errores para aplicaciones de IA en producción.

Tipos de Errores Comunes

1. Errores de Red

try
{
    var response = await aiService.GenerateAsync(prompt);
}
catch (HttpRequestException ex)
{
    _logger.LogError(ex, "Error de conexión al servicio de IA");
    // Retry o fallback
}
catch (TaskCanceledException ex)
{
    _logger.LogError(ex, "Timeout al llamar al servicio de IA");
    // Timeout handling
}

2. Rate Limiting (429)

catch (RequestFailedException ex) when (ex.Status == 429)
{
    var retryAfter = ex.GetRawResponse()?.Headers
        .TryGetValue("Retry-After", out var value) == true
        ? int.Parse(value) : 60;

    _logger.LogWarning("Rate limit alcanzado. Reintentar en {Seconds}s", retryAfter);
    await Task.Delay(TimeSpan.FromSeconds(retryAfter));
    // Retry
}

3. Respuestas Inesperadas del Modelo

var response = await aiService.GenerateAsync(prompt);

if (string.IsNullOrWhiteSpace(response))
{
    throw new AIServiceException("Modelo retornó respuesta vacía");
}

if (!IsValidFormat(response))
{
    _logger.LogWarning("Respuesta en formato inesperado: {Response}", response);
    // Intentar parsear o usar respuesta por defecto
}

Patrones de Retry

Retry Simple

public async Task<string> GenerateWithRetryAsync(
    string prompt,
    int maxRetries = 3)
{
    for (int attempt = 0; attempt < maxRetries; attempt++)
    {
        try
        {
            return await _aiService.GenerateAsync(prompt);
        }
        catch (Exception ex) when (attempt < maxRetries - 1)
        {
            _logger.LogWarning(ex, "Intento {Attempt} falló, reintentando...", attempt + 1);
            await Task.Delay(TimeSpan.FromSeconds(Math.Pow(2, attempt)));
        }
    }

    throw new AIServiceException(
quot;Fallo después de {maxRetries} intentos"); } 

Exponential Backoff con Polly

using Polly;

var retryPolicy = Policy
    .Handle<HttpRequestException>()
    .Or<RequestFailedException>(ex => ex.Status == 429 || ex.Status == 503)
    .WaitAndRetryAsync(
        retryCount: 3,
        sleepDurationProvider: attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt)),
        onRetry: (exception, timeSpan, retryCount, context) =>
        {
            _logger.LogWarning(
                "Retry {RetryCount} después de {Delay}s: {Error}",
                retryCount, timeSpan.TotalSeconds, exception.Message);
        });

var response = await retryPolicy.ExecuteAsync(
    async () => await _aiService.GenerateAsync(prompt));

Mejores Prácticas

  1. Siempre loggear errores con contexto
  2. Implementar circuit breakers para servicios externos
  3. Tener fallbacks para funcionalidad crítica
  4. Validar respuestas antes de usarlas

Palabras clave: error handling, retry patterns, Polly, resilience, exception handling, AI services