bibibi12345 commited on
Commit
d09d5b5
·
verified ·
1 Parent(s): 40acccd
Files changed (1) hide show
  1. app/main.py +143 -17
app/main.py CHANGED
@@ -179,38 +179,97 @@ def init_vertex_ai():
179
  credentials_json_str = os.environ.get("GOOGLE_CREDENTIALS_JSON")
180
  if credentials_json_str:
181
  try:
182
- credentials_info = json.loads(credentials_json_str)
183
- credentials = service_account.Credentials.from_service_account_info(credentials_info, scopes=['https://www.googleapis.com/auth/cloud-platform'])
184
- project_id = credentials.project_id
185
- client = genai.Client(vertexai=True, credentials=credentials, project=project_id, location="us-central1")
186
- print(f"Initialized Vertex AI using GOOGLE_CREDENTIALS_JSON env var for project: {project_id}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
  return True
188
  except Exception as e:
189
  print(f"Error loading credentials from GOOGLE_CREDENTIALS_JSON: {e}")
190
  # Fall through to other methods if this fails
191
 
192
  # Priority 2: Try to use the credential manager to get credentials from files
 
193
  credentials, project_id = credential_manager.get_next_credentials()
194
 
195
  if credentials and project_id:
196
- client = genai.Client(vertexai=True, credentials=credentials, project=project_id, location="us-central1")
197
- print(f"Initialized Vertex AI using Credential Manager for project: {project_id}")
198
- return True
199
-
200
- # Priority 3: Fall back to GOOGLE_APPLICATION_CREDENTIALS environment variable (file path)
201
- file_path = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS")
202
- if file_path and os.path.exists(file_path):
203
  try:
204
- credentials = service_account.Credentials.from_service_account_file(file_path, scopes=['https://www.googleapis.com/auth/cloud-platform'])
205
- project_id = credentials.project_id
206
  client = genai.Client(vertexai=True, credentials=credentials, project=project_id, location="us-central1")
207
- print(f"Initialized Vertex AI using GOOGLE_APPLICATION_CREDENTIALS file path for project: {project_id}")
208
  return True
209
  except Exception as e:
210
- print(f"Error loading credentials from GOOGLE_APPLICATION_CREDENTIALS path {file_path}: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
 
212
  # If none of the methods worked
213
- print(f"Error: No valid credentials found. Tried GOOGLE_CREDENTIALS_JSON, Credential Manager ({credential_manager.credentials_dir}), and GOOGLE_APPLICATION_CREDENTIALS.")
 
 
 
214
  return False
215
  except Exception as e:
216
  print(f"Error initializing authentication: {e}")
@@ -778,3 +837,70 @@ def health_check(api_key: str = Depends(get_api_key)):
778
  "current_index": credential_manager.current_index
779
  }
780
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
  credentials_json_str = os.environ.get("GOOGLE_CREDENTIALS_JSON")
180
  if credentials_json_str:
181
  try:
182
+ print(f"Found GOOGLE_CREDENTIALS_JSON environment variable, length: {len(credentials_json_str)} characters")
183
+ # Try to parse the JSON
184
+ try:
185
+ credentials_info = json.loads(credentials_json_str)
186
+ print(f"Successfully parsed JSON from GOOGLE_CREDENTIALS_JSON")
187
+ # Check if the parsed JSON has the expected structure
188
+ if not isinstance(credentials_info, dict):
189
+ print(f"ERROR: Parsed JSON is not a dictionary, type: {type(credentials_info)}")
190
+ raise ValueError("Credentials JSON must be a dictionary")
191
+
192
+ # Check for required fields in the service account JSON
193
+ required_fields = ["type", "project_id", "private_key_id", "private_key", "client_email"]
194
+ missing_fields = [field for field in required_fields if field not in credentials_info]
195
+ if missing_fields:
196
+ print(f"ERROR: Missing required fields in credentials JSON: {missing_fields}")
197
+ raise ValueError(f"Credentials JSON missing required fields: {missing_fields}")
198
+
199
+ print(f"Credentials JSON contains all required fields")
200
+ except json.JSONDecodeError as json_err:
201
+ print(f"ERROR: Failed to parse GOOGLE_CREDENTIALS_JSON as JSON: {json_err}")
202
+ # Print a small sample of the string for debugging (avoid printing the whole thing for security)
203
+ safe_sample = credentials_json_str[:20] + "..." if len(credentials_json_str) > 20 else credentials_json_str
204
+ print(f"First few characters: {safe_sample}")
205
+ raise
206
+
207
+ # Create credentials from the parsed JSON
208
+ try:
209
+ credentials = service_account.Credentials.from_service_account_info(
210
+ credentials_info,
211
+ scopes=['https://www.googleapis.com/auth/cloud-platform']
212
+ )
213
+ project_id = credentials.project_id
214
+ print(f"Successfully created credentials object for project: {project_id}")
215
+ except Exception as cred_err:
216
+ print(f"ERROR: Failed to create credentials from parsed JSON: {cred_err}")
217
+ raise
218
+
219
+ # Initialize the client with the credentials
220
+ try:
221
+ client = genai.Client(vertexai=True, credentials=credentials, project=project_id, location="us-central1")
222
+ print(f"Initialized Vertex AI using GOOGLE_CREDENTIALS_JSON env var for project: {project_id}")
223
+ except Exception as client_err:
224
+ print(f"ERROR: Failed to initialize genai.Client: {client_err}")
225
+ raise
226
  return True
227
  except Exception as e:
228
  print(f"Error loading credentials from GOOGLE_CREDENTIALS_JSON: {e}")
229
  # Fall through to other methods if this fails
230
 
231
  # Priority 2: Try to use the credential manager to get credentials from files
232
+ print(f"Trying credential manager (directory: {credential_manager.credentials_dir})")
233
  credentials, project_id = credential_manager.get_next_credentials()
234
 
235
  if credentials and project_id:
 
 
 
 
 
 
 
236
  try:
 
 
237
  client = genai.Client(vertexai=True, credentials=credentials, project=project_id, location="us-central1")
238
+ print(f"Initialized Vertex AI using Credential Manager for project: {project_id}")
239
  return True
240
  except Exception as e:
241
+ print(f"ERROR: Failed to initialize client with credentials from Credential Manager: {e}")
242
+
243
+ # Priority 3: Fall back to GOOGLE_APPLICATION_CREDENTIALS environment variable (file path)
244
+ file_path = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS")
245
+ if file_path:
246
+ print(f"Checking GOOGLE_APPLICATION_CREDENTIALS file path: {file_path}")
247
+ if os.path.exists(file_path):
248
+ try:
249
+ print(f"File exists, attempting to load credentials")
250
+ credentials = service_account.Credentials.from_service_account_file(
251
+ file_path,
252
+ scopes=['https://www.googleapis.com/auth/cloud-platform']
253
+ )
254
+ project_id = credentials.project_id
255
+ print(f"Successfully loaded credentials from file for project: {project_id}")
256
+
257
+ try:
258
+ client = genai.Client(vertexai=True, credentials=credentials, project=project_id, location="us-central1")
259
+ print(f"Initialized Vertex AI using GOOGLE_APPLICATION_CREDENTIALS file path for project: {project_id}")
260
+ return True
261
+ except Exception as client_err:
262
+ print(f"ERROR: Failed to initialize client with credentials from file: {client_err}")
263
+ except Exception as e:
264
+ print(f"ERROR: Failed to load credentials from GOOGLE_APPLICATION_CREDENTIALS path {file_path}: {e}")
265
+ else:
266
+ print(f"ERROR: GOOGLE_APPLICATION_CREDENTIALS file does not exist at path: {file_path}")
267
 
268
  # If none of the methods worked
269
+ print(f"ERROR: No valid credentials found. Tried all methods:")
270
+ print(f" 1. GOOGLE_CREDENTIALS_JSON: {'Present' if os.environ.get('GOOGLE_CREDENTIALS_JSON') else 'Not found'}")
271
+ print(f" 2. Credential Manager: Directory {credential_manager.credentials_dir}, Files found: {len(credential_manager.credentials_files)}")
272
+ print(f" 3. GOOGLE_APPLICATION_CREDENTIALS: {'Present' if os.environ.get('GOOGLE_APPLICATION_CREDENTIALS') else 'Not found'}")
273
  return False
274
  except Exception as e:
275
  print(f"Error initializing authentication: {e}")
 
837
  "current_index": credential_manager.current_index
838
  }
