Skip to content

Commit ef6d6ab

Browse files
avoid duplicated api calls
1 parent c4d121e commit ef6d6ab

File tree

3 files changed

+23
-73
lines changed

3 files changed

+23
-73
lines changed

codeflash/api/aiservice.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,27 @@
3232

3333
class AiServiceClient:
3434
def __init__(self) -> None:
35+
# Validate API key before initializing the client
36+
try:
37+
from codeflash.api.cfapi import get_user_id # noqa: PLC0415
38+
39+
# Try to get user ID, if it fails the API key is invalid
40+
user_id = get_user_id()
41+
if user_id is None:
42+
msg = (
43+
"Invalid Codeflash API key. The API key you provided is not valid.\n"
44+
"Please generate a new one at https://app.codeflash.ai/app/apikeys ,\n"
45+
"then set it as a CODEFLASH_API_KEY environment variable.\n"
46+
"For more information, refer to the documentation at \n"
47+
"https://docs.codeflash.ai/optimizing-with-codeflash/codeflash-github-actions#manual-setup\n"
48+
"or\n"
49+
"https://docs.codeflash.ai/optimizing-with-codeflash/codeflash-github-actions#automated-setup-recommended"
50+
)
51+
raise OSError(msg)
52+
except ImportError:
53+
# If cfapi is not available, skip validation
54+
pass
55+
3556
self.base_url = self.get_aiservice_base_url()
3657
self.headers = {"Authorization": f"Bearer {get_codeflash_api_key()}", "Connection": "close"}
3758

codeflash/api/cfapi.py

Lines changed: 1 addition & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ def make_cfapi_request(
8989
def get_user_id(api_key: Optional[str] = None) -> Optional[str]:
9090
"""Retrieve the user's userid by making a request to the /cfapi/cli-get-user endpoint.
9191
92+
:param api_key: The API key to use. If None, uses get_codeflash_api_key().
9293
:return: The userid or None if the request fails.
9394
"""
9495
if not api_key and not ensure_codeflash_api_key():
@@ -119,75 +120,6 @@ def get_user_id(api_key: Optional[str] = None) -> Optional[str]:
119120
logger.error(f"Failed to look up your userid; is your CF API key valid? ({response.reason})")
120121
return None
121122

122-
123-
def validate_api_key(api_key: Optional[str] = None) -> None:
124-
"""Validate that the API key is valid by attempting to retrieve the user ID.
125-
126-
Raises OSError if the API key is invalid or missing.
127-
128-
:param api_key: The API key to validate. If None, uses get_codeflash_api_key().
129-
:raises OSError: If the API key is invalid or missing.
130-
"""
131-
# First check if API key exists
132-
if not api_key:
133-
api_key = get_codeflash_api_key()
134-
135-
def raise_os_error(msg: str) -> None:
136-
"""Raise OSError with the given message."""
137-
raise OSError(msg)
138-
139-
# Make the request to validate the API key
140-
try:
141-
response = make_cfapi_request(
142-
endpoint="/cli-get-user",
143-
method="GET",
144-
extra_headers={"cli_version": __version__},
145-
api_key=api_key,
146-
suppress_errors=True, # Don't log errors yet, we'll handle it below
147-
)
148-
149-
if response.status_code == 403:
150-
msg = (
151-
"Invalid Codeflash API key. The API key you provided is not valid.\n"
152-
"Please generate a new one at https://app.codeflash.ai/app/apikeys ,\n"
153-
"then set it as a CODEFLASH_API_KEY environment variable.\n"
154-
"For more information, refer to the documentation at "
155-
"https://docs.codeflash.ai/getting-started/codeflash-github-actions#add-your-api-key-to-your-repository-secrets"
156-
)
157-
raise_os_error(msg)
158-
elif response.status_code != 200:
159-
msg = (
160-
f"Failed to validate API key with Codeflash API (status {response.status_code}).\n"
161-
"Please verify your API key is correct.\n"
162-
"You can generate a new one at https://app.codeflash.ai/app/apikeys"
163-
)
164-
raise_os_error(msg)
165-
166-
# Check for version updates
167-
if response.status_code == 200:
168-
try:
169-
resp_json = response.json()
170-
min_version = resp_json.get("min_version")
171-
if min_version and version.parse(min_version) > version.parse(__version__):
172-
msg = "Your Codeflash CLI version is outdated. Please update to the latest version using `pip install --upgrade codeflash`."
173-
raise_os_error(msg)
174-
except (json.JSONDecodeError, KeyError, TypeError):
175-
# If response is not JSON or doesn't have min_version, that's okay
176-
pass
177-
178-
except OSError:
179-
# Re-raise OSError as-is
180-
raise
181-
except Exception as e:
182-
# Wrap other exceptions
183-
msg = (
184-
f"Failed to validate API key: {e}\n"
185-
"Please verify your API key is correct.\n"
186-
"You can generate a new one at https://app.codeflash.ai/app/apikeys"
187-
)
188-
raise OSError(msg) from e
189-
190-
191123
def suggest_changes(
192124
owner: str,
193125
repo: str,

codeflash/optimization/optimizer.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from typing import TYPE_CHECKING
1212

1313
from codeflash.api.aiservice import AiServiceClient, LocalAiServiceClient
14-
from codeflash.api.cfapi import send_completion_email, validate_api_key
14+
from codeflash.api.cfapi import send_completion_email
1515
from codeflash.cli_cmds.console import console, logger, progress_bar
1616
from codeflash.code_utils import env_utils
1717
from codeflash.code_utils.code_utils import cleanup_paths, get_run_tmp_file
@@ -494,9 +494,6 @@ def mirror_path(path: Path, src_root: Path, dest_root: Path) -> Path:
494494
def run_with_args(args: Namespace) -> None:
495495
optimizer = None
496496
try:
497-
# Validate API key early before initializing optimizer
498-
validate_api_key()
499-
500497
optimizer = Optimizer(args)
501498
optimizer.run()
502499
except KeyboardInterrupt:

0 commit comments

Comments
 (0)