0Pricing
LLM Apps in Production (RAG + Vector DB + Caching) · Урок

Обработка ошибок и шаблоны отказоустойчивости

Спроектируйте надёжную обработку ошибок, механизмы повторных попыток и автоматические размыкатели цепи, чтобы повысить отказоустойчивость приложений LLM.

«Обработка ошибок и шаблоны отказоустойчивости» — бесплатный урок LLM Apps in Production (RAG + Vector DB + Caching) на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения LLM Apps in Production (RAG + Vector DB + Caching), и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс LLM Apps in Production (RAG + Vector DB + Caching) содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Build Robust LLM Apps

LLM applications, especially those interacting with external APIs, need to be tough!

Resilience is about designing systems that can recover from failures gracefully, without crashing or providing a bad user experience.

In this lesson, we'll learn patterns to make your LLM apps more fault-tolerant.

Typical Failures

What kind of errors can an LLM application face?

  • API Rate Limits: Too many requests at once.
  • Network Issues: Temporary connection drops.
  • LLM Service Unavailability: The LLM provider is down.
  • Bad LLM Responses: Model returns invalid JSON or hallucinates.
  • Dependency Failures: Vector DB or other services fail.

Standard Try-Catch

The first line of defense is standard error handling using try-catch blocks. This prevents your entire application from crashing when an expected error occurs.

It allows you to log the error, inform the user, or attempt a fallback.

public class Main {
  public static void main(String[] args) {
    try {
      // Simulate an LLM API call that might fail
      callLlmApi();
      System.out.println("API call successful.");
    } catch (Exception e) {
      System.out.println("Error: " + e.getMessage());
      // Log the error, notify user, etc.
    }
  }

  public static void callLlmApi() throws Exception {
    // In a real app, this would make an actual API call
    if (Math.random() < 0.5) { // 50% chance of failure
      throw new RuntimeException("LLM service unavailable.");
    }
  }
}

Why Just Catching Isn't Enough

Some errors are transient, meaning they're temporary and might resolve if you just try again. Think of a brief network glitch or a momentary rate limit.

A simple try-catch just fails immediately. For transient errors, a retry mechanism can significantly improve reliability without user intervention.

Simple Retry Logic

We can implement a basic retry loop. If an error occurs, we wait a bit and try again, up to a maximum number of attempts.

public class Main {
  public static void main(String[] args) {
    int maxRetries = 3;
    int currentRetry = 0;
    boolean success = false;

    while (currentRetry < maxRetries && !success) {
      try {
        System.out.println("Attempt " + (currentRetry + 1));
        callLlmApi();
        System.out.println("API call successful.");
        success = true;
      } catch (Exception e) {
        System.out.println("Error: " + e.getMessage());
        currentRetry++;
        if (currentRetry < maxRetries) {
          System.out.println("Retrying in 1 second...");
          try { Thread.sleep(1000); } catch (InterruptedException ie) {}
        }
      }
    }
    if (!success) {
      System.out.println("All retries failed.");
    }
  }

  public static void callLlmApi() throws Exception {
    // Simulate an LLM API call with 70% chance of failure
    if (Math.random() < 0.7) {
      throw new RuntimeException("Transient network error.");
    }
  }
}

Smart Retries: Exponential Backoff

Constant retry delays can overwhelm a struggling service. Exponential backoff is a strategy where the delay between retries increases exponentially.

This gives the remote service more time to recover and prevents your app from hammering it with requests.

  • Initial delay: 1s
  • Second delay: 2s
  • Third delay: 4s
  • And so on...

Circuit Breaker Pattern

What if a service is truly down, not just experiencing transient errors? Retrying repeatedly only wastes resources and delays failure detection.

The Circuit Breaker pattern prevents an application from repeatedly trying to invoke a service that is likely to fail, saving resources and allowing the service time to recover.

Circuit Breaker States

A circuit breaker has three main states:

  • Closed: Operations proceed normally. If errors exceed a threshold, it trips to Open.
  • Open: All requests fail immediately without trying the service. After a timeout, it transitions to Half-Open.
  • Half-Open: A limited number of requests are allowed to pass through to test if the service has recovered. If successful, it goes back to Closed; otherwise, back to Open.

Preventing Hung Requests with Timeouts

LLM API calls can sometimes hang indefinitely, waiting for a response that never comes. This can exhaust resources and degrade user experience.

Always configure timeouts for your API calls. This sets a maximum duration your application will wait for a response before giving up and throwing an error.

import java.util.concurrent.TimeUnit;

public class Main {
  public static void main(String[] args) {
    long startTime = System.nanoTime();
    long timeoutMillis = 2000; // 2 seconds timeout

    try {
      System.out.println("Calling LLM API with a timeout...");
      callLlmApiWithTimeout(timeoutMillis);
      System.out.println("API call completed successfully.");
    } catch (Exception e) {
      System.out.println("API call failed: " + e.getMessage());
    }

    long endTime = System.nanoTime();
    long duration = TimeUnit.NANOSECONDS.toMillis(endTime - startTime);
    System.out.println("Total duration: " + duration + "ms");
  }

  public static void callLlmApiWithTimeout(long timeoutMillis) throws Exception {
    // Simulate a long-running/hung API call
    long processingTime = 2500; // 2.5 seconds
    if (processingTime > timeoutMillis) {
      throw new RuntimeException("Operation timed out after " + timeoutMillis + "ms");
    }
    try {
      Thread.sleep(processingTime);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      throw new RuntimeException("API call interrupted.", e);
    }
  }
}

Resilience Check

When should you use a Circuit Breaker pattern instead of just a Retry mechanism?

Recap: Building Resilient LLM Apps

We've covered key patterns for making your LLM applications fault-tolerant:

  • Basic Error Handling: Using try-catch for immediate failure management.
  • Retry Mechanisms: For handling transient errors, often with exponential backoff.
  • Circuit Breakers: To prevent overwhelming consistently failing services.
  • Timeouts: Essential for preventing hung API calls and resource exhaustion.

These patterns are crucial for robust production LLM systems!

Часто задаваемые вопросы

Урок «Обработка ошибок и шаблоны отказоустойчивости» бесплатный?

Да — полный текст урока «Обработка ошибок и шаблоны отказоустойчивости» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс LLM Apps in Production (RAG + Vector DB + Caching), подпишись на CoddyKit PRO. Курс LLM Apps in Production (RAG + Vector DB + Caching) содержит 4 уроков всего.

Чему я научусь в уроке «Обработка ошибок и шаблоны отказоустойчивости»?

Спроектируйте надёжную обработку ошибок, механизмы повторных попыток и автоматические размыкатели цепи, чтобы повысить отказоустойчивость приложений LLM. Ты практикуешь LLM Apps in Production (RAG + Vector DB + Caching) с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать LLM Apps in Production (RAG + Vector DB + Caching)?

Предыдущий опыт не требуется. LLM Apps in Production (RAG + Vector DB + Caching) на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.

Сколько времени занимает урок «Обработка ошибок и шаблоны отказоустойчивости»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке LLM Apps in Production (RAG + Vector DB + Caching)?

Да. Каждый урок LLM Apps in Production (RAG + Vector DB + Caching) включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Защита ключей API LLM и конфиденциальных данных
  2. Ограничение частоты запросов и предотвращение злоупотреблений
  3. Обработка ошибок и шаблоны отказоустойчивости
  4. Защита от внедрения запросов
← Назад к LLM Apps in Production (RAG + Vector DB + Caching)