839
  }
840
+
841
+ # Diagnostic endpoint for troubleshooting credential issues
842
+ @app.get("/debug/credentials")
843
+ def debug_credentials(api_key: str = Depends(get_api_key)):
844
+ """
845
+ Diagnostic endpoint to check credential configuration without actually authenticating.
846
+ This helps troubleshoot issues with credential setup, especially on Hugging Face.
847
+ """
848
+ # Check GOOGLE_CREDENTIALS_JSON
849
+ creds_json = os.environ.get("GOOGLE_CREDENTIALS_JSON")
850
+ creds_json_status = {
851
+ "present": creds_json is not None,
852
+ "length": len(creds_json) if creds_json else 0,
853
+ "parse_status": "not_attempted"
854
+ }
855
+
856
+ # Try to parse the JSON if present
857
+ if creds_json:
858
+ try:
859
+ creds_info = json.loads(creds_json)
860
+ # Check for required fields
861
+ required_fields = ["type", "project_id", "private_key_id", "private_key", "client_email"]
862
+ missing_fields = [field for field in required_fields if field not in creds_info]
863
+
864
+ creds_json_status.update({
865
+ "parse_status": "success",
866
+ "is_dict": isinstance(creds_info, dict),
867
+ "missing_required_fields": missing_fields,
868
+ "project_id": creds_info.get("project_id", "not_found"),
869
+ # Include a safe sample of the private key to check if it's properly formatted
870
+ "private_key_sample": creds_info.get("private_key", "not_found")[:10] + "..." if "private_key" in creds_info else "not_found"
871
+ })
872
+ except json.JSONDecodeError as e:
873
+ creds_json_status.update({
874
+ "parse_status": "error",
875
+ "error": str(e),
876
+ "sample": creds_json[:20] + "..." if len(creds_json) > 20 else creds_json
877
+ })
878
+
879
+ # Check credential files
880
+ credential_manager.refresh_credentials_list()
881
+
882
+ # Check GOOGLE_APPLICATION_CREDENTIALS
883
+ app_creds_path = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS")
884
+ app_creds_status = {
885
+ "present": app_creds_path is not None,
886
+ "path": app_creds_path,
887
+ "exists": os.path.exists(app_creds_path) if app_creds_path else False
888
+ }
889
+
890
+ return {
891
+ "environment": {
892
+ "GOOGLE_CREDENTIALS_JSON": creds_json_status,
893
+ "CREDENTIALS_DIR": {
894
+ "path": credential_manager.credentials_dir,
895
+ "exists": os.path.exists(credential_manager.credentials_dir),
896
+ "files_found": len(credential_manager.credentials_files),
897
+ "files": [os.path.basename(f) for f in credential_manager.credentials_files]
898
+ },
899
+ "GOOGLE_APPLICATION_CREDENTIALS": app_creds_status
900
+ },
901
+ "recommendations": [
902
+ "Ensure GOOGLE_CREDENTIALS_JSON contains the full, properly formatted JSON content of your service account key",
903
+ "Check for any special characters or line breaks that might need proper escaping",
904
+ "Verify that the service account has the necessary permissions for Vertex AI"
905
+ ]
906
+ }