Commit ·
5a054cc
1
Parent(s): 6a843ee
fixed token refresh bug
Browse files356 unmodified lines3573583593603613623633643653663673683693703713723733743757 unmodified lines3833843853863873883893903913923933943952 unmodified lines3983994004014024034044054064074 unmodified lines41241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346460 unmodified lines52552652752852953015 unmodified lines54654754854955055155255335 unmodified lines58959059159259359436 unmodified lines6316326336346356366374 unmodified lines6426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977981 unmodified line800801802803804805806356 unmodified linesraisedef save_credentials(creds, project_id=None):creds_data = {"client_id": CLIENT_ID,"client_secret": CLIENT_SECRET,"access_token": creds.token,"refresh_token": creds.refresh_token,"scope": " ".join(creds.scopes) if creds.scopes else " ".join(SCOPES),"token_type": "Bearer","token_uri": "https://oauth2.googleapis.com/token",}# Add expiry if availableif creds.expiry:creds_data["expiry"] = creds.expiry.isoformat()# If project_id is provided, save it; otherwise preserve existing project_idif project_id:7 unmodified linesexcept Exception:pass # If we can't read existing file, just continue without project_idwith open(CREDENTIAL_FILE, "w") as f:json.dump(creds_data, f)def get_credentials():"""Loads credentials matching gemini-cli OAuth2 flow."""global credentials# Check environment for credentials firstenv_creds = os.getenv("GOOGLE_APPLICATION_CREDENTIALS")if env_creds and os.path.exists(env_creds):2 unmodified linescreds_data = json.load(f)credentials = Credentials.from_authorized_user_info(creds_data, SCOPES)print("Loaded credentials from GOOGLE_APPLICATION_CREDENTIALS.")if credentials.expired and credentials.refresh_token:print("Refreshing expired credentials...")credentials.refresh(GoogleAuthRequest())save_credentials(credentials)return credentialsexcept Exception as e:print(f"Could not load credentials from GOOGLE_APPLICATION_CREDENTIALS: {e}")4 unmodified lineswith open(CREDENTIAL_FILE, "r") as f:creds_data = json.load(f)credentials = Credentials.from_authorized_user_info(creds_data, SCOPES)print("Loaded credentials from cache.")# Try to refresh if we have refresh token but no access tokenif not credentials.token and credentials.refresh_token:print("Attempting to refresh credentials...")try:from google.auth.transport.requests import Request as AuthRequestauth_request = AuthRequest()credentials.refresh(auth_request)print("Credentials refreshed successfully!")# Save refreshed credentialsupdated_creds_data = {'client_id': credentials.client_id,'client_secret': credentials.client_secret,'access_token': credentials.token,'refresh_token': credentials.refresh_token,'scope': credentials.scopes,'token_type': 'Bearer','token_uri': credentials.token_uri,'expiry': credentials.expiry.isoformat() if credentials.expiry else None,'project_id': creds_data.get('project_id')}with open(CREDENTIAL_FILE, 'w') as f:json.dump(updated_creds_data, f, indent=2)print("Refreshed credentials saved.")except Exception as e:print(f"Failed to refresh credentials: {e}")return None# Check if we have a valid token after potential refreshif not credentials.token:print("No access token available after refresh attempt. Starting new login.")return Noneif credentials.expired and credentials.refresh_token:print("Refreshing expired credentials...")try:credentials.refresh(GoogleAuthRequest())save_credentials(credentials)print("Credentials refreshed and saved.")except Exception as refresh_error:print(f"Failed to refresh credentials: {refresh_error}. Starting new login.")return Nonereturn credentialsexcept Exception as e:print(f"Could not load cached credentials: {e}. Starting new login.")60 unmodified linesoauthlib.oauth2.rfc6749.parameters.validate_token_parameters = original_validate@app.options("/{full_path:path}")async def handle_preflight(request: Request, full_path: str):"""Handle CORS preflight requests without authentication."""15 unmodified linesif not creds:print("❌ No credentials available")return Response(content="Authentication failed. Please restart the proxy to log in.", status_code=500)# Check if credentials need refreshing (more lenient validation)if creds.expired and creds.refresh_token:print("Credentials expired. Refreshing...")try:35 unmodified lines# Remove our authentication parametersquery_params.pop("key", None)# Add remaining query parameters to target URL if anyif query_params:from urllib.parse import urlencode36 unmodified linesexcept (json.JSONDecodeError, AttributeError):final_post_data = post_dataheaders = {"Authorization": f"Bearer {creds.token}","Content-Type": "application/json","User-Agent": get_user_agent(),4 unmodified linestry:print(f"[STREAM] Starting streaming request to: {target_url}")print(f"[STREAM] Request payload size: {len(final_post_data)} bytes")# Make the initial streaming requestresp = requests.post(target_url, data=final_post_data, headers=headers, stream=True)print(f"[STREAM] Response status: {resp.status_code}")print(f"[STREAM] Response headers: {dict(resp.headers)}")# If we get a 401, try refreshing the token and retry onceif resp.status_code == 401 and creds.refresh_token:print("[STREAM] Received 401 from Google API. Attempting to refresh token and retry...")resp.close() # Close the failed responsetry:creds.refresh(GoogleAuthRequest())save_credentials(creds)print("[STREAM] Token refreshed successfully. Retrying streaming request...")# Update headers with new token and retryheaders["Authorization"] = f"Bearer {creds.token}"resp = requests.post(target_url, data=final_post_data, headers=headers, stream=True)print(f"[STREAM] Retry request status: {resp.status_code}")except Exception as e:print(f"[STREAM] Could not refresh token after 401 error: {e}")error_message = json.dumps({"error": {"message": "Token refresh failed after 401 error. Please restart the proxy to re-authenticate."}})yield f"data: {error_message}\n\n"returnwith resp:resp.raise_for_status()buffer = ""brace_count = 0in_array = Falsechunk_count = 0total_bytes = 0objects_yielded = 0print(f"[STREAM] Starting to process chunks...")for chunk in resp.iter_content(chunk_size=1024):if isinstance(chunk, bytes):chunk = chunk.decode('utf-8', errors='replace')chunk_count += 1chunk_size = len(chunk) if chunk else 0total_bytes += chunk_sizebuffer += chunk# Process complete JSON objects from the bufferprocessing_iterations = 0while buffer:processing_iterations += 1if processing_iterations > 100: # Prevent infinite loopsbreakbuffer = buffer.lstrip()if not buffer:break# Handle array startif buffer.startswith('[') and not in_array:buffer = buffer[1:].lstrip()in_array = Truecontinue# Handle array endif buffer.startswith(']'):break# Skip commas between objectsif buffer.startswith(','):buffer = buffer[1:].lstrip()continue# Look for complete JSON objectsif buffer.startswith('{'):brace_count = 0in_string = Falseescape_next = Falseend_pos = -1for i, char in enumerate(buffer):if escape_next:escape_next = Falsecontinueif char == '\\':escape_next = Truecontinueif char == '"' and not escape_next:in_string = not in_stringcontinueif not in_string:if char == '{':brace_count += 1elif char == '}':brace_count -= 1if brace_count == 0:end_pos = i + 1breakif end_pos > 0:# Found complete JSON objectjson_str = buffer[:end_pos]buffer = buffer[end_pos:].lstrip()try:obj = json.loads(json_str)if "response" in obj:response_chunk = obj["response"]objects_yielded += 1response_json = json.dumps(response_chunk)yield f"data: {response_json}\n\n"except json.JSONDecodeError as e:continueelse:# Incomplete object, wait for more databreakelse:# Skip unexpected charactersbuffer = buffer[1:]except requests.exceptions.RequestException as e:print(f"Error during streaming request: {e}")error_message = json.dumps({"error": {"message": f"Upstream request failed: {e}"}})yield f"data: {error_message}\n\n"except Exception as e:print(f"An unexpected error occurred during streaming: {e}")error_message = json.dumps({"error": {"message": f"An unexpected error occurred: {e}"}})yield f"data: {error_message}\n\n"return StreamingResponse(stream_generator(), media_type="text/event-stream")else:# Make the requestresp = requests.post(target_url, data=final_post_data, headers=headers)# If we get a 401, try refreshing the token and retry onceif resp.status_code == 401 and creds.refresh_token:print("Received 401 from Google API. Attempting to refresh token and retry...")try:creds.refresh(GoogleAuthRequest())save_credentials(creds)print("Token refreshed successfully. Retrying request...")# Update headers with new token and retryheaders["Authorization"] = f"Bearer {creds.token}"resp = requests.post(target_url, data=final_post_data, headers=headers)print(f"Retry request status: {resp.status_code}")except Exception as e:print(f"Could not refresh token after 401 error: {e}")return Response(content="Token refresh failed after 401 error. Please restart the proxy to re-authenticate.", status_code=500)if resp.status_code == 200:try:1 unmodified line# The actual response is nested under the "response" keystandard_gemini_response = google_api_response.get("response")# Return the response object directly, not wrapped in a listreturn Response(content=json.dumps(standard_gemini_response), status_code=200, media_type="application/json")except (json.JSONDecodeError, AttributeError) as e:print(f"Error converting to standard Gemini format: {e}")# Fallback to sending the original content if conversion fails356 unmodified lines3573583593603613623633643653663673683693703713723733743753763773783793803813823833843857 unmodified lines3933943953963973983994004014024034044054064074084094104114124134144154164172 unmodified lines4204214224234244254264 unmodified lines43143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847960 unmodified lines54054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768815 unmodified lines70470570670770870971071171271335 unmodified lines74975075175275375475575675775836 unmodified lines7957967977987998008014 unmodified lines8068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469471 unmodified line949950951952953954955356 unmodified linesraisedef save_credentials(creds, project_id=None):print(f"DEBUG: Saving credentials - Token: {creds.token[:20] if creds.token else 'None'}..., Expired: {creds.expired}, Expiry: {creds.expiry}")creds_data = {"client_id": CLIENT_ID,"client_secret": CLIENT_SECRET,"token": creds.token, # Use 'token' instead of 'access_token' for consistency with Google Auth Library"refresh_token": creds.refresh_token,"scopes": creds.scopes if creds.scopes else SCOPES, # Use 'scopes' as list instead of 'scope' as string"token_uri": "https://oauth2.googleapis.com/token",}# Add expiry if available - ensure it's timezone-awareif creds.expiry:# Ensure the expiry is timezone-aware (UTC)if creds.expiry.tzinfo is None:from datetime import timezoneexpiry_utc = creds.expiry.replace(tzinfo=timezone.utc)else:expiry_utc = creds.expirycreds_data["expiry"] = expiry_utc.isoformat()print(f"DEBUG: Saving expiry as: {creds_data['expiry']}")else:print("DEBUG: No expiry time available to save")# If project_id is provided, save it; otherwise preserve existing project_idif project_id:7 unmodified linesexcept Exception:pass # If we can't read existing file, just continue without project_idprint(f"DEBUG: Final credential data to save: {json.dumps(creds_data, indent=2)}")with open(CREDENTIAL_FILE, "w") as f:json.dump(creds_data, f, indent=2)print("DEBUG: Credentials saved to file")def get_credentials():"""Loads credentials matching gemini-cli OAuth2 flow."""global credentials# First, check if we already have valid credentials in memoryif credentials and credentials.token:print("Using valid credentials from memory cache.")print(f"DEBUG: Memory credentials - Token: {credentials.token[:20] if credentials.token else 'None'}..., Expired: {credentials.expired}, Expiry: {credentials.expiry}")return credentialselse:print("No valid credentials in memory. Loading from disk.")# Check environment for credentials firstenv_creds = os.getenv("GOOGLE_APPLICATION_CREDENTIALS")if env_creds and os.path.exists(env_creds):2 unmodified linescreds_data = json.load(f)credentials = Credentials.from_authorized_user_info(creds_data, SCOPES)print("Loaded credentials from GOOGLE_APPLICATION_CREDENTIALS.")print(f"DEBUG: Env credentials - Token: {credentials.token[:20] if credentials.token else 'None'}..., Expired: {credentials.expired}, Expiry: {credentials.expiry}")return credentialsexcept Exception as e:print(f"Could not load credentials from GOOGLE_APPLICATION_CREDENTIALS: {e}")4 unmodified lineswith open(CREDENTIAL_FILE, "r") as f:creds_data = json.load(f)print(f"DEBUG: Raw credential data from file: {json.dumps(creds_data, indent=2)}")# Handle both old format (access_token) and new format (token)if "access_token" in creds_data and "token" not in creds_data:creds_data["token"] = creds_data["access_token"]print("DEBUG: Converted access_token to token field")# Handle both old format (scope as string) and new format (scopes as list)if "scope" in creds_data and "scopes" not in creds_data:creds_data["scopes"] = creds_data["scope"].split()print("DEBUG: Converted scope string to scopes list")credentials = Credentials.from_authorized_user_info(creds_data, SCOPES)print("Loaded credentials from cache.")print(f"DEBUG: Loaded credentials - Token: {credentials.token[:20] if credentials.token else 'None'}..., Expired: {credentials.expired}, Expiry: {credentials.expiry}")# Manual expiry check to avoid timezone issuesif credentials.expiry:from datetime import datetime, timezonenow = datetime.now(timezone.utc)# Handle timezone-naive expiry by assuming it's UTCif credentials.expiry.tzinfo is None:expiry_utc = credentials.expiry.replace(tzinfo=timezone.utc)else:expiry_utc = credentials.expirytime_until_expiry = expiry_utc - nowprint(f"DEBUG: Current time: {now}")print(f"DEBUG: Token expires at: {expiry_utc}")print(f"DEBUG: Time until expiry: {time_until_expiry}")# Override the expired property if the token is actually still validis_actually_expired = time_until_expiry.total_seconds() <= 0print(f"DEBUG: Token is actually expired: {is_actually_expired}")print(f"DEBUG: Google Auth Library says expired: {credentials.expired}")if not is_actually_expired and credentials.token:print("DEBUG: Token is valid, overriding expired status")# Monkey patch the expired property to return Falsecredentials._expiry = expiry_utcreturn credentialsreturn credentialsexcept Exception as e:print(f"Could not load cached credentials: {e}. Starting new login.")60 unmodified linesoauthlib.oauth2.rfc6749.parameters.validate_token_parameters = original_validate@app.get("/v1/models")async def list_models(request: Request, username: str = Depends(authenticate_user)):"""List available models - matching gemini-cli supported models exactly."""print(f"[GET] /v1/models - User: {username}")# Return all models supported by gemini-cli based on tokenLimits.tsmodels_response = {"models": [{"name": "models/gemini-1.5-pro","version": "001","displayName": "Gemini 1.5 Pro","description": "Mid-size multimodal model that supports up to 2 million tokens","inputTokenLimit": 2097152,"outputTokenLimit": 8192,"supportedGenerationMethods": ["generateContent", "streamGenerateContent"],"temperature": 1.0,"maxTemperature": 2.0,"topP": 0.95,"topK": 64},{"name": "models/gemini-1.5-flash","version": "001","displayName": "Gemini 1.5 Flash","description": "Fast and versatile multimodal model for scaling across diverse tasks","inputTokenLimit": 1048576,"outputTokenLimit": 8192,"supportedGenerationMethods": ["generateContent", "streamGenerateContent"],"temperature": 1.0,"maxTemperature": 2.0,"topP": 0.95,"topK": 64},{"name": "models/gemini-2.5-pro-preview-05-06","version": "001","displayName": "Gemini 2.5 Pro Preview 05-06","description": "Preview version of Gemini 2.5 Pro from May 6th","inputTokenLimit": 1048576,"outputTokenLimit": 8192,"supportedGenerationMethods": ["generateContent", "streamGenerateContent"],"temperature": 1.0,"maxTemperature": 2.0,"topP": 0.95,"topK": 64},{"name": "models/gemini-2.5-pro-preview-06-05","version": "001","displayName": "Gemini 2.5 Pro Preview 06-05","description": "Preview version of Gemini 2.5 Pro from June 5th","inputTokenLimit": 1048576,"outputTokenLimit": 8192,"supportedGenerationMethods": ["generateContent", "streamGenerateContent"],"temperature": 1.0,"maxTemperature": 2.0,"topP": 0.95,"topK": 64},{"name": "models/gemini-2.5-pro","version": "001","displayName": "Gemini 2.5 Pro","description": "Advanced multimodal model with enhanced capabilities","inputTokenLimit": 1048576,"outputTokenLimit": 8192,"supportedGenerationMethods": ["generateContent", "streamGenerateContent"],"temperature": 1.0,"maxTemperature": 2.0,"topP": 0.95,"topK": 64},{"name": "models/gemini-2.5-flash-preview-05-20","version": "001","displayName": "Gemini 2.5 Flash Preview 05-20","description": "Preview version of Gemini 2.5 Flash from May 20th","inputTokenLimit": 1048576,"outputTokenLimit": 8192,"supportedGenerationMethods": ["generateContent", "streamGenerateContent"],"temperature": 1.0,"maxTemperature": 2.0,"topP": 0.95,"topK": 64},{"name": "models/gemini-2.5-flash","version": "001","displayName": "Gemini 2.5 Flash","description": "Fast and efficient multimodal model with latest improvements","inputTokenLimit": 1048576,"outputTokenLimit": 8192,"supportedGenerationMethods": ["generateContent", "streamGenerateContent"],"temperature": 1.0,"maxTemperature": 2.0,"topP": 0.95,"topK": 64},{"name": "models/gemini-2.0-flash","version": "001","displayName": "Gemini 2.0 Flash","description": "Latest generation fast multimodal model","inputTokenLimit": 1048576,"outputTokenLimit": 8192,"supportedGenerationMethods": ["generateContent", "streamGenerateContent"],"temperature": 1.0,"maxTemperature": 2.0,"topP": 0.95,"topK": 64},{"name": "models/gemini-2.0-flash-preview-image-generation","version": "001","displayName": "Gemini 2.0 Flash Preview Image Generation","description": "Preview version with image generation capabilities","inputTokenLimit": 32000,"outputTokenLimit": 8192,"supportedGenerationMethods": ["generateContent", "streamGenerateContent"],"temperature": 1.0,"maxTemperature": 2.0,"topP": 0.95,"topK": 64},{"name": "models/gemini-embedding-001","version": "001","displayName": "Gemini Embedding 001","description": "Text embedding model for semantic similarity and search","inputTokenLimit": 2048,"outputTokenLimit": 1,"supportedGenerationMethods": ["embedContent"],"temperature": 0.0,"maxTemperature": 0.0,"topP": 1.0,"topK": 1}]}return Response(content=json.dumps(models_response), status_code=200, media_type="application/json; charset=utf-8")@app.options("/{full_path:path}")async def handle_preflight(request: Request, full_path: str):"""Handle CORS preflight requests without authentication."""15 unmodified linesif not creds:print("❌ No credentials available")return Response(content="Authentication failed. Please restart the proxy to log in.", status_code=500)print(f"Using credentials - Token: {creds.token[:20] if creds.token else 'None'}..., Expired: {creds.expired}")# Check if credentials need refreshing (only when expired)if creds.expired and creds.refresh_token:print("Credentials expired. Refreshing...")try:35 unmodified lines# Remove our authentication parametersquery_params.pop("key", None)# For streaming requests, always ensure alt=sse is setif is_streaming:query_params["alt"] = "sse"# Add remaining query parameters to target URL if anyif query_params:from urllib.parse import urlencode36 unmodified linesexcept (json.JSONDecodeError, AttributeError):final_post_data = post_datarequest_headers = {"Authorization": f"Bearer {creds.token}","Content-Type": "application/json","User-Agent": get_user_agent(),4 unmodified linestry:print(f"[STREAM] Starting streaming request to: {target_url}")print(f"[STREAM] Request payload size: {len(final_post_data)} bytes")print(f"[STREAM] Authorization header: Bearer {creds.token[:50]}...")print(f"[STREAM] Full headers being sent: {request_headers}")# Make the initial streaming requestresp = requests.post(target_url, data=final_post_data, headers=request_headers, stream=True)print(f"[STREAM] Response status: {resp.status_code}")print(f"[STREAM] Response headers: {dict(resp.headers)}")# If we get a 401, try refreshing the token onceif resp.status_code == 401:print("[STREAM] Received 401 from Google API. Attempting token refresh...")print(f"[STREAM] Response text: {resp.text}")if creds.refresh_token:try:creds.refresh(GoogleAuthRequest())save_credentials(creds)print("[STREAM] Token refreshed successfully. Retrying request...")# Update headers with new tokenrequest_headers["Authorization"] = f"Bearer {creds.token}"# Retry the request with refreshed tokenresp = requests.post(target_url, data=final_post_data, headers=request_headers, stream=True)print(f"[STREAM] Retry response status: {resp.status_code}")if resp.status_code == 401:print("[STREAM] Still getting 401 after token refresh.")yield f'data: {{"error": {{"message": "Authentication failed even after token refresh. Please restart the proxy to re-authenticate."}}}}\n\n'returnexcept Exception as refresh_error:print(f"[STREAM] Token refresh failed: {refresh_error}")yield f'data: {{"error": {{"message": "Token refresh failed. Please restart the proxy to re-authenticate."}}}}\n\n'returnelse:print("[STREAM] No refresh token available.")yield f'data: {{"error": {{"message": "Authentication failed. Please restart the proxy to re-authenticate."}}}}\n\n'returnwith resp:resp.raise_for_status()# Process exactly like the real Gemini SDKprint("[STREAM] Processing with Gemini SDK-compatible logic")# Use iter_lines() exactly like the real Gemini SDK (without decode_unicode)# This should be non-blocking and yield lines as they arrivefor chunk in resp.iter_lines():if chunk:# Decode UTF-8 if it's bytes (matching SDK logic exactly)if not isinstance(chunk, str):chunk = chunk.decode('utf-8')# Strip 'data: ' prefix if present (matching SDK logic)if chunk.startswith('data: '):chunk = chunk[len('data: '):]try:# Parse the JSON from Google's internal APIobj = json.loads(chunk)# Convert Google's internal format to standard Gemini formatif "response" in obj:response_chunk = obj["response"]# Output in standard Gemini streaming formatresponse_json = json.dumps(response_chunk, separators=(',', ':'))yield f"data: {response_json}\n\n"except json.JSONDecodeError:# Skip invalid JSONcontinueexcept requests.exceptions.RequestException as e:print(f"Error during streaming request: {e}")# Format error as real Gemini API wouldyield f'data: {{"error": {{"message": "Upstream request failed: {str(e)}"}}}}\n\n'except Exception as e:print(f"An unexpected error occurred during streaming: {e}")# Format error as real Gemini API wouldyield f'data: {{"error": {{"message": "An unexpected error occurred: {str(e)}"}}}}\n\n'# Create the streaming response with headers matching real Gemini APIresponse_headers = {"Content-Type": "text/event-stream","Content-Disposition": "attachment","Vary": "Origin, X-Origin, Referer","X-XSS-Protection": "0","X-Frame-Options": "SAMEORIGIN","X-Content-Type-Options": "nosniff","Server": "ESF"}response = StreamingResponse(stream_generator(),media_type="text/event-stream",headers=response_headers)return responseelse:# Make the requestprint(f"[NON-STREAM] Starting request to: {target_url}")print(f"[NON-STREAM] Authorization header: Bearer {creds.token[:50]}...")print(f"[NON-STREAM] Full headers being sent: {request_headers}")resp = requests.post(target_url, data=final_post_data, headers=request_headers)print(f"[NON-STREAM] Response status: {resp.status_code}")print(f"[NON-STREAM] Response headers: {dict(resp.headers)}")# If we get a 401, try refreshing the token onceif resp.status_code == 401:print("Received 401 from Google API. Attempting token refresh...")print(f"Response text: {resp.text}")if creds.refresh_token:try:creds.refresh(GoogleAuthRequest())save_credentials(creds)print("Token refreshed successfully. Retrying request...")# Update headers with new tokenrequest_headers["Authorization"] = f"Bearer {creds.token}"# Retry the request with refreshed tokenresp = requests.post(target_url, data=final_post_data, headers=request_headers)print(f"Retry response status: {resp.status_code}")if resp.status_code == 401:print("Still getting 401 after token refresh.")return Response(content="Authentication failed even after token refresh. Please restart the proxy to re-authenticate.", status_code=500)except Exception as refresh_error:print(f"Token refresh failed: {refresh_error}")return Response(content="Token refresh failed. Please restart the proxy to re-authenticate.", status_code=500)else:print("No refresh token available.")return Response(content="Authentication failed. Please restart the proxy to re-authenticate.", status_code=500)if resp.status_code == 200:try:1 unmodified line# The actual response is nested under the "response" keystandard_gemini_response = google_api_response.get("response")# Return the response object directly, not wrapped in a listreturn Response(content=json.dumps(standard_gemini_response), status_code=200, media_type="application/json; charset=utf-8")except (json.JSONDecodeError, AttributeError) as e:print(f"Error converting to standard Gemini format: {e}")# Fallback to sending the original content if conversion fails
gemini_proxy.py+335-186