LLM 응답 캐싱

·3분 읽기

원문: Koog Documentation — llm-response-caching 이 글은 Koog 공식 문서의 llm-response-caching 페이지를 한국어로 옮긴 번역본입니다. 문서 구조와 링크 의미를 유지하되, MkDocs 전용 UI 문법은 블로그에서 읽기 좋도록 정리했습니다.

LLM 응답 캐싱

프롬프트 실행기로 실행하는 반복 요청의 경우 LLM 응답을 캐시하여 Kotlin과 Java 모두에서 성능을 최적화하고 비용을 절감할 수 있습니다. Koog에서는 CachedPromptExecutor을 통해 모든 프롬프트 실행자가 캐싱을 사용할 수 있습니다. 이는 캐싱 기능을 추가하는 PromptExecutor 주위의 래퍼입니다. 이전에 실행된 프롬프트의 응답을 저장하고 동일한 프롬프트가 다시 실행될 때 이를 검색할 수 있습니다.

Kotlin 또는 Java에서 캐시된 프롬프트 실행기를 만들려면 다음을 수행하세요.

  1. 응답을 캐시하려는 프롬프트 실행기를 만듭니다.
  2. 원하는 캐시와 생성한 프롬프트 실행기를 제공하여 CachedPromptExecutor 인스턴스를 생성합니다.
  3. 원하는 프롬프트와 모델을 사용하여 생성된 CachedPromptExecutor을 실행합니다.

예는 다음과 같습니다.

코틀린

1// Create a prompt executor2val client = OpenAILLMClient(System.getenv("OPENAI_API_KEY"))3val promptExecutor = MultiLLMPromptExecutor(client)45// Create a cached prompt executor6val cachedExecutor = CachedPromptExecutor(7    cache = FilePromptCache(Path("path/to/your/cache/directory")),8    nested = promptExecutor9)1011// Run cached prompt executor for the first time12// This will perform an actual LLM request13val firstTime = measureTimeMillis {14    val firstResponse = cachedExecutor.execute(prompt, OpenAIModels.Chat.GPT4o)15    println("First response: ${firstResponse.first().content}")16}17println("First execution took: ${firstTime}ms")1819// Run cached prompt executor for the second time20// This will return the result immediately from the cache21val secondTime = measureTimeMillis {22    val secondResponse = cachedExecutor.execute(prompt, OpenAIModels.Chat.GPT4o)23    println("Second response: ${secondResponse.first().content}")24}25println("Second execution took: ${secondTime}ms")

자바

1// Create a prompt2Prompt prompt = Prompt.builder("test")3        .user("Hello")4        .build();56// Create a prompt executor7OpenAILLMClient client = new OpenAILLMClient(System.getenv("OPENAI_API_KEY"));8MultiLLMPromptExecutor promptExecutor = new MultiLLMPromptExecutor(client);910// Create a cached prompt executor11FilePromptCache cache = new FilePromptCache(Path.of("path/to/your/cache/directory"), null);12CachedPromptExecutor cachedExecutor = new CachedPromptExecutor(cache, promptExecutor, Clock.System.INSTANCE);1314// Run cached prompt executor for the first time15// This will perform an actual LLM request16long start1 = System.nanoTime();17List<Message.Response> firstResponse = cachedExecutor.execute(prompt, OllamaModels.Meta.LLAMA_3_2);18long firstTimeMs = (System.nanoTime() - start1) / 1_000_000L;19System.out.println("First response: " + firstResponse.getFirst().getContent());20System.out.println("First execution took: " + firstTimeMs + "ms");2122// Run cached prompt executor for the second time23// This will return the result immediately from the cache24long start2 = System.nanoTime();25List<Message.Response> secondResponse = cachedExecutor.execute(prompt, OllamaModels.Meta.LLAMA_3_2);26long secondTimeMs = (System.nanoTime() - start2) / 1_000_000L;27System.out.println("Second response: " + secondResponse.getFirst().getContent());28System.out.println("Second execution took: " + secondTimeMs + "ms");

이 예에서는 다음과 같은 출력을 생성합니다.

1First response: Hello! It seems like we're starting a new conversation. What can I help you with today?2First execution took: 48ms3Second response: Hello! It seems like we're starting a new conversation. What can I help you with today?4Second execution took: 1ms

두 번째 응답은 캐시에서 검색되며 1ms만 소요됩니다.

참고

  • 캐시된 프롬프트 실행기를 사용하여 Kotlin에서 executeStreaming() 또는 Java에서 executeStreamingWithPublisher()을 호출하면 응답이 단일 청크로 생성됩니다.
  • Kotlin 또는 Java에서 캐시된 프롬프트 실행기로 moderate()을 호출하면 요청이 중첩된 프롬프트 실행기로 전달되고 캐시를 사용하지 않습니다.
  • Kotlin이나 Java에서는 객관식 응답(executeMultipleChoices()) 캐싱이 지원되지 않습니다.