Skip to content
Blog

Ephemeral Document Loading: Ingesting 500-Page PDFs Direct into Gemini Context in Google ADK

How to leverage Gemini 3.8 large context windows to load 500-page enterprise PDFs ephemerally into Google ADK without chunking or vector database infrastructure.

Published on • December 5, 2026

AI Assistant

For years, processing large documents required complex RAG pipelines: parsing PDFs, chunking paragraphs, generating vector embeddings, indexing in Milvus or Pinecone, and writing retrieval queries. While effective for massive static corporate knowledge bases, traditional RAG often fails on holistic document comprehension: cross-table reconciliation, global summaries, and complex multi-page financial audits.

With Gemini 3.8’s million-token context window and native multimodal document processing via the Google GenAI Files API, developers can now perform Ephemeral Document Loading (EDL). In this pattern, an entire 500-page PDF is loaded directly into the model’s active context for the duration of a task and discarded afterward, eliminating chunking loss entirely.


RAG Chunking vs. Native Long-Context Ingestion

Traditional RAG Pipeline:
PDF (500 pages) ──► OCR / Parse ──► Chunking (500 tokens) ──► Embedding ──► Vector DB
                                                                               │
Query ─────────────────────────────────────────────────────────────► Top-K Chunks (Loss of context)

Ephemeral Long-Context Ingestion (Gemini 3.8 + ADK):
PDF (500 pages) ──► Google GenAI Files API ──► Native Gemini Context (Full document fidelity)
                                                      │
Query / Multi-Turn Agent Turn ────────────────────────┴─► Cross-page reasoning, table joins, exact cites

Advantages of Ephemeral Ingestion

  1. Preserves Visual and Spatial Structure: Gemini parses native PDFs including diagrams, multi-column tables, charts, and header hierarchies without OCR degradation.
  2. Zero Ingestion Latency: No embedding computation or vector indexing overhead.
  3. No Chunk Boundary Splitting: Prevents critical numbers or clauses from being split across chunk borders.

Implementing Ephemeral PDF Loading in ADK

Using the google-genai SDK, we upload the PDF to the Files API and pass its reference part directly to an ADK LlmAgent.

import asyncio
from pathlib import Path
from google.genai import Client
from google.genai.types import Part
from google_adk.agents import LlmAgent
from google_adk.runners import Runner
from google_adk.sessions import InMemorySessionService

class EphemeralDocumentManager:
    def __init__(self):
        self.client = Client()

    async def upload_document(self, file_path: str):
        """Uploads PDF to GenAI File Service (retained for 48 hours)."""
        path = Path(file_path)
        print(f"Uploading {path.name} to Gemini Files API...")
        
        file_ref = await self.client.files.upload(
            file=str(path),
            config={"display_name": path.name}
        )
        print(f"Uploaded successfully. URI: {file_ref.uri}")
        return file_ref

    async def cleanup_document(self, file_name: str):
        """Immediately deletes the document to maintain ephemeral hygiene."""
        try:
            await self.client.files.delete(name=file_name)
            print(f"Deleted ephemeral file: {file_name}")
        except Exception as e:
            print(f"Warning: Cleanup failed for {file_name}: {e}")

async def main():
    doc_mgr = EphemeralDocumentManager()
    
    # 1. Upload 500-page enterprise PDF (e.g., Annual Financial 10-K Report)
    uploaded_file = await doc_mgr.upload_document("annual_report_500pages.pdf")

    try:
        # 2. Configure ADK Agent with file part injected into session context
        agent = LlmAgent(
            name="AuditorAgent",
            model="gemini-3.8-flash",
            system_instruction=(
                "You are an enterprise financial auditor. You have access to the full annual report. "
                "Quote exact page numbers, table rows, and fiscal notes for every verification."
            )
        )

        runner = Runner(agent=agent, session_service=InMemorySessionService())
        session = await runner.session_service.create_session("audit_session_01")

        # 3. Query the document holistically
        query = "Reconcile the differences between Note 14 (Contingent Liabilities) and the Cash Flow table on page 412."
        
        response = await runner.run_async(
            session_id=session.id,
            user_message=[uploaded_file, query]
        )

        print("\n=== Agent Audit Response ===")
        print(response.text)

    finally:
        # 4. Ephemeral hygiene: Clean up file reference
        await doc_mgr.cleanup_document(uploaded_file.name)

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

Combining Ephemeral Loading with Gemini Context Caching

If an agent must answer dozens of questions against the same 500-page PDF (approx. 250,000 to 400,000 tokens), re-uploading and re-processing the document on every query becomes expensive.

By declaring an ADK ContextCacheConfig, Gemini creates an explicit server-side cache of the document. Subsequent queries against the cached document benefit from a 75% discount on input token costs and near-instant TTFT.

from google_adk.context import ContextCacheConfig
from datetime import timedelta

# Cache the 500-page document for 1 hour
cache_config = ContextCacheConfig(
    ttl=timedelta(minutes=60),
    cache_contents=[uploaded_file]
)

When to Use Ephemeral Documents vs. Vector RAG

CriteriaEphemeral Loading (Long Context)Vector RAG
Document Volume1 to 10 large documents (< 1M tokens total)Hundreds of thousands of documents
Query TypeHolistic synthesis, comparative tables, cross-page reasoningSpecific keyword/fact retrieval
Setup OverheadZero (just upload file)High (chunkers, embedders, vector DB)
Visual ElementsNative chart & table readingRequires complex OCR/multimodal embedding
Cost ProfilePay per token in window (mitigated by caching)Pay for search query + small top-K window

Summary

Ephemeral Document Loading in Google ADK allows developers to bypass the brittleness of PDF parsers and chunking heuristics for document analysis tasks. With Gemini 3.8 and automatic context caching, 500-page documents can be ingested with full multimodal fidelity in seconds.