diff --git a/src/services/models_service.py b/src/services/models_service.py index 01707dd2..c3129af3 100644 --- a/src/services/models_service.py +++ b/src/services/models_service.py @@ -234,12 +234,37 @@ class ModelsService: # Use provided endpoint or default watson_endpoint = endpoint + # Get bearer token from IBM IAM + bearer_token = None + if api_key: + async with httpx.AsyncClient() as client: + token_response = await client.post( + "https://iam.cloud.ibm.com/identity/token", + headers={"Content-Type": "application/x-www-form-urlencoded"}, + data={ + "grant_type": "urn:ibm:params:oauth:grant-type:apikey", + "apikey": api_key, + }, + timeout=10.0, + ) + + if token_response.status_code != 200: + raise Exception( + f"Failed to get IBM IAM token: {token_response.status_code} - {token_response.text}" + ) + + token_data = token_response.json() + bearer_token = token_data.get("access_token") + + if not bearer_token: + raise Exception("No access_token in IBM IAM response") + # Prepare headers for authentication headers = { "Content-Type": "application/json", } - if api_key: - headers["Authorization"] = f"Bearer {api_key}" + if bearer_token: + headers["Authorization"] = f"Bearer {bearer_token}" if project_id: headers["Project-ID"] = project_id