使用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密钥
1条答案
按热度按时间unhi4e5o1#
您可以尝试在代码中设置最大请求限制。假设您可以在免费层上每分钟发送20个请求,比如说15个请求,那么您可以每4秒发送一个请求。