completion()을 Fallbacks(Failover)로 안정성 확보하기
completion()을 Fallbacks(Failover)로 안정성 확보하기
LLM API는 불안정할 수 있어요. 이 튜토리얼에서는 completion() 함수와 모델 fallbacks(장애 조치, failover)를 함께 사용해 호출이 항상 응답을 받도록 하는 방법을 다룹니다. 기본 모델이 실패해도 백업 모델 목록을 순회하면서 응답을 보장받을 수 있어요.
출처: 문서
본문
Virtual Key를 위한 Fallbacks 설정
사용법
completion()에서 fallback 모델을 사용하려면 fallbacks 파라미터에 모델 목록을 지정합니다. fallbacks 목록에는 사용하고 싶은 기본(primary) 모델을 먼저 넣고, 그 뒤에 기본 모델이 응답하지 못할 때 쓸 백업 모델들을 나열하면 돼요.
response = completion(model="bad-model", fallbacks=["gpt-5.6-luna" "command-nightly"], messages=messages)
completion_with_fallbacks()는 어떻게 동작하나요?
completion_with_fallbacks() 함수는 completion(model=model)에서 model로 지정한 기본 모델로 completion 호출을 시도합니다. 기본 모델이 실패하거나 오류가 나면 지정된 순서대로 fallbacks 모델을 자동으로 시도해요. 이 덕분에 기본 모델을 사용할 수 없어도 항상 응답을 받을 수 있어요.
호출의 출력
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 }}
Model Fallbacks 구현의 핵심 구성 요소
-
fallbacks목록 순회하기 -
rate-limited 모델에 대한 Cool-Downs
fallbacks 목록 순회하기
각 요청에 45초를 허용합니다. 이 45초 동안 model로 지정한 기본 모델을 호출해 봐요. 기본 모델이 실패하면 백업 fallbacks 모델을 순회하면서 여기에 설정된 45초 시간 안에 응답을 얻으려고 시도합니다.
while response == None and time.time() - start_time
rate-limited 모델에 대한 Cool-Downs
모델 API 호출에서 오류가 발생하면 해당 모델을 60초 동안 cooldown 하도록 허용해요.
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 = 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