pandas 如何在使用Tenacity处理GPT3模型时克服速率限制错误

l7wslrjt  于 2023-05-27  发布在  其他
关注(0)|答案(1)|浏览(149)

在我的情况下,我试图使用helper函数向实际的GPT 3模型传递提示符,在我的情况下是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 support@openai.com 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.

为了克服这个错误,我正在研究这个link,发现tenacity可以帮助解决我的问题。但我不知道如何构建我的代码。目前我正在做以下事情
如何使用链接中建议的代码来克服速率限制错误?

jexiocij

jexiocij1#

在代码的开头导入tenacity,然后在使用create调用openai库的地方添加装饰。所以你代码看起来像这样:

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

相关问题