From 1c157c7a86a488c814d97e700104d7244a08cc31 Mon Sep 17 00:00:00 2001 From: rafiq-mahsud <88088087+rafiq-mahsud@users.noreply.github.com> Date: Fri, 11 Aug 2023 23:07:44 +0500 Subject: [PATCH] Update model.py --- easycompletion/model.py | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/easycompletion/model.py b/easycompletion/model.py index 4bbcacc..dc623af 100644 --- a/easycompletion/model.py +++ b/easycompletion/model.py @@ -23,9 +23,23 @@ from .prompt import count_tokens -openai.api_key = EASYCOMPLETION_API_KEY openai.api_base = EASYCOMPLETION_API_ENDPOINT +def validate_api_key(api_key=None): + """ + Validates the OpenAI API key. + + Parameters: + api_key (str, optional): OpenAI API key. If not provided, it uses the one defined in constants.py. + + Returns: + bool: True if the API key is valid, False otherwise. + """ + if api_key is None: + api_key = EASYCOMPLETION_API_KEY + + return api_key is not None and api_key.strip() != "" + def parse_arguments(arguments, debug=DEBUG): """ Parses arguments that are expected to be either a JSON string, dictionary, or a list. @@ -154,7 +168,6 @@ def validate_functions(response, functions, function_call, debug=DEBUG): log("Function call is valid", type="success", log=debug) return True - def chat_completion( messages, model_failure_retries=5, @@ -180,10 +193,11 @@ def chat_completion( Example: >>> text_completion("Hello, how are you?", model_failure_retries=3, model='gpt-3.5-turbo', chunk_length=1024, api_key='your_openai_api_key') """ + # Validate the API key + if not validate_api_key(api_key): + return {"error": "Invalid OpenAI API key"} - # Override the API key if provided as parameter - if api_key is not None: - openai.api_key = api_key + openai.api_key = api_key # Use the default model if no model is specified if model == None: