bibibi12345 commited on
Commit
c2747b9
·
1 Parent(s): 33414ab

fixed bugs

Browse files
Files changed (1) hide show
  1. app/project_id_discovery.py +73 -0
app/project_id_discovery.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import aiohttp
2
+ import json
3
+ import re
4
+ from typing import Dict, Optional
5
+
6
+ # Global cache for project IDs: {api_key: project_id}
7
+ PROJECT_ID_CACHE: Dict[str, str] = {}
8
+
9
+
10
+ async def discover_project_id(api_key: str) -> str:
11
+ """
12
+ Discover project ID by triggering an intentional error with a non-existent model.
13
+ The project ID is extracted from the error message and cached for future use.
14
+
15
+ Args:
16
+ api_key: The Vertex AI Express API key
17
+
18
+ Returns:
19
+ The discovered project ID
20
+
21
+ Raises:
22
+ Exception: If project ID discovery fails
23
+ """
24
+ # Check cache first
25
+ if api_key in PROJECT_ID_CACHE:
26
+ print(f"INFO: Using cached project ID: {PROJECT_ID_CACHE[api_key]}")
27
+ return PROJECT_ID_CACHE[api_key]
28
+
29
+ # Use a non-existent model to trigger error
30
+ error_url = f"https://aiplatform.googleapis.com/v1/publishers/google/models/gemini-2.7-pro-preview-05-06:streamGenerateContent?key={api_key}"
31
+
32
+ # Create minimal request payload
33
+ payload = {
34
+ "contents": [{"role": "user", "parts": [{"text": "test"}]}]
35
+ }
36
+
37
+ async with aiohttp.ClientSession() as session:
38
+ try:
39
+ async with session.post(error_url, json=payload) as response:
40
+ response_text = await response.text()
41
+
42
+ try:
43
+ # Try to parse as JSON first
44
+ error_data = json.loads(response_text)
45
+
46
+ # Handle array response format
47
+ if isinstance(error_data, list) and len(error_data) > 0:
48
+ error_data = error_data[0]
49
+
50
+ if "error" in error_data:
51
+ error_message = error_data["error"].get("message", "")
52
+ # Extract project ID from error message
53
+ # Pattern: "projects/39982734461/locations/..."
54
+ match = re.search(r'projects/(\d+)/locations/', error_message)
55
+ if match:
56
+ project_id = match.group(1)
57
+ PROJECT_ID_CACHE[api_key] = project_id
58
+ print(f"INFO: Discovered project ID: {project_id}")
59
+ return project_id
60
+ except json.JSONDecodeError:
61
+ # If not JSON, try to find project ID in raw text
62
+ match = re.search(r'projects/(\d+)/locations/', response_text)
63
+ if match:
64
+ project_id = match.group(1)
65
+ PROJECT_ID_CACHE[api_key] = project_id
66
+ print(f"INFO: Discovered project ID from raw response: {project_id}")
67
+ return project_id
68
+
69
+ raise Exception(f"Failed to discover project ID. Status: {response.status}, Response: {response_text[:500]}")
70
+
71
+ except Exception as e:
72
+ print(f"ERROR: Failed to discover project ID: {e}")
73
+ raise