通过重试避免触发速率限制
您已经创建了一个使用自定义消息来运行 Chat Completions 的函数,但发现有时会因为速率限制而失败。您决定使用 tenacity 库中的 @retry 装饰器,在可能的情况下避免报错。
本练习是课程的一部分
使用 OpenAI API 构建 AI 系统
练习说明
- 导入
tenacity库中所需的函数:retry、wait_random_exponential和stop_after_attempt。 - 创建一个 OpenAI API 客户端。
- 完成重试装饰器参数配置:从 5 秒开始重试,最长间隔 40 秒,并在尝试 4 次后停止。
如果练习超时,请确认间隔和尝试次数与上面要求完全一致。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Import the tenacity library
from ____ import ____
client = OpenAI(api_key="")
# Add the appropriate parameters to the decorator
@retry(____, ____)
def get_response(model, message):
response = client.chat.completions.create(
model=model,
messages=[message]
)
return response.choices[0].message.content
print(get_response("gpt-4o-mini", {"role": "user", "content": "List ten holiday destinations."}))