From 9832807814d7da6017773d3e0533229cdd1dc9d2 Mon Sep 17 00:00:00 2001 From: Paul Gauthier Date: Sat, 27 May 2023 06:21:06 -0700 Subject: [PATCH] aider: Added custom exception `MissingAPIKeyError` to `Coder` class to raise an error when no OpenAI API key is provided. # Context: USER: what's a good exception to raise in coder if no api key ASSISTANT: A good exception to raise in this case would be a custom exception, such as `MissingAPIKeyError`. You can define this custom exception by subclassing the built-in `ValueError` class. Here's how to define and raise the custom exception: ```python aider/coder.py <<<<<<< ORIGINAL class Coder: abs_fnames = None repo = None last_aider_commit_hash = None last_asked_for_commit_time = 0 def __init__( self, io, main_model="gpt-4", fnames=None, pretty=True, show_diffs=False, auto_commits=True, dirty_commits=True, dry_run=False, use_ctags=False, verbose=False, openai_api_key=None, ): if openai_api_key: openai.api_key = openai_api_key else: io.tool_error('No OpenAI API key provided.') ======= class MissingAPIKeyError(ValueError): pass class Coder: abs_fnames = None repo = None last_aider_commit_hash = None last_asked_for_commit_time = 0 def __init__( self, io, main_model="gpt-4", fnames=None, pretty=True, show_diffs=False, auto_commits=True, dirty_commits=True, dry_run=False, use_ctags=False, verbose=False, openai_api_key=None, ): if openai_api_key: openai.api_key = openai_api_key else: raise MissingAPIKeyError('No OpenAI API key provided.') >>>>>>> UPDATED ``` This custom exception `MissingAPIKeyError` will provide a more specific and informative error message when the API key is not provided. --- aider/coder.py | 6 +++++- aider/main.py | 1 + 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/aider/coder.py b/aider/coder.py index 1890d2d4a..45e72b8e4 100755 --- a/aider/coder.py +++ b/aider/coder.py @@ -20,6 +20,9 @@ from aider import prompts from aider.commands import Commands from aider.repomap import RepoMap +class MissingAPIKeyError(ValueError): + pass + class Coder: abs_fnames = None repo = None @@ -43,7 +46,8 @@ class Coder: if openai_api_key: openai.api_key = openai_api_key else: - openai.api_key = os.getenv("OPENAI_API_KEY") + raise MissingAPIKeyError('No OpenAI API key provided.') + self.verbose = verbose self.abs_fnames = set() self.cur_messages = [] diff --git a/aider/main.py b/aider/main.py index ba91e86eb..dd0d87734 100644 --- a/aider/main.py +++ b/aider/main.py @@ -131,6 +131,7 @@ def main(args=None, input=None, output=None): "--openai-api-key", metavar="OPENAI_API_KEY", help="Specify the OpenAI API key", + env_var="OPENAI_API_KEY", ) parser.add_argument( "--dry-run",