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.
This commit is contained in:
Paul Gauthier 2023-05-27 06:21:06 -07:00
parent abf73d00a2
commit 9832807814
2 changed files with 6 additions and 1 deletions

View file

@ -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 = []

View file

@ -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",