Commit ·
9119b63
1
Parent(s): a87d626
fixed token expire at startup issue
Browse files420 unmodified lines42142242342442542647 unmodified lines474475476477478479356 unmodified lines83683783883984084184284384484584684784884985023 unmodified lines8748758768778788798801 unmodified line882883884885886887888889890891892420 unmodified linescredentials = 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}")47 unmodified linescredentials._expiry = expiry_utcreturn credentialsreturn credentialsexcept Exception as e:print(f"Could not load cached credentials: {e}. Starting new login.")356 unmodified linesif 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:23 unmodified linesresponse_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 JSONcontinue1 unmodified lineexcept 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 = {420 unmodified lines42142242342442542642742842943043143243343443543643743843944047 unmodified lines488489490491492493494495496497498499500501502503504505506356 unmodified lines86386486586686786886987087187287387487587687723 unmodified lines9019029039049059069079089091 unmodified line911912913914915916917918919920921420 unmodified linescredentials = 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}")# Always refresh tokens at startup when loading from file to avoid issuesif credentials.refresh_token:print("Refreshing environment credentials at startup for reliability...")try:credentials.refresh(GoogleAuthRequest())# Note: We don't save environment credentials back to the env fileprint("Startup token refresh successful for environment credentials.")except Exception as refresh_error:print(f"Startup token refresh failed for environment credentials: {refresh_error}. Credentials may be stale.")# Continue with existing credentials - they might still workelse:print("No refresh token available in environment credentials - using as-is.")return credentialsexcept Exception as e:print(f"Could not load credentials from GOOGLE_APPLICATION_CREDENTIALS: {e}")47 unmodified linescredentials._expiry = expiry_utcreturn credentials# Always refresh tokens at startup when loading from file to avoid issuesif credentials.refresh_token:print("Refreshing tokens at startup for reliability...")try:credentials.refresh(GoogleAuthRequest())save_credentials(credentials)print("Startup token refresh successful.")except Exception as refresh_error:print(f"Startup token refresh failed: {refresh_error}. Credentials may be stale.")# Continue with existing credentials - they might still workelse:print("No refresh token available - using cached credentials as-is.")return credentialsexcept Exception as e:print(f"Could not load cached credentials: {e}. Starting new login.")356 unmodified linesif 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'.encode('utf-8')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'.encode('utf-8')returnelse:print("[STREAM] No refresh token available.")yield f'data: {{"error": {{"message": "Authentication failed. Please restart the proxy to re-authenticate."}}}}\n\n'.encode('utf-8')returnwith resp:23 unmodified linesresponse_chunk = obj["response"]# Output in standard Gemini streaming formatresponse_json = json.dumps(response_chunk, separators=(',', ':'))# Encode back to UTF-8 bytes to match exactly what real Gemini API sendsresponse_line = f"data: {response_json}\n\n"yield response_line.encode('utf-8')except json.JSONDecodeError:# Skip invalid JSONcontinue1 unmodified lineexcept 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'.encode('utf-8')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'.encode('utf-8')# Create the streaming response with headers matching real Gemini APIresponse_headers = {
gemini_proxy.py+35-6