0Pricing
LLM Apps in Production (RAG + Vector DB + Caching) · レッスン

エラーハンドリングとレジリエンスパターン

堅牢なエラーハンドリング、リトライ機構、サーキットブレーカーを設計し、LLMアプリケーションの耐障害性を高めます。

「エラーハンドリングとレジリエンスパターン」はCoddyKit上の無料LLM Apps in Production (RAG + Vector DB + Caching)レッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これは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時間対応のAIチューター)、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時間対応のAIチューターがレッスンを進める中での質問に答えます。

LLM Apps in Production (RAG + Vector DB + Caching)を始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのLLM Apps in Production (RAG + Vector DB + Caching)は初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/4です。

「エラーハンドリングとレジリエンスパターン」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このLLM Apps in Production (RAG + Vector DB + Caching)レッスンでコードを書いて実行できますか?

はい。すべてのLLM Apps in Production (RAG + Vector DB + Caching)レッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. LLM APIキーと機密データの保護
  2. レート制限と不正利用の防止
  3. エラーハンドリングとレジリエンスパターン
  4. プロンプトインジェクションから防御する
← LLM Apps in Production (RAG + Vector DB + Caching)に戻る