Skip to content

Commit a37f599

Browse files
avoid duplicated calls while validating API key
1 parent 7eb6a38 commit a37f599

File tree

2 files changed

+15
-47
lines changed

2 files changed

+15
-47
lines changed

codeflash/api/cfapi.py

Lines changed: 15 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
"""Module for interacting with the Codeflash API."""
2+
13
from __future__ import annotations
24

35
import json
@@ -90,6 +92,7 @@ def make_cfapi_request(
9092
def get_user_id(api_key: Optional[str] = None) -> Optional[str]:
9193
"""Retrieve the user's userid by making a request to the /cfapi/cli-get-user endpoint.
9294
95+
:param api_key: The API key to use. If None, uses get_codeflash_api_key().
9396
:return: The userid or None if the request fails.
9497
"""
9598
if not api_key and not ensure_codeflash_api_key():
@@ -117,55 +120,23 @@ def get_user_id(api_key: Optional[str] = None) -> Optional[str]:
117120
logger.error("Failed to retrieve userid from the response.")
118121
return None
119122

120-
logger.error(f"Failed to look up your userid; is your CF API key valid? ({response.reason})")
121-
return None
122-
123-
124-
def validate_api_key() -> None:
125-
"""Validate the API key by making a request to the /cfapi/cli-get-user endpoint.
126-
127-
Raises SystemExit if the API key is invalid (403) or missing.
128-
This should be called early in the CLI flow before starting optimization.
129-
"""
130-
logger.debug("validate_api_key: Starting API key validation")
131-
api_key = get_codeflash_api_key()
132-
133-
response = make_cfapi_request(
134-
endpoint="/cli-get-user",
135-
method="GET",
136-
extra_headers={"cli_version": __version__},
137-
api_key=api_key,
138-
suppress_errors=True,
139-
)
140-
123+
# Handle 403 (Invalid API key) - exit with error message
141124
if response.status_code == 403:
142-
error_message = "Invalid API key"
143-
try:
144-
json_response = response.json()
145-
if "error" in json_response:
146-
error_message = json_response["error"]
147-
elif "message" in json_response:
148-
error_message = json_response["message"]
149-
except (ValueError, TypeError):
150-
error_message = response.text or "Invalid API key"
151-
152125
msg = (
153-
f"Invalid Codeflash API key. {error_message}\n"
154-
"You can generate a valid API key at https://app.codeflash.ai/app/apikeys,\n"
155-
"then set it as a CODEFLASH_API_KEY environment variable."
126+
"Invalid Codeflash API key. The API key you provided is not valid.\n"
127+
"Please generate a new one at https://app.codeflash.ai/app/apikeys ,\n"
128+
"then set it as a CODEFLASH_API_KEY environment variable.\n"
129+
"For more information, refer to the documentation at \n"
130+
"https://docs.codeflash.ai/optimizing-with-codeflash/codeflash-github-actions#manual-setup\n"
131+
"or\n"
132+
"https://docs.codeflash.ai/optimizing-with-codeflash/codeflash-github-actions#automated-setup-recommended"
156133
)
157-
logger.error(f"validate_api_key: API key validation failed with 403 - {error_message}")
134+
logger.error(f"Failed to look up your userid; is your CF API key valid? ({response.reason})")
158135
exit_with_message(msg, error_on_exit=True)
159136

160-
if response.status_code != 200:
161-
msg = (
162-
f"Failed to validate API key (status {response.status_code}: {response.reason})\n"
163-
"Please check your API key at https://app.codeflash.ai/app/apikeys"
164-
)
165-
logger.error(f"validate_api_key: API key validation failed with status {response.status_code}")
166-
exit_with_message(msg, error_on_exit=True)
167-
168-
logger.debug("validate_api_key: API key validation successful")
137+
# For other errors, log and return None (backward compatibility)
138+
logger.error(f"Failed to look up your userid; is your CF API key valid? ({response.reason})")
139+
return None
169140

170141

171142
def suggest_changes(

codeflash/main.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66

77
from pathlib import Path
88

9-
from codeflash.api.cfapi import validate_api_key
109
from codeflash.cli_cmds.cli import parse_args, process_pyproject_config
1110
from codeflash.cli_cmds.cmd_init import CODEFLASH_LOGO, ask_run_end_to_end_test
1211
from codeflash.cli_cmds.console import paneled_text
@@ -43,8 +42,6 @@ def main() -> None:
4342
args = process_pyproject_config(args)
4443
if not env_utils.check_formatter_installed(args.formatter_cmds):
4544
return
46-
# Validate API key early before starting optimization
47-
validate_api_key()
4845
args.previous_checkpoint_functions = ask_should_use_checkpoint_get_functions(args)
4946
init_sentry(not args.disable_telemetry, exclude_errors=True)
5047
posthog_cf.initialize_posthog(not args.disable_telemetry)

0 commit comments

Comments
 (0)