안정성 - 재시도, 폴백
안정성 - 재시도, 폴백 (Reliability - Retries, Fallbacks)
LiteLLM은 실패한 요청을 두 가지 방식으로 방지합니다:
- 재시도 (Retries)
- 폴백 (Fallbacks): 컨텍스트 창 + 일반(General)
헬퍼 유틸
LiteLLM은 안정성을 위해 다음 함수를 지원합니다:
litellm.longer_context_model_fallback_dict: 더 큰 등가물이 있는 모델들의 매핑을 가진 사전num_retries: tenacity 재시도를 사용completion()with fallbacks: 오류 시 모델/키/API base 간 전환
실패한 요청 재시도
completion(..num_retries=2) 처럼 completion에서 호출하세요.
사용 방법을 빠르게 보여드릴게요:
from litellm import completion
user_message = "Hello, whats the weather in San Francisco??"
messages = [{"content": user_message, "role": "user"}]
# normal call
response = completion(
model="gpt-5.6-luna",
messages=messages,
num_retries=2
)
폴백 (SDK)
PROXY에서 하는 방법 보기
컨텍스트 창 폴백 (SDK)
아래 ID는 설명용이며 컨텍스트 창 크기를 위해 유지됩니다: 4k 모델이 16k 변형으로 폴백하는 경우.
from litellm import completion
fallback_dict = {"gpt-3.5-turbo": "gpt-3.5-turbo-16k"}
messages = [{"content": "how does a court case get to the Supreme Court?" * 500, "role": "user"}]
completion(model="gpt-3.5-turbo", messages=messages, context_window_fallback_dict=fallback_dict)
출처: 문서
본문
폴백 - 모델/API 키/API base 전환 (SDK)
LLM API는 불안정할 수 있으며, completion() with fallbacks 는 호출에서 항상 응답을 받도록 보장합니다.
사용법
completion() 으로 폴백 모델을 사용하려면 fallbacks 파라미터에 모델 목록을 지정하세요.
fallbacks 목록은 사용하려는 기본 모델을 먼저, 그다음 기본 모델이 응답을 제공하지 못할 경우 백업으로 사용할 수 있는 추가 모델을 포함해야 해요.
모델 전환
response = completion(model="bad-model", messages=messages,
fallbacks=["gpt-5.6-luna" "command-nightly"])
API 키/base 전환 (예: azure 배포)
같은 azure 배포에 대해 서로 다른 키를 전환하거나, 다른 배포도 사용할 수 있습니다.
api_key="bad-key"
response = completion(model="azure/gpt-5.6-terra", messages=messages, api_key=api_key,
fallbacks=[{"api_key": "good-key-1"}, {"api_key": "good-key-2", "api_base": "good-api-base-2"}])
이 섹션에서 구현 세부 사항을 확인하세요.
구현 세부 사항 (SDK)
폴백
호출 출력
Completion with 'bad-model': got exception Unable to map your input to a model. Check your input - {'model': 'bad-model'
completion call gpt-5.6-luna
{
"id": "chatcmpl-7qTmVRuO3m3gIBg4aTmAumV1TmQhB",
"object": "chat.completion",
"created": 1692741891,
"model": "gpt-5.6-luna",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "I apologize, but as an AI, I do not have the capability to provide real-time weather updates. However, you can easily check the current weather in San Francisco by using a search engine or checking a weather website or app."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 16,
"completion_tokens": 46,
"total_tokens": 62
}
}
폴백 동작 방식
completion 에 fallbacks를 전달하면, completion(model=model) 에서 기본 모델로 지정된 기본 모델로 첫 컴플리션 호출을 만듭니다. 기본 모델이 실패하거나 오류가 발생하면 지정된 순서로 fallbacks 모델을 자동으로 시도합니다. 이는 기본 모델을 사용할 수 없어도 응답을 보장합니다.
Model Fallbacks 구현의 핵심 구성 요소:
- fallbacks 루핑
- 속도 제한된 모델의 쿨다운(Cooldowns)
fallbacks 루핑
각 요청에 45초를 허용합니다. 이 45초 동안 이 함수는 model 로 설정된 기본 모델을 호출해 봅니다. model 이 실패하면 백업 fallbacks 모델을 루프하고 할당된 45초 안에 응답을 얻으려 시도합니다:
while response == None and time.time() - start_time < 45:
for model in fallbacks:
...
속도 제한된 모델의 쿨다운
모델 API 호출이 오류로 이어지면 60초 동안 쿨다운을 허용합니다:
try:
...
except Exception as e:
print(f"got exception {e} for model {model}")
rate_limited_models.add(model)
model_expiration_times[model] = (
time.time() + 60
) # cool down this selected model
pass
LLM API 호출을 하기 전에 선택된 모델이 rate_limited_models 에 있는지 확인하고, 있으면 API 호출을 건너뜁니다:
if (
model in rate_limited_models
): # check if model is currently cooling down
if (
model_expiration_times.get(model)
and time.time() >= model_expiration_times[model]
):
rate_limited_models.remove(
model
) # check if it's been 60s of cool down and remove model
else:
continue # skip model
fallbacks()를 포함한 completion의 전체 코드
response = None
rate_limited_models = set()
model_expiration_times = {}
start_time = time.time()
fallbacks = [kwargs["model"]] + kwargs["fallbacks"]
del kwargs["fallbacks"] # remove fallbacks so it's not recursive
while response == None and time.time() - start_time < 45:
for model in fallbacks:
# loop thru all models
try:
if (
model in rate_limited_models
): # check if model is currently cooling down
if (
model_expiration_times.get(model)
and time.time() >= model_expiration_times[model]
):
rate_limited_models.remove(
model
) # check if it's been 60s of cool down and remove model
else:
continue # skip model
# delete model from kwargs if it exists
if kwargs.get("model"):
del kwargs["model"]
print("making completion call", model)
response = litellm.completion(**kwargs, model=model)
if response != None:
return response
except Exception as e:
print(f"got exception {e} for model {model}")
rate_limited_models.add(model)
model_expiration_times[model] = (
time.time() + 60
) # cool down this selected model
pass
return response