You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Tenacity解决调用GPT-3模型时的RateLimitError问题

解决OpenAI RateLimitError的Tenacity整合方案

步骤1:安装Tenacity

先安装依赖包:

pip install tenacity

步骤2:修改函数添加重试逻辑

导入Tenacity相关模块,用装饰器为sentiment_text添加针对RateLimitError的重试策略,同时设置指数退避的等待规则,避免频繁请求触发更严格限制:

from tenacity import retry, stop_after_attempt, wait_exponential_jitter, retry_if_exception_type
import openai

def sentiment_prompt(text):
    return """Is the sentiment Positive, Negative or Neutral for the following text:
    
    "{}"
    """.format(text)

@retry(
    stop=stop_after_attempt(5),  # 最多重试5次
    wait=wait_exponential_jitter(initial=1, max=10),  # 指数退避+随机抖动,初始等待1秒,最长10秒
    retry=retry_if_exception_type(openai.error.RateLimitError)  # 仅捕获RateLimitError时重试
)
def sentiment_text(text):
    response = openai.Completion.create(
       engine="text-ada-001",
       prompt=sentiment_prompt(text),
       max_tokens=1000,
       temperature=0,
       top_p=1,
       frequency_penalty=0,
       presence_penalty=0
    )
    sentiment = response.choices[0].text.strip()  # 清理返回结果的多余换行和空格
    return sentiment

步骤3:保持原处理代码不变

你的pandas列处理代码无需修改,直接使用即可:

df['sentiment'] = df['text'].apply(sentiment_text)

关键参数说明

  • stop_after_attempt(5):限制最大重试次数,避免无限循环
  • wait_exponential_jitter:重试等待时间随次数指数增加,同时加入随机抖动,降低请求集中触发限流的概率
  • retry_if_exception_type:精准指定仅对RateLimitError重试,其他异常(如密钥错误、网络故障)直接抛出,方便排查问题

内容的提问来源于stack exchange,提问作者Django0602

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 09:02:19