跳至主要內容

快取

備註

關於 OpenAI/Anthropic Prompt Caching,請前往 這裡

快取 LLM 回應。LiteLLM 的快取系統會儲存並重用 LLM 回應,以節省成本並降低延遲。當您兩次送出相同的請求時,系統會回傳快取的回應,而不是再次呼叫 LLM API。

支援的快取

  • 記憶體快取
  • 磁碟快取
  • Redis 快取
  • Qdrant 語意快取
  • Redis 語意快取
  • Valkey 語意快取
  • S3 Bucket 快取
  • GCS Bucket 快取

虛擬金鑰驗證快取(Redis)

當 proxy 驗證 virtual key(客戶 API 金鑰)時,結果會被快取,這樣就不必在每次請求時查詢資料庫。預設情況下,該快取只存在於每個 worker process 中——因此在部署之後,新 pod 或額外的 Uvicorn workers 會各自預熱自己的快取,並可能在快取預熱完成前觸發更多 DB 讀取。

設定 litellm_settings.enable_redis_auth_cache: true,即可將 virtual-key 驗證資料鏡像到在 litellm_settings.cache / cache_params 下設定的同一個 Redis instance。接著,workers 與 replicas 就能在整個叢集之間共享已快取的驗證項目。

需求

  • litellm_settings.cache 必須是 true(proxy 的 Redis 會在快取設定期間初始化)。請參閱 所有設定
  • cache_params.type 必須是 redis(或依您的快取設定使用 Redis Cluster);驗證快取會附加到該 Redis client。請參閱 支援的 cache_params
  • 可選擇設定 general_settings.user_api_key_cache_ttl(秒):當啟用 Redis 驗證快取時,TTL 會同時套用於記憶體與 Redis 兩層,因此過期金鑰會一致地失效。

範例:

litellm_settings:
cache: true
enable_redis_auth_cache: true
cache_params:
type: redis
host: os.environ/REDIS_HOST
port: 6379

general_settings:
user_api_key_cache_ttl: 300 # optional; seconds
提示

啟動記錄會區分這兩種模式:使用 enable_redis_auth_cache: true 時,您應該會看到一則訊息,表示 virtual-key 查詢會在 workers 之間共享。

快速開始

可透過在 config.yaml 中加入 cache 鍵來啟用快取

步驟 1:將 cache 加入 config.yaml

model_list:
- model_name: gpt-3.5-turbo
litellm_params:
model: gpt-3.5-turbo
- model_name: text-embedding-ada-002
litellm_params:
model: text-embedding-ada-002

litellm_settings:
set_verbose: True
cache: True # set cache responses to True, litellm defaults to using a redis cache

[選用] 步驟 1.5:加入 redis 命名空間、預設 ttl

命名空間

如果您想為金鑰建立某個資料夾,可以這樣設定命名空間:

litellm_settings:
cache: true
cache_params: # set cache params for redis
type: redis
namespace: "litellm.caching.caching"

金鑰會像這樣儲存:

litellm.caching.caching:<hash>

Redis 叢集

model_list:
- model_name: "*"
litellm_params:
model: "*"

litellm_settings:
cache: True
cache_params:
type: redis
redis_startup_nodes: [{ "host": "127.0.0.1", "port": "7001" }]

Redis Sentinel

model_list:
- model_name: "*"
litellm_params:
model: "*"

litellm_settings:
cache: true
cache_params:
type: "redis"
service_name: "mymaster"
sentinel_nodes: [["localhost", 26379]]
sentinel_password: "password" # [OPTIONAL]

TTL

litellm_settings:
cache: true
cache_params: # set cache params for redis
type: redis
ttl: 600 # will be cached on redis for 600s
# default_in_memory_ttl: Optional[float], default is None. time in seconds.
# default_in_redis_ttl: Optional[float], default is None. time in seconds.

SSL

只要在您的 .env 中設定 REDIS_SSL="True",LiteLLM 就會讀取這個設定。

REDIS_SSL="True"

若要快速測試,您也可以使用 REDIS_URL,例如:

REDIS_URL="rediss://.."

但我們建議在正式環境使用 REDIS_URL。我們注意到使用它與使用 redis_host、port 等設定之間有效能差異。

GCP IAM 驗證

若要使用具備 IAM 驗證的 GCP Memorystore Redis,請安裝所需相依套件:

目前只有透過 GCP 才支援 redis 的 IAM 驗證,且目前僅支援 Redis Clusters。
uv add google-cloud-iam

適用於具 GCP IAM 的 Redis Cluster:

