python-3.x 我正在尝试解决有关状态代码的问题:429

djp7away  于 2023-04-13  发布在  Python
关注(0)|答案(1)|浏览(142)

使用OpenAI API的Python自动化代码

parser = argparse.ArgumentParser()
parser.add_argument("prompt", help="The Prompt to send to OpenAI API ")
parser.add_argument("file_name", help="Name of the File")
args = parser.parse_args()

api_endpoints = "https://api.openai.com/v1/completions"
api_key = os.getenv("OPENAI_API_KEY")

request_headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer " + api_key
}

request_data = {
    "model": "text-davinci-003",
    "prompt": f"Write python script for {args.prompt}. Provide only code, no text",
    "max_tokens": 100,
    "temperature": 0.5
}

time.sleep(5)

response = requests.post(api_endpoints, headers=request_headers, json=request_data)

if response.status_code == 200:
    response_text = response.json()["choices"][0]["text"]
    with open(args.file_name, "w") as file:
        file.write(response_text)
else:
    print(f"Request failed with status code : {str(response.status_code)}")

错误:请求失败,状态代码:429
1.免费试用用户20 RPM
1.增加时限
1.隐藏API密钥

unhi4e5o

unhi4e5o1#

您可以尝试在代码中设置最大请求限制。假设您可以在免费层上每分钟发送20个请求,比如说15个请求,那么您可以每4秒发送一个请求。

import time
print("start")
time.sleep(4) # this waits 4 seconds
# send request

相关问题