Created
August 21, 2023 05:47
-
-
Save Wind010/f8cc1920246d4b6d903911350d0879ea to your computer and use it in GitHub Desktop.
Python script to check if OpenAI API Key is valid.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# USAGE: api_key_checker.py --keys <API_KEY> | |
# Or populate list of keys in keys list below. | |
import argparse | |
import openai | |
keys = [ | |
] | |
def is_api_key_valid(key): | |
try: | |
openai.api_key = key | |
response = openai.Completion.create( | |
engine="davinci", # https://platform.openai.com/docs/models | |
prompt="This is a test.", | |
max_tokens=5 | |
) | |
except Exception as ex: | |
return str(ex) | |
return False | |
else: | |
return True | |
def check_api_keys(keys): | |
d_keys = {} | |
for k in keys: | |
validity = is_api_key_valid(k) | |
d_keys[k] = validity | |
return d_keys | |
def main(): | |
CLI=argparse.ArgumentParser() | |
CLI.add_argument( | |
"--keys", # Name on the CLI - lose the `--` for positional/required parameters. | |
nargs="*", # Expects 0 or more values and creates a list. | |
type=str, | |
default=[], | |
) | |
args = CLI.parse_args() | |
if args.keys: | |
keys = args.keys | |
d_keys = check_api_keys(keys) | |
for k, v in d_keys.items(): | |
print(f"API key '{k}' validity: {v}") | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment