캐싱 - 인메모리, Redis, s3, gcs, Redis 시맨틱 캐시, 디스크

캐싱 - 인메모리, Redis, s3, gcs, Redis 시맨틱 캐시, 디스크 (All Caches)

LiteLLM은 다양한 백엔드에서 캐싱을 지원해요. 각 백엔드의 초기화 방법과 캐시 제어, 커스텀 캐시 키에 대해 정리한 페이지입니다.

  • Proxy Server용? 문서는 여기: Caching Proxy Server
  • OpenAI/Anthropic 프롬프트 캐싱은 여기를 보세요.

캐시 초기화 - 인메모리, Redis, s3 Bucket, gcs Bucket, Redis 시맨틱, 디스크, Qdrant 시맨틱

  • redis-cache
  • gcs-cache
  • s3-cache
  • azure-blob-cache
  • redis-semantic cache
  • qdrant-semantic cache
  • valkey-semantic cache
  • in memory cache
  • disk cache

Redis 캐시

Redis 설치:

uv add redis

호스티드 버전은 여기서 자체 Redis DB를 설정할 수 있어요: https://redis.io/try-free/

기본 Redis 캐시:

import litellm
from litellm import completion
from litellm.caching.caching import Cache

litellm.cache = Cache(
    type="redis",
    host="<host>",
    port="<port>",
    password="<password>",
)

# Make completion calls
response1 = completion(
    model="gpt-5.6-luna",
    messages=[{"role": "user", "content": "Tell me a joke."}],
)
response2 = completion(
    model="gpt-5.6-luna",
    messages=[{"role": "user", "content": "Tell me a joke."}],
)

# response1 == response2, response 1 is cached

GCP IAM Redis 인증

IAM 인증을 가진 GCP Memorystore Redis의 경우:

uv add google-cloud-iam
import litellm
from litellm import completion
# For Redis Cluster with GCP IAM
from litellm.caching.redis_cluster_cache import RedisClusterCache

litellm.cache = RedisClusterCache(
    startup_nodes=[
        {"host": "10.128.0.2", "port": 6379},
        {"host": "10.128.0.2", "port": 11008},
    ],
    gcp_service_account="projects/-/serviceAccounts/[email protected]",
    ssl=True,
    ssl_cert_reqs=None,
    ssl_check_hostname=False,
)

# Make completion calls
response1 = completion(
    model="gpt-5.6-luna",
    messages=[{"role": "user", "content": "Tell me a joke."}],
)
response2 = completion(
    model="gpt-5.6-luna",
    messages=[{"role": "user", "content": "Tell me a joke."}],
)

# response1 == response2, response 1 is cached

GCP IAM Redis용 환경 변수:

export REDIS_HOST="10.128.0.2"
export REDIS_PORT="6379"
export REDIS_GCP_SERVICE_ACCOUNT="projects/-/serviceAccounts/[email protected]"
export REDIS_SSL="False"

그다음 간단히 초기화:

litellm.cache = Cache(type="redis")

모든 Redis 클라이언트 라이브러리 파라미터를 구성하는 기본 메커니즘으로 REDIS_* 환경 변수를 사용하세요. 이 접근 방식은 자동으로 매핑됩니다.

gcs 캐시

환경 변수 설정:

GCS_BUCKET_NAME="my-cache-bucket"
GCS_PATH_SERVICE_ACCOUNT="/path/to/service_account.json"
import litellm
from litellm import completion
from litellm.caching.caching import Cache

litellm.cache = Cache(
    type="gcs",
    gcs_bucket_name="my-cache-bucket",
    gcs_path_service_account="/path/to/service_account.json",
)

response1 = completion(
    model="gpt-5.6-luna",
    messages=[{"role": "user", "content": "Tell me a joke."}],
)
response2 = completion(
    model="gpt-5.6-luna",
    messages=[{"role": "user", "content": "Tell me a joke."}],
)

# response1 == response2, response 1 is cached

s3 캐시

boto3 설치:

uv add boto3

AWS 환경 변수 설정:

AWS_ACCESS_KEY_ID = "AKI*******"
AWS_SECRET_ACCESS_KEY = "WOl*****"
import litellm
from litellm import completion
from litellm.caching.caching import Cache

# pass s3-bucket name
litellm.cache = Cache(
    type="s3",
    s3_bucket_name="cache-bucket-litellm",
    s3_region_name="us-west-2",
)

# Make completion calls
response1 = completion(
    model="gpt-5.6-luna",
    messages=[{"role": "user", "content": "Tell me a joke."}],
)
response2 = completion(
    model="gpt-5.6-luna",
    messages=[{"role": "user", "content": "Tell me a joke."}],
)

# response1 == response2, response 1 is cached

azure-blob 캐시

azure-storage-blobazure-identity 설치:

uv add azure-storage-blob azure-identity
import litellm
from litellm import completion
from litellm.caching.caching import Cache
from azure.identity import DefaultAzureCredential

# pass Azure Blob Storage account URL and container name
litellm.cache = Cache(
    type="azure-blob",
    azure_account_url="https://example.blob.core.windows.net",
    azure_blob_container="litellm",
)

# Make completion calls
response1 = completion(
    model="gpt-5.6-luna",
    messages=[{"role": "user", "content": "Tell me a joke."}],
)
response2 = completion(
    model="gpt-5.6-luna",
    messages=[{"role": "user", "content": "Tell me a joke."}],
)

# response1 == response2, response 1 is cached

Redis 시맨틱 캐시

redisvl 클라이언트 설치:

uv add redisvl==0.4.1
import litellm
from litellm import completion
from litellm.caching.caching import Cache

random_number = random.randint(1, 100000)  # add a random number to ensure it's always adding / reading from cache
print("testing semantic caching")

litellm.cache = Cache(
    type="redis-semantic",
    host=os.environ["REDIS_HOST"],
    port=os.environ["REDIS_PORT"],
    password=os.environ["REDIS_PASSWORD"],
    similarity_threshold=0.8,  # similarity threshold for cache hits, 0 == no similarity, 1 = exact matches, 0.5 == 50% similarity
    ttl=120,
    redis_semantic_cache_embedding_model="text-embedding-ada-002",  # this model is passed to litellm.embedding(), any litellm.embedding() model is supported here
)

response1 = completion(
    model="gpt-5.6-luna",
    messages=[
        {"role": "user", "content": f"write a one sentence poem about: {random_number}"}
    ],
    max_tokens=20,
)
print(f"response1: {response1}")

random_number = random.randint(1, 100000)
response2 = completion(
    model="gpt-5.6-luna",
    messages=[
        {"role": "user", "content": f"write a one sentence poem about: {random_number}"}
    ],
    max_tokens=20,
)
print(f"response2: {response1}")

assert response1.id == response2.id  # response1 == response2, response 1 is cached

Qdrant 시맨틱 캐시

자체 클라우드 Qdrant 클러스터는 https://qdrant.tech/documentation/quickstart-cloud/ 로, 로컬 Qdrant 클러스터는 https://qdrant.tech/documentation/quickstart/ 로 설정할 수 있어요.

import litellm
from litellm import completion
from litellm.caching.caching import Cache

random_number = random.randint(1, 100000)  # add a random number to ensure it's always adding / reading from cache
print("testing semantic caching")

litellm.cache = Cache(
    type="qdrant-semantic",
    qdrant_api_base=os.environ["QDRANT_API_BASE"],
    qdrant_api_key=os.environ["QDRANT_API_KEY"],
    qdrant_collection_name="your_collection_name",  # any name of your collection
    similarity_threshold=0.7,  # similarity threshold for cache hits, 0 == no similarity, 1 = exact matches, 0.5 == 50% similarity
    qdrant_quantization_config="binary",  # can be one of 'binary', 'product' or 'scalar' quantizations that is supported by qdrant
    qdrant_semantic_cache_embedding_model="text-embedding-ada-002",  # this model is passed to litellm.embedding(), any litellm.embedding() model is supported here
    qdrant_semantic_cache_vector_size=1536,  # vector size for the embedding model, must match the dimensionality of the embedding model used
)

response1 = completion(
    model="gpt-5.6-luna",
    messages=[
        {"role": "user", "content": f"write a one sentence poem about: {random_number}"}
    ],
    max_tokens=20,
)
print(f"response1: {response1}")

random_number = random.randint(1, 100000)
response2 = completion(
    model="gpt-5.6-luna",
    messages=[
        {"role": "user", "content": f"write a one sentence poem about: {random_number}"}
    ],
    max_tokens=20,
)
print(f"response2: {response2}")

assert response1.id == response2.id  # response1 == response2, response 1 is cached

Valkey 시맨틱 캐시

벡터 저장소가 valkey-search 모듈을 실행하는 Valkey 인스턴스(예: AWS ElastiCache for Valkey)일 때 사용하세요. RediSearch와 RedisVL은 필요 없습니다. LiteLLM이 Redis 프로토콜로 valkey-search를 직접 구동합니다.

요구사항: valkey-search 모듈이 서버에 로드되어야 합니다(MODULE LIST 실행 후 search 확인, 또는 FT._LIST). AWS ElastiCache에서는 노드 기반 Valkey 8.2+ 클러스터에서만 벡터 검색이 가능합니다. cluster-mode-disabled 노드 그룹이 지원되며 권장 대상이고, 수평 샤딩만 지원되지 않으므로 primary + read replicas도 괜찮아요. ElastiCache Serverless는 벡터 검색을 지원하지 않으므로 serverless 엔드포인트에서는 작동하지 않습니다. 이 백엔드는 async 클라이언트가 샤드 간에 FT.* 검색 명령을 라우팅할 수 없으므로 multi-shard(cluster-mode-enabled) 엔드포인트는 지원되지 않습니다. 대신 수직 확장하세요.

로컬에서 valkey-search와 함께 Valkey를 실행하려면 valkey/valkey-bundle 이미지가 모듈을 포함합니다:

docker run -d -p 6379:6379 valkey/valkey-bundle:8.1
import litellm
from litellm import completion
from litellm.caching.caching import Cache

random_number = random.randint(1, 100000)  # add a random number to ensure it's always adding / reading from cache
print("testing semantic caching")

litellm.cache = Cache(
    type="valkey-semantic",
    host=os.environ["VALKEY_HOST"],
    port=os.environ["VALKEY_PORT"],
    password=os.environ.get("VALKEY_PASSWORD"),  # omit for passwordless / IAM-auth clusters
    similarity_threshold=0.8,  # similarity threshold for cache hits, 0 == no similarity, 1 = exact matches, 0.5 == 50% similarity
    ttl=120,
    valkey_semantic_cache_embedding_model="text-embedding-ada-002",  # this model is passed to litellm.embedding(), any litellm.embedding() model is supported here
    valkey_semantic_cache_index_name="litellm_semantic_cache_index",  # optional, defaults to litellm_semantic_cache_index
)

response1 = completion(
    model="gpt-5.6-luna",
    messages=[
        {"role": "user", "content": f"write a one sentence poem about: {random_number}"}
    ],
    max_tokens=20,
)

인메모리 캐시 (빠른 시작)

import litellm
from litellm import completion
from litellm.caching.caching import Cache
litellm.cache = Cache()

# Make completion calls
response1 = completion(
    model="gpt-5.6-luna", 
    messages=[{"role": "user", "content": "Tell me a joke."}],
    caching=True
)
response2 = completion(
    model="gpt-5.6-luna", 
    messages=[{"role": "user", "content": "Tell me a joke."}],
    caching=True
)

# response1 == response2, response 1 is cached

디스크 캐시

디스크 캐싱 extra를 설치하세요:

uv add "litellm[caching]"

그다음 디스크 캐시를 다음과 같이 사용할 수 있어요.

import litellm
from litellm import completion
from litellm.caching.caching import Cache

litellm.cache = Cache(type="disk")

# Make completion calls
response1 = completion(
    model="gpt-5.6-luna",
    messages=[{"role": "user", "content": "Tell me a joke."}],
    caching=True
)
response2 = completion(
    model="gpt-5.6-luna",
    messages=[{"role": "user", "content": "Tell me a joke."}],
    caching=True
)

# response1 == response2, response 1 is cached

코드를 두 번 실행하면 response1이 첫 실행에서 캐시 파일에 저장된 캐시를 사용합니다.

출처: 문서

본문

LiteLLM 호출별 캐시 켜기/끄기

LiteLLM은 4가지 캐시 제어를 지원해요:

  • no-cache : Optional(bool) True면 캐시된 응답을 반환하지 않고 실제 엔드포인트를 호출합니다.

  • no-store : Optional(bool) True면 응답을 캐시하지 않습니다.

  • ttl : Optional(int) - 사용자 정의 시간(초) 동안 응답을 캐시합니다.

  • s-maxage : Optional(int) 사용자 정의 범위(초) 내의 캐시된 응답만 수락합니다.

  • No-Cache

  • No-Store

  • ttl

  • s-maxage

no-cache 예시 - True면 캐시된 응답을 반환하지 않음:

response = litellm.completion(
    model="gpt-5.6-luna",
    messages=[{"role": "user", "content": "hello who are you"}],
    cache={"no-cache": True},
)

no-store 예시 - True면 응답을 캐시하지 않음:

response = litellm.completion(
    model="gpt-5.6-luna",
    messages=[{"role": "user", "content": "hello who are you"}],
    cache={"no-store": True},
)

ttl 예시 - 10초 동안 응답 캐시:

response = litellm.completion(
    model="gpt-5.6-luna",
    messages=[{"role": "user", "content": "hello who are you"}],
    cache={"ttl": 10},
)

s-maxage 예시 - 60초 동안만 캐시된 응답 수락:

response = litellm.completion(
    model="gpt-5.6-luna",
    messages=[{"role": "user", "content": "hello who are you"}],
    cache={"s-maxage": 60},
)

캐시 컨텍스트 매니저 - 캐시 활성화, 비활성화, 업데이트

liteLLM 캐시를 쉽게 활성화/비활성화/업데이트하려면 컨텍스트 매니저를 사용하세요.

캐시 활성화

빠른 시작:

litellm.enable_cache()

고급 파라미터:

def enable_cache(
    type: Optional[Literal["local", "redis", "s3", "gcs", "disk"]] = "local",
    host: Optional[str] = None,
    port: Optional[str] = None,
    password: Optional[str] = None,
    supported_call_types: Optional[
        List[Literal["completion", "acompletion", "embedding", "aembedding", "atranscription", "transcription"]]
    ] = ["completion", "acompletion", "embedding", "aembedding", "atranscription", "transcription"],
    **kwargs,
) -> None: ...

캐시 비활성화

캐싱 끄기:

litellm.disable_cache()

캐시 파라미터 업데이트 (Redis 호스트, 포트 등)

캐시 파라미터 업데이트:

def update_cache(
    type: Optional[Literal["local", "redis", "s3", "gcs", "disk"]] = "local",
    host: Optional[str] = None,
    port: Optional[str] = None,
    password: Optional[str] = None,
    supported_call_types: Optional[
        List[Literal["completion", "acompletion", "embedding", "aembedding", "atranscription", "transcription"]]
    ] = ["completion", "acompletion", "embedding", "aembedding", "atranscription", "transcription"],
    **kwargs,
) -> None: ...

커스텀 캐시 키

캐시 키를 반환하는 함수를 정의하세요:

# this function takes in *args, **kwargs and returns the key you want to use for caching
def custom_get_cache_key(*args, **kwargs):
    # return key to use for your cache:
    key = kwargs.get("model", "") + str(kwargs.get("messages", "")) + str(kwargs.get("temperature", "")) + str(kwargs.get("logit_bias", ""))
    print("key for cache", key)
    return key

litellm.cache.get_cache_key 로 함수를 설정하세요:

from litellm.caching.caching import Cache

cache = Cache(type="redis", host=os.environ['REDIS_HOST'], port=os.environ['REDIS_PORT'], password=os.environ['REDIS_PASSWORD'])

cache.get_cache_key = custom_get_cache_key # set get_cache_key function for your cache

litellm.cache = cache # set litellm.cache to your cache 

커스텀 add/get 캐시 함수 작성

1. 캐시 초기화

from litellm.caching.caching import Cache
cache = Cache()

2. 커스텀 add/get 캐시 함수 정의

def add_cache(self, result, *args, **kwargs):
  ...
  
def get_cache(self, *args, **kwargs):
  ...

3. 캐시 add/get 함수를 자신의 함수로 지정

cache.add_cache = add_cache
cache.get_cache = get_cache

캐시 초기화 파라미터

def __init__(
    self,
    type: Optional[Literal["local", "redis", "redis-semantic", "valkey-semantic", "s3", "gcs", "disk"]] = "local",
    supported_call_types: Optional[
        List[Literal["completion", "acompletion", "embedding", "aembedding", "atranscription", "transcription"]]
    ] = ["completion", "acompletion", "embedding", "aembedding", "atranscription", "transcription"],
    ttl: Optional[float] = None,
    default_in_memory_ttl: Optional[float] = None,

    # redis cache params
    host: Optional[str] = None,
    port: Optional[str] = None,
    password: Optional[str] = None,
    namespace: Optional[str] = None,
    default_in_redis_ttl: Optional[float] = None,
    redis_flush_size=None,
    
    # GCP IAM Redis authentication params
    gcp_service_account: Optional[str] = None,
    gcp_ssl_ca_certs: Optional[str] = None,
    ssl: Optional[bool] = None,
    ssl_cert_reqs: Optional[Union[str, None]] = None,
    ssl_check_hostname: Optional[bool] = None,

    # redis semantic cache params
    similarity_threshold: Optional[float] = None,
    redis_semantic_cache_embedding_model: str = "text-embedding-ada-002",
    redis_semantic_cache_index_name: Optional[str] = None,

    # valkey semantic cache params (valkey-search module, e.g. ElastiCache for Valkey)
    valkey_semantic_cache_embedding_model: str = "text-embedding-ada-002",
    valkey_semantic_cache_index_name: Optional[str] = None,

    # semantic cache tenant scope: "key" (key/team/org) or "end_user" (also per end user)
    semantic_cache_scope: str = "key",

    # s3 Bucket, boto3 configuration
    s3_bucket_name: Optional[str] = None,
    s3_region_name: Optional[str] = None,
    s3_api_version: Optional[str] = None,
    s3_path: Optional[str] = None, # if you wish to save to a specific path
    s3_use_ssl: Optional[bool] = True,
    s3_verify: Optional[Union[bool, str]] = None,
    s3_endpoint_url: Optional[str] = None,
    s3_aws_access_key_id: Optional[str] = None,
    s3_aws_secret_access_key: Optional[str] = None,
    s3_aws_session_token: Optional[str] = None,
    s3_config: Optional[Any] = None,

    # disk cache params
    disk_cache_dir=None,

    # qdrant cache params
    qdrant_api_base: Optional[str] = None,
    qdrant_api_key: Optional[str] = None,
    qdrant_collection_name: Optional[str] = None,
    qdrant_quantization_config: Optional[str] = None,
    qdrant_semantic_cache_embedding_model="text-embedding-ada-002",

    qdrant_semantic_cache_vector_size: Optional[int] = None,
    **kwargs
): ...

로깅

캐시 히트는 success 이벤트에서 kwarg["cache_hit"] 로 로깅됩니다.

접근 예시:

import litellm
from litellm.integrations.custom_logger import CustomLogger
from litellm import completion, acompletion, Cache

# create custom callback for success_events
class MyCustomHandler(CustomLogger):
  async def async_log_success_event(self, kwargs, response_obj, start_time, end_time): 
      print(f"On Success")
      print(f"Value of Cache hit: {kwargs['cache_hit']}")

async def test_async_completion_azure_caching():
  # set custom callback
  customHandler_caching = MyCustomHandler()
  litellm.callbacks = [customHandler_caching]

  # init cache 
  litellm.cache = Cache(type="redis", host=os.environ['REDIS_HOST'], port=os.environ['REDIS_PORT'], password=os.environ['REDIS_PASSWORD'])
  unique_time = time.time()
  response1 = await litellm.acompletion(model="azure/chatgpt-v-2",
                          messages=[{
                              "role": "user",
                              "content": f"Hi 👋 - i'm async azure {unique_time}"
                          }],
                          caching=True)
  await asyncio.sleep(1)
  print(f"customHandler_caching.states pre-cache hit: {customHandler_caching.states}")
  response2 = await litellm.acompletion(model="azure/chatgpt-v-2",
                          messages=[{
                              "role": "user",
                              "content": f"Hi 👋 - i'm async azure {unique_time}"
                          }],
                          caching=True)
  await asyncio.sleep(1) # success callbacks are done in parallel

더 알아보기 (Learn more)