Skip to content

Commit a0f2b27

Browse files
committed
Add retry for apikey
1 parent 84de6d7 commit a0f2b27

File tree

1 file changed

+29
-18
lines changed

1 file changed

+29
-18
lines changed

services/chatbot/src/mcpserver/server.py

Lines changed: 29 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import json
44
import os
55
import logging
6-
6+
import time
77
# Configure logging
88
logging.basicConfig(
99
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
@@ -26,23 +26,34 @@
2626

2727
def get_api_key():
2828
global API_KEY
29-
if API_KEY is None:
30-
login_body = {"email": API_USER, "password": API_PASSWORD}
31-
apikey_url = f"{BASE_IDENTITY_URL}/identity/management/user/apikey"
32-
headers = {
33-
"Content-Type": "application/json",
34-
}
35-
with httpx.Client(
36-
base_url=API_URL,
37-
headers=headers,
38-
) as client:
39-
response = client.post(apikey_url, json=login_body)
40-
response.raise_for_status()
41-
response_json = response.json()
42-
logger.info(f"Response: {response_json}")
43-
API_KEY = response_json.get("apiKey")
44-
logger.info(f"Chatbot API Key: {API_KEY}")
45-
return API_KEY
29+
# Try 5 times to get API key
30+
MAX_ATTEMPTS = 5
31+
for i in range(MAX_ATTEMPTS):
32+
logger.info(f"Attempt {i+1} to get API key...")
33+
try:
34+
if API_KEY is None:
35+
login_body = {"email": API_USER, "password": API_PASSWORD}
36+
apikey_url = f"{BASE_IDENTITY_URL}/identity/management/user/apikey"
37+
headers = {
38+
"Content-Type": "application/json",
39+
}
40+
with httpx.Client(
41+
base_url=API_URL,
42+
headers=headers,
43+
) as client:
44+
response = client.post(apikey_url, json=login_body)
45+
response.raise_for_status()
46+
response_json = response.json()
47+
logger.info(f"Response: {response_json}")
48+
API_KEY = response_json.get("apiKey")
49+
logger.info(f"Chatbot API Key: {API_KEY}")
50+
return API_KEY
51+
except Exception as e:
52+
if i == MAX_ATTEMPTS - 1:
53+
logger.error(f"Failed to get API key after {i+1} attempts. Giving up.")
54+
raise
55+
logger.error(f"Failed to get API key in attempt {i+1}: {e}. Sleeping for {i} seconds...")
56+
time.sleep(i)
4657
return API_KEY
4758

4859

0 commit comments

Comments
 (0)