在我的情况下,我试图通过一个辅助函数将提示传递给实际的GPT3模型,在我的例子中是text-ada-001,然后最终将其应用于pandas列,使用以下代码。但我遇到了以下错误:
def sentiment_prompt(text): return """Is the sentiment Positive, Negative or Neutral for the following text: "{}" """.format(text) 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 return sentiment
然后最终应用到我的pandas列上:
df['sentiment'] = df['text'].apply(lambda x :sentiment_text(x))
错误如下:
RateLimitError: Rate limit reached for default-global-with-image-limits in organization org-XXXX on requests per min. Limit: 60 / min. Please try again in 1s. Contact [email protected] if you continue to have issues. Please add a payment method to your account to increase your rate limit. Visit https://platform.openai.com/account/billing to add a payment method.
为了克服这个错误,我查看了这个链接,发现tenacity可以帮助解决我的问题。但我不确定如何构建我的代码。目前我正在做以下操作
我如何使用链接中建议的代码来克服速率限制错误?
回答:
在代码开始时导入tenacity,然后在调用OpenAI库的create方法时添加其装饰器。这样你的代码看起来会像这样:
from tenacity import ( retry, stop_after_attempt, wait_random_exponential,) @retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(6))def sentiment_text(text): your_prompt = """Is the sentiment Positive, Negative or Neutral for the following text: "{}" """.format(text) response = openai.Completion.create( engine="text-ada-001", prompt=your_prompt , max_tokens=1000, temperature=0, top_p=1, frequency_penalty=0, presence_penalty=0 ) sentiment = response.choices[0].text return sentiment