From b7ba7e8a7be438538dd86773f296f5ac194b8685 Mon Sep 17 00:00:00 2001 From: Mark Date: Sat, 17 Jun 2023 18:44:17 +0200 Subject: [PATCH] Allow GoogleDrive to authenticate via application default credentials on Cloud Run/GCE etc without service key (#6035) @eyurtsev The existing GoogleDrive implementation always needs a service account to be available at the credentials location. When running on GCP services such as Cloud Run, a service account already exists in the metadata of the service, so no physical key is necessary. This change adds a check to see if it is running in such an environment, and uses that authentication instead. --------- Co-authored-by: Harrison Chase --- langchain/document_loaders/googledrive.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/langchain/document_loaders/googledrive.py b/langchain/document_loaders/googledrive.py index dc00eb4aaf..c28bf705bc 100644 --- a/langchain/document_loaders/googledrive.py +++ b/langchain/document_loaders/googledrive.py @@ -9,6 +9,7 @@ # 4. For service accounts visit # https://cloud.google.com/iam/docs/service-accounts-create +import os from pathlib import Path from typing import Any, Dict, List, Optional, Sequence, Union @@ -91,6 +92,7 @@ class GoogleDriveLoader(BaseLoader, BaseModel): """Load credentials.""" # Adapted from https://developers.google.com/drive/api/v3/quickstart/python try: + from google.auth import default from google.auth.transport.requests import Request from google.oauth2 import service_account from google.oauth2.credentials import Credentials @@ -116,6 +118,12 @@ class GoogleDriveLoader(BaseLoader, BaseModel): if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) + elif "GOOGLE_APPLICATION_CREDENTIALS" not in os.environ: + creds, project = default() + creds = creds.with_scopes(SCOPES) + # no need to write to file + if creds: + return creds else: flow = InstalledAppFlow.from_client_secrets_file( str(self.credentials_path), SCOPES