호스티드 캐시
호스티드 캐시 (Hosted Cache) - api.litellm.ai
api.litellm.ai를 사용해서 completion()과 embedding() 응답을 캐싱할 수 있어요. 호스티드 캐시를 쓰면 같은 요청을 반복할 때 빠르게 캐시된 응답을 돌려받을 수 있답니다.
출처: 문서
본문
api.litellm.ai를 completion()과 embedding() 응답 캐싱에 사용하세요.
빠른 시작 - Completion (Quick Start Usage)
import litellm
from litellm import completion
from litellm.caching.caching import Cache
litellm.cache = Cache(type="hosted") # init cache to use api.litellm.ai
# 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
Cache(type="hosted")로 캐시를 초기화하면 api.litellm.ai를 이용하게 돼요. 같은 요청이라면 response1 == response2가 되고, 첫 응답이 캐시되어 재사용돼요.
사용 방법 - Embedding()
import time
import litellm
from litellm import completion, embedding
from litellm.caching.caching import Cache
litellm.cache = Cache(type="hosted")
start_time = time.time()
embedding1 = embedding(model="text-embedding-ada-002", input=["hello from litellm"*5], caching=True)
end_time = time.time()
print(f"Embedding 1 response time: {end_time - start_time} seconds")
start_time = time.time()
embedding2 = embedding(model="text-embedding-ada-002", input=["hello from litellm"*5], caching=True)
end_time = time.time()
print(f"Embedding 2 response time: {end_time - start_time} seconds")
스트리밍과 캐싱 (Caching with Streaming)
LiteLLM은 스트리밍 응답도 캐싱할 수 있어요.
사용 방법 (Usage)
import litellm
import time
from litellm import completion
from litellm.caching.caching import Cache
litellm.cache = Cache(type="hosted")
# Make completion calls
response1 = completion(
model="gpt-5.6-luna",
messages=[{"role": "user", "content": "Tell me a joke."}],
stream=True,
caching=True)
for chunk in response1:
print(chunk)
time.sleep(1) # cache is updated asynchronously
response2 = completion(
model="gpt-5.6-luna",
messages=[{"role": "user", "content": "Tell me a joke."}],
stream=True,
caching=True)
for chunk in response2:
print(chunk)
캐시는 비동기적으로 업데이트되므로, 두 번째 호출 전에 잠깐 time.sleep(1)로 기다려 주면 캐시된 응답을 재사용할 수 있어요.