litellm_settings:
cache: True
cache_params:
type: redis
redis_startup_nodes:
[{ "host": "10.128.0.2", "port": 6379 }, { "host": "10.128.0.2", "port": 11008 }]
gcp_service_account: "projects/-/serviceAccounts/your-sa@project.iam.gserviceaccount.com"
ssl: true
ssl_cert_reqs: null
ssl_check_hostname: false

步驟 2:將 Redis 憑證加入 .env

在您的作業系統環境中設定 REDIS_URLREDIS_HOST,以啟用快取。

REDIS_URL = ""        # REDIS_URL='redis://username:password@hostname:port/database'
## OR ##
REDIS_HOST = "" # REDIS_HOST='redis-18841.c274.us-east-1-3.ec2.cloud.redislabs.com'
REDIS_PORT = "" # REDIS_PORT='18841'
REDIS_PASSWORD = "" # REDIS_PASSWORD='liteLlmIsAmazing'
REDIS_USERNAME = "" # REDIS_USERNAME='my-redis-username' [OPTIONAL] if your redis server requires a username
REDIS_SSL = "True" # REDIS_SSL='True' to enable SSL by default is False

其他 kwargs

資訊

使用 REDIS_* 環境變數來設定所有 Redis client library 參數。這是切換 Redis 設定的建議方式,因為它會自動將環境變數對應到 Redis client kwargs。

您可以透過在作業系統環境中儲存變數和值,來傳入任何額外的 redis.Redis 引數,如下所示:

REDIS_<redis-kwarg-name> = ""

例如:

REDIS_SSL = "True"
REDIS_SSL_CERT_REQS = "None"
REDIS_CONNECTION_POOL_KWARGS = '{"max_connections": 20}'
注意

注意:對於非字串型別的 Redis 參數(例如整數、布林值或複雜物件),請避免使用 REDIS_* 環境變數,因為在 Redis client 初始化期間可能會失敗。對於這類參數,請改用您路由器設定中的 cache_kwargs

查看它如何從環境讀取

步驟 3:使用 config 執行 proxy

$ litellm --config /path/to/config.yaml

使用方式

基本

兩次送出相同的請求:

curl http://0.0.0.0:4000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-3.5-turbo",
"messages": [{"role": "user", "content": "write a poem about litellm!"}],
"temperature": 0.7
}'

curl http://0.0.0.0:4000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-3.5-turbo",
"messages": [{"role": "user", "content": "write a poem about litellm!"}],
"temperature": 0.7
}'

動態快取控制

參數類型說明
ttl選用(int)會依使用者定義的時間長度(以秒為單位)快取回應
s-maxage選用(int)只會接受落在使用者定義範圍內(以秒為單位)的快取回應
no-cache選用(bool)不會將回應儲存在快取中。
no-store選用(bool)不會快取回應
namespace選用(str)會在使用者定義的命名空間下快取回應

每個快取參數都可針對每個請求進行控制。以下是各參數的範例:

ttl

設定回應要快取多久(以秒為單位)。

from openai import OpenAI

client = OpenAI(
api_key="your-api-key",
base_url="http://0.0.0.0:4000"
)

chat_completion = client.chat.completions.create(
messages=[{"role": "user", "content": "Hello"}],
model="gpt-3.5-turbo",
extra_body={
"cache": {
"ttl": 300 # Cache response for 5 minutes
}
}
)

s-maxage

只接受在指定年齡範圍內(以秒為單位)的快取回應。

from openai import OpenAI

client = OpenAI(
api_key="your-api-key",
base_url="http://0.0.0.0:4000"
)

chat_completion = client.chat.completions.create(
messages=[{"role": "user", "content": "Hello"}],
model="gpt-3.5-turbo",
extra_body={
"cache": {
"s-maxage": 600 # Only use cache if less than 10 minutes old
}
}
)

no-cache

強制取得新的回應,略過快取。

from openai import OpenAI

client = OpenAI(
api_key="your-api-key",
base_url="http://0.0.0.0:4000"
)

chat_completion = client.chat.completions.create(
messages=[{"role": "user", "content": "Hello"}],
model="gpt-3.5-turbo",
extra_body={
"cache": {
"no-cache": True # Skip cache check, get fresh response
}
}
)

no-store

不會將回應儲存在快取中。

from openai import OpenAI

client = OpenAI(
api_key="your-api-key",
base_url="http://0.0.0.0:4000"
)

chat_completion = client.chat.completions.create(
messages=[{"role": "user", "content": "Hello"}],
model="gpt-3.5-turbo",
extra_body={
"cache": {
"no-store": True # Don't cache this response
}
}
)

namespace

將回應儲存在特定的快取命名空間下。

from openai import OpenAI

client = OpenAI(
api_key="your-api-key",
base_url="http://0.0.0.0:4000"
)

chat_completion = client.chat.completions.create(
messages=[{"role": "user", "content": "Hello"}],
model="gpt-3.5-turbo",
extra_body={
"cache": {
"namespace": "my-custom-namespace" # Store in custom namespace
}
}
)

設定 proxy 的快取,但不在實際的 llm api 請求上啟用

如果您只想啟用像是速率限制與跨多個 實例的負載平衡等功能,請使用此項。

設定 supported_call_types: [] 以停用實際 api 請求上的快取。

litellm_settings:
cache: True
cache_params:
type: redis
supported_call_types: []

快取除錯 - /cache/ping

LiteLLM Proxy 提供一個 /cache/ping 端點,用來測試快取是否如預期運作

使用方式

curl --location 'http://0.0.0.0:4000/cache/ping'  -H "Authorization: Bearer sk-1234"

預期回應 - 當快取正常時

{
"status": "healthy",
"cache_type": "redis",
"ping_response": true,
"set_cache_response": "success",
"litellm_cache_params": {
"supported_call_types": "['completion', 'acompletion', 'embedding', 'aembedding', 'atranscription', 'transcription']",
"type": "redis",
"namespace": "None"
},
"redis_cache_params": {
"redis_client": "Redis<ConnectionPool<Connection<host=redis-16337.c322.us-east-1-2.ec2.cloud.redislabs.com,port=16337,db=0>>>",
"redis_kwargs": "{'url': 'redis://:******@redis-16337.c322.us-east-1-2.ec2.cloud.redislabs.com:16337'}",
"async_redis_conn_pool": "BlockingConnectionPool<Connection<host=redis-16337.c322.us-east-1-2.ec2.cloud.redislabs.com,port=16337,db=0>>",
"redis_version": "7.2.0"
}
}

進階

控制快取啟用的請求類型 - (/chat/completion/embeddings 等)

預設情況下,所有請求類型都會啟用快取。您可以透過在 cache_params 中設定 supported_call_types,來控制哪些請求類型啟用快取。

快取只會對 supported_call_types 中指定的請求類型啟用

litellm_settings:
cache: True
cache_params:
type: redis
supported_call_types:
["acompletion", "atext_completion", "aembedding", "atranscription"]
# /chat/completions, /completions, /embeddings, /audio/transcriptions

在 config.yaml 上設定快取參數

model_list:
- model_name: gpt-3.5-turbo
litellm_params:
model: gpt-3.5-turbo
- model_name: text-embedding-ada-002
litellm_params:
model: text-embedding-ada-002

litellm_settings:
set_verbose: True
cache: True # set cache responses to True, litellm defaults to using a redis cache
cache_params: # cache_params are optional
type: "redis" # The type of cache to initialize. Can be "local", "redis", "s3", or "gcs". Defaults to "local".
host: "localhost" # The host address for the Redis cache. Required if type is "redis".
port: 6379 # The port number for the Redis cache. Required if type is "redis".
password: "your_password" # The password for the Redis cache. Required if type is "redis".

# Optional configurations
supported_call_types:
["acompletion", "atext_completion", "aembedding", "atranscription"]
# /chat/completions, /completions, /embeddings, /audio/transcriptions

刪除快取鍵 - /cache/delete

若要刪除快取鍵,請向 /cache/delete 發送包含您要刪除之 keys 的請求

範例

curl -X POST "http://0.0.0.0:4000/cache/delete" \
-H "Authorization: Bearer sk-1234" \
-d '{"keys": ["586bf3f3c1bf5aecb55bd9996494d3bbc69eb58397163add6d49537762a7548d", "key2"]}'
# {"status":"success"}

檢視回應中的快取鍵

您可以在回應標頭中查看 cache_key,在命中快取時,快取鍵會以 x-litellm-cache-key 回應標頭的形式傳送

curl -i --location 'http://0.0.0.0:4000/chat/completions' \
--header 'Authorization: Bearer sk-1234' \
--header 'Content-Type: application/json' \
--data '{
"model": "gpt-3.5-turbo",
"user": "ishan",
"messages": [
{
"role": "user",
"content": "what is litellm"
}
],
}'

來自 litellm proxy 的回應

date: Thu, 04 Apr 2024 17:37:21 GMT
content-type: application/json
x-litellm-cache-key: 586bf3f3c1bf5aecb55bd9996494d3bbc69eb58397163add6d49537762a7548d

{
"id": "chatcmpl-9ALJTzsBlXR9zTxPvzfFFtFbFtG6T",
"choices": [
{
"finish_reason": "stop",
"index": 0,
"message": {
"content": "I'm sorr.."
"role": "assistant"
}
}
],
"created": 1712252235,
}

**將快取預設關閉 - 僅在選用時啟用 **

  1. mode: default_off 設為快取
model_list:
- model_name: fake-openai-endpoint
litellm_params:
model: openai/fake
api_key: fake-key
api_base: https://exampleopenaiendpoint-production.up.railway.app/

# default off mode
litellm_settings:
set_verbose: True
cache: True
cache_params:
mode: default_off # 👈 Key change cache is default_off
  1. 在快取預設關閉時選用啟用快取
import os
from openai import OpenAI

client = OpenAI(api_key=<litellm-api-key>, base_url="http://0.0.0.0:4000")

chat_completion = client.chat.completions.create(
messages=[
{
"role": "user",
"content": "Say this is a test",
}
],
model="gpt-3.5-turbo",
extra_body = { # OpenAI python accepts extra args in extra_body
"cache": {"use-cache": True}
}
)

Redis 最大連線數

您可以在 Redis 的 cache_params 中設定 max_connections 參數。這會直接傳遞給 Redis 用戶端,並控制連線池中的最大同時連線數。如果您看到像 No connection available 這樣的錯誤,請嘗試增加這個值:

litellm_settings:
cache: true
cache_params:
type: redis
max_connections: 100

proxy config.yaml 上支援的 cache_params

cache_params:
# ttl
ttl: Optional[float]
default_in_memory_ttl: Optional[float]
default_in_redis_ttl: Optional[float]
max_connections: Optional[Int]

# Type of cache (options: "local", "redis", "s3", "gcs")
type: s3

# List of litellm call types to cache for
# Options: "completion", "acompletion", "embedding", "aembedding"
supported_call_types:
["acompletion", "atext_completion", "aembedding", "atranscription"]
# /chat/completions, /completions, /embeddings, /audio/transcriptions

# Redis cache parameters
host: localhost # Redis server hostname or IP address
port: "6379" # Redis server port (as a string)
password: secret_password # Redis server password
namespace: Optional[str] = None,

# GCP IAM Authentication for Redis
gcp_service_account: "projects/-/serviceAccounts/your-sa@project.iam.gserviceaccount.com" # GCP service account for IAM authentication
gcp_ssl_ca_certs: "./server-ca.pem" # Path to SSL CA certificate file for GCP Memorystore Redis
ssl: true # Enable SSL for secure connections
ssl_cert_reqs: null # Set to null for self-signed certificates
ssl_check_hostname: false # Set to false for self-signed certificates

# S3 cache parameters
s3_bucket_name: your_s3_bucket_name # Name of the S3 bucket
s3_region_name: us-west-2 # AWS region of the S3 bucket
s3_api_version: 2006-03-01 # AWS S3 API version
s3_use_ssl: true # Use SSL for S3 connections (options: true, false)
s3_verify: true # SSL certificate verification for S3 connections (options: true, false)
s3_endpoint_url: https://s3.amazonaws.com # S3 endpoint URL
s3_aws_access_key_id: your_access_key # AWS Access Key ID for S3
s3_aws_secret_access_key: your_secret_key # AWS Secret Access Key for S3
s3_aws_session_token: your_session_token # AWS Session Token for temporary credentials

# GCS cache parameters
gcs_bucket_name: your_gcs_bucket_name # Name of the GCS bucket
gcs_path_service_account: /path/to/service-account.json # Path to GCS service account JSON file
gcs_path: cache/ # [OPTIONAL] GCS path prefix for cache objects

供應者專屬選用參數快取

預設情況下,LiteLLM 只會在快取鍵中包含標準 OpenAI 參數。不過,某些提供者(例如 Vertex AI)會使用會影響輸出但未納入標準快取鍵生成的額外參數。

啟用提供者專屬參數快取

將此設定加入您的 config.yaml,以將提供者專屬的選用參數納入快取鍵:

litellm_settings:
cache: True
cache_params:
type: "redis"
enable_caching_on_provider_specific_optional_params: True # Include provider-specific params in cache keys

進階 - 使用者 api key 快取 ttl

設定記憶體內快取儲存金鑰物件的時間長度(可避免 db 請求)

general_settings:
user_api_key_cache_ttl: <your-number> #time in seconds

預設此值為 60 秒。