跳到主要内容

可靠性 - 重试, 回退

LiteLLM 通过 2 种方式帮助防止请求失败

  • 重试
  • 回退: 上下文窗口 + 通用

辅助工具

LiteLLM 支持以下可靠性功能

  • litellm.longer_context_model_fallback_dict: 具有更大等效模型的映射字典
  • num_retries: 使用 tenacity 重试
  • completion() 带回退: 在发生错误时切换模型/密钥/API 基址。

重试失败的请求

在 completion() 中像这样调用 completion(..num_retries=2)

以下是如何快速使用它的示例

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-3.5-turbo",
messages=messages,
num_retries=2
)

回退 (SDK)

上下文窗口回退 (SDK)

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 基址 (SDK)

LLM API 可能不稳定, 带回退的 completion() 可确保您的调用始终获得响应

用法

要将回退模型与 completion() 一起使用, 请在 fallbacks 参数中指定模型列表。

fallbacks 列表应包含您想要使用的主要模型, 然后是可作为备份的其他模型, 以防主要模型未能提供响应。

切换模型

response = completion(model="bad-model", messages=messages, 
fallbacks=["gpt-3.5-turbo" "command-nightly"])

切换 API 密钥/基址 (例如 Azure 部署)

可在同一 Azure 部署的不同密钥之间切换, 或使用另一个部署。

api_key="bad-key"
response = completion(model="azure/gpt-4", 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-3.5-turbo
{
"id": "chatcmpl-7qTmVRuO3m3gIBg4aTmAumV1TmQhB",
"object": "chat.completion",
"created": 1692741891,
"model": "gpt-3.5-turbo-0613",
"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
}
}

回退的工作原理

当您将 fallbacks 传递给 completion 时, 它会使用在 completion(model=model) 中指定为 model 的主要模型进行首次 completion 调用。如果主要模型失败或遇到错误, 它会自动按指定顺序尝试 fallbacks 中的模型。即使主要模型不可用, 这也能确保获得响应。

模型回退实现的关键组成部分:

  • 遍历 fallbacks
  • 限速模型的冷却时间

遍历 fallbacks

为每个请求分配 45秒。在这 45 秒内, 此函数会尝试调用设置为 model 的主要模型。如果模型失败, 它会遍历备份 fallbacks 中的模型, 并在此处设置的 45秒 分配时间内尝试获取响应。

while response == None and time.time() - start_time < 45:
for model in fallbacks:

限速模型的冷却时间

如果模型 API 调用导致错误 - 允许其冷却 60秒

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

带回退的 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