Tickd.ai
← The Tickd Guide

Tutorials & Guides

How to Build a Local PDF Context Injector with Gemini 1.5 Pro to Bypass Vector Database RAG

Vector databases and complex RAG pipelines are overkill for medium-sized document sets. Here is how to build a local Python tool that uses Gemini's massive context window to query your PDFs directly.

Updated 11/2/2026

Retrieval-Augmented Generation (RAG) is the default answer for querying custom documents. We are told we must chunk our text, choose an embedding model, spin up a vector database, write a similarity search algorithm, and handle chunk overlap.

For enterprise datasets with millions of documents, that setup is necessary. But for your collection of API specs, local product manuals, or project files? It is massive over-engineering.

Thanks to the massive context window of Google's Gemini 1.5 Pro (which comfortably swallows up to 2 million tokens), we can bypass the entire RAG pipeline. Instead of slicing your files into confusing snippets, you can feed entire PDF documents directly into the prompt context. This approach keeps the document's structure, layout, and cross-references completely intact, which leads to far more accurate answers.

Here is how to build a local command-line Python tool that extracts text from a folder of PDFs and injects them directly into /platforms/gemini to query your documents without a single vector database in sight.

Why Skip the Vector Database?

Traditional chunk-based RAG has a massive flaw: it loses the overall context. If your PDF has a table on page 3 that explains a diagram on page 12, a vector search will struggle to connect them because they sit in different text chunks.

By injecting the entire document set directly into the model’s context window, Gemini reads the material exactly like a human would. It can understand document-wide themes, follow long-form narratives, and reference distant pages simultaneously. It makes your development pipeline far simpler and keeps your local workflow ticking along nicely without the overhead of managing a database container.

Which AI should I use for this?

Tickd is independent and not affiliated with any AI company.

Step 1: Set Up Your Project and Dependencies

First, create a clean directory for your project and set up a virtual environment. We will use PyMuPDF (also known as fitz) for fast, clean text extraction from our PDFs, and the official Google GenAI SDK.

`bash mkdir local-pdf-injector cd local-pdf-injector python3 -m venv venv source venv/bin/activate pip install google-genai pymupdf `

Next, grab an API key from Google AI Studio and export it to your environment variables:

`bash export GEMINI_API_KEY="your_api_key_here" `

Step 2: Write the PDF Text Extractor

Before sending anything to Gemini, we need to extract the text from our local PDFs. We will write a utility function that loops through a directory, reads each PDF, and outputs a single structured text payload where each page is clearly demarcated. This structure helps Gemini understand exactly where information is located.

Create a file named injector.py and add the following code:

`python import os import glob import fitz # PyMuPDF from google import genai from google.genai import types

def extract_text_from_pdfs(pdf_dir: str) -> str: """ Reads all PDFs in a directory and compiles their text with page markers. """ pdf_files = glob.glob(os.path.join(pdf_dir, "*.pdf")) if not pdf_files: print(f"No PDFs found in {pdf_dir}") return "" compiled_context = [] for pdf_path in pdf_files: filename = os.path.basename(pdf_path) print(f"Processing: {filename}...") try: doc = fitz.open(pdf_path) compiled_context.append(f"=== START OF DOCUMENT: {filename} ===") for page_num in range(len(doc)): page = doc.load_page(page_num) text = page.get_text("text") compiled_context.append(f"--- Page {page_num + 1} of {filename} ---") compiled_context.append(text) compiled_context.append(f"=== END OF DOCUMENT: {filename} ===\n") except Exception as e: print(f"Failed to process {filename}: {e}") return "\n".join(compiled_context) `

Step 3: Set Up the Query Loop

Now, we will build the interactive command-line interface. This script compiles the PDF data once, starts a system instruction block telling Gemini how to act, and enters an interactive query loop.

`python def query_loop(document_context: str): """ Starts an interactive prompt loop using the compiled PDF context. """ # Initialize the client using the environment variable client = genai.Client() # System instructions guide how Gemini behaves when reading the documents system_instruction = ( "You are an expert research assistant. You have been provided with the full text of " "several PDF documents. Your task is to answer queries using ONLY the provided text. " "When answering, always cite the specific document filename and page numbers where the " "information was found. If the answer cannot be found in the text, clearly state that." )

We use gemini-1.5-pro for its massive context capacity and reasoning skills model_name = "gemini-1.5-pro" print("\nInitialization complete. Ask your documents anything!") print("Type 'exit' or 'quit' to close the program.\n") while True: user_query = input("\nQuery > ").strip() if not user_query: continue if user_query.lower() in ["exit", "quit"]: print("Goodbye!") break # We pack the document context and the user's query into the contents parameter prompt_payload = [ f"Here is the reference material:\n\n{document_context}", f"Based on the reference material above, please answer this question: {user_query}" ] print("Thinking...") try: response = client.models.generate_content( model=model_name, contents=prompt_payload, config=types.GenerateContentConfig( system_instruction=system_instruction, temperature=0.2, # Low temperature keeps answers accurate to the text ) ) print("\nAnswer:") print(response.text) except Exception as e: print(f"\nError during generation: {e}") print("For troubleshooting tips, check out our guide at /platforms/gemini/articles")

if __name__ == "__main__": # Create a local 'docs' directory if it doesn't exist docs_directory = "./docs" if not os.path.exists(docs_directory): os.makedirs(docs_directory) print(f"Created '{docs_directory}' directory. Drop your PDFs inside and run the script again.") else: print("Compiling document context...") all_docs_text = extract_text_from_pdfs(docs_directory) if all_docs_text.strip(): query_loop(all_docs_text) else: print("Please add some PDFs to the './docs' directory and try again.") `

Step 4: Run and Test the Tool

To use the tool, drop a couple of complex manuals or documents into the newly created ./docs directory. Run the script:

`bash python injector.py `

Ask a question that requires connecting information from two separate pages or files. You will notice that the model responds with highly contextual, citation-rich answers without any of the retrieval errors or broken chunk issues common to standard RAG setups.

Limitations and When to Choose Vector RAG

While this method is incredibly fast to build and highly accurate, it is not a silver bullet. You should be aware of two trade-offs:

  1. API Cost: Because you send your entire document set with every single query, your token usage will be high. If your folder contains 500,000 tokens of text, a conversation with 5 queries will use 2.5 million input tokens. If you are query-heavy, this gets expensive quickly.
  2. Latency: While Gemini is impressively fast, processing millions of tokens still takes a few seconds before the response starts generating.

For large-scale, cost-sensitive production apps with millions of documents, you should stick to traditional RAG architectures. But for local development, internal documentation search, and fast prototyping, injecting the raw text into Gemini's massive context window wins every single time.

geminipythontutorialsragai-agents

Keep going

Build something with the prompt generator, decode the jargon in the glossary, or compare the tools on our platform deep-dives.