Skip to content
Blog

Integrating Google Drive and Workspace APIs as ADK Tools

A step-by-step tutorial on connecting Google Drive, Docs, and Sheets to Google ADK agents using the Google Workspace APIs and official Python client libraries.

Published on • November 29, 2026

AI Assistant

Modern productivity agents must do more than chat—they need to read quarterly memos from Google Docs, summarize customer feedback from Google Sheets, and organize meeting assets in Google Drive folders.

Google Agent Development Kit (ADK) paired with Gemini 3.8 makes integrating Google Workspace straightforward. In this tutorial, we will construct an enterprise-ready ADK toolset that interfaces with the Google Drive and Google Docs APIs using service account delegation and user credentials.


1. Authentication Strategies: Service Account vs User OAuth

When integrating Google Workspace APIs into ADK tools, you have two primary authentication models:

DimensionService Account (Domain-Wide Delegation)User-Initiated OAuth 2.0
Primary Use CaseInternal enterprise bots acting on behalf of an organization or automated pipeline.Multi-tenant consumer or SaaS applications acting strictly on behalf of the logged-in user.
Permission ScopeCan impersonate any user in the Google Workspace domain if granted delegation.Strictly scoped to permissions granted by the specific user during consent.
Token HandlingGenerated server-side using service account private keys (credentials.json).Bearer tokens stored in ADK session.state or secure Redis token cache.

In this guide, we use Google’s official google-api-python-client with a service account or user credentials to authenticate tool calls.


2. Setting Up Dependencies and Client Builders

Install the required Google client libraries:

pip install google-api-python-client google-auth google-auth-httplib2 google-auth-oauthlib google-adk

Create a reusable client builder module workspace_client.py:

from typing import Optional
from google.oauth2 import service_account
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build, Resource

SCOPES = [
    "https://www.googleapis.com/auth/drive.readonly",
    "https://www.googleapis.com/auth/documents.readonly",
    "https://www.googleapis.com/auth/spreadsheets.readonly",
]

def get_workspace_services(
    service_account_file: Optional[str] = "service_account.json",
    user_access_token: Optional[str] = None
) -> tuple[Resource, Resource, Resource]:
    """Builds and returns Google Drive, Docs, and Sheets service resources."""
    if user_access_token:
        creds = Credentials(token=user_access_token)
    elif service_account_file:
        creds = service_account.Credentials.from_service_account_file(
            service_account_file,
            scopes=SCOPES
        )
    else:
        raise ValueError("Must provide either a service account file or an access token.")

    drive_service = build("drive", "v3", credentials=creds, cache_discovery=False)
    docs_service = build("docs", "v1", credentials=creds, cache_discovery=False)
    sheets_service = build("sheets", "v4", credentials=creds, cache_discovery=False)

    return drive_service, docs_service, sheets_service

3. Defining the ADK Workspace Tools

Now, let’s create the tool functions. Notice how we parse and extract clean plaintext from Google Docs structures rather than feeding raw JSON formatting trees into the LLM context.

from typing import Dict, Any, List
from pydantic import BaseModel, Field
from google.adk.agents import Agent
from google.adk.agents.invocation_context import InvocationContext

class SearchDriveFilesInput(BaseModel):
    query: str = Field(
        description="Search term or file name to locate in Google Drive, e.g., 'Q3 Roadmap'"
    )
    max_results: int = Field(default=5, ge=1, le=20)

def search_drive_files(input_data: SearchDriveFilesInput) -> Dict[str, Any]:
    """Searches for files in Google Drive by title or full-text query."""
    drive_service, _, _ = get_workspace_services()

    # Safe escaping for Drive queries
    escaped = input_data.query.replace("'", "\\'")
    q = f"name contains '{escaped}' and trashed = false"

    results = drive_service.files().list(
        q=q,
        pageSize=input_data.max_results,
        fields="files(id, name, mimeType, modifiedTime, webViewLink)",
    ).execute()

    files = results.get("files", [])
    return {
        "status": "success",
        "matches_found": len(files),
        "files": files,
    }

class ReadGoogleDocInput(BaseModel):
    document_id: str = Field(
        description="The Google Docs unique file identifier extracted from search results."
    )

def read_google_document(input_data: ReadGoogleDocInput) -> Dict[str, Any]:
    """Reads a Google Doc and extracts its plain text content."""
    _, docs_service, _ = get_workspace_services()

    try:
        doc = docs_service.documents().get(documentId=input_data.document_id).execute()
        title = doc.get("title", "Untitled")

        # Extract textual content from document structural elements
        body_elements = doc.get("body", {}).get("content", [])
        text_lines: List[str] = []

        for element in body_elements:
            paragraph = element.get("paragraph")
            if paragraph:
                for part in paragraph.get("elements", []):
                    text_run = part.get("textRun")
                    if text_run and "content" in text_run:
                        text_lines.append(text_run["content"])

        full_text = "".join(text_lines).strip()

        # Truncate content if it exceeds token budget
        max_chars = 12000
        truncated = len(full_text) > max_chars
        content_preview = full_text[:max_chars] if truncated else full_text

        return {
            "status": "success",
            "document_id": input_data.document_id,
            "title": title,
            "content": content_preview,
            "is_truncated": truncated,
        }

    except Exception as exc:
        return {
            "status": "error",
            "message": f"Failed to retrieve document: {str(exc)}",
        }

4. Assembling the Workspace Assistant Agent

We now supply these tools to an ADK Agent equipped with Gemini 3.8 Flash:

workspace_agent = Agent(
    name="workspace_navigator",
    model="gemini-3.8-flash",
    instruction="""
    You are an intelligent Google Workspace executive assistant.
    Your duties:
    1. Help users discover corporate documents across Google Drive using `search_drive_files`.
    2. Read and extract content from specific Google Docs using `read_google_document`.
    3. Synthesize summaries, bullet points, and action items clearly.
    Always cite the document title and include its webViewLink when presenting answers.
    """,
    tools=[search_drive_files, read_google_document],
)

Running an Execution Turn

import asyncio
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService

async def main():
    session_service = InMemorySessionService()
    runner = Runner(agent=workspace_agent, session_service=session_service)
    session = await session_service.get_or_create("user_workspace_session")

    prompt = "Find our 2026 Product Strategy document and give me the top 3 priorities."
    print(f"Prompt: {prompt}\n")

    async for event in runner.run_async(session=session, message=prompt):
        if event.content:
            for part in event.content.parts:
                if hasattr(part, "text") and part.text:
                    print(part.text, end="")
    print()

if __name__ == "__main__":
    asyncio.run(main())

5. Production Considerations

  1. Token Budget Protection: Google Docs can contain hundreds of pages. Always slice text chunks or implement a semantic chunker before returning content to the agent context.
  2. Rate Limits (Google Quotas): Workspace APIs enforce strict per-user quotas (e.g., 300 requests per minute). Implement exponential backoff or caching inside your ADK tools.
  3. MIME Type Validation: Ensure the agent does not attempt to pass image or binary file IDs to the Docs API; check mimeType == 'application/vnd.google-apps.document' in your tool logic.

Takeaway: Integrating Google Workspace into ADK agents empowers teams with hands-free document discovery and synthesis while preserving strict enterprise permission boundaries.

Sources