Zero Labs
Industry News / AI

Building a production-ready Agentic RAG system on GCP: (Vertex AI, ADK, Terraform)

Source · Towards AI By allglenn

From the publisher’s feed, collected in the ZeroLabs newsroom.

Learn how to build a production-grade Retrieval-Augmented Generation (RAG) system on Google Cloud Platform using Vertex AI, Cloud Run, Eventarc, and Gemini. Includes architecture breakdowns, step-by-step deployment, comparisons with AWS, Azure, and LangChain alternatives, and real-world use cases.Code provided at the endyour documents deserve better than a keyword searchLet me paint a picture you might recognize. Your company has thousands of PDFs , contracts, technical specs, HR handbooks, compliance manuals scattered across shared drives and inboxes. Someone joins the team and spends their first week reading documentation. A lawyer needs to review 200 contracts for a specific clause. A customer support rep searches for the right product spec for the fifteenth time today.Now imagine asking a plain question , “What’s the maximum liability clause in our enterprise contracts?” and getting a precise, cited answer in under two seconds, pulled from the right document, grounded in fact, and impossible to hallucinate because it’s extracted directly from your own corpus.That’s Retrieval-Augmented Generation (RAG) in production. Not a demo. Not a Jupyter notebook. A real, scalable, event-driven pipeline that processes documents the moment they land in cloud storage, indexes them into a managed vector database, and serves grounded answers through a Gemini-powered agent , all on Google Cloud Platform.This article is your complete guide to building exactly that. We’ll walk through the architecture of the project, dissect every component, compare it against alternatives like AWS Bedrock, Azure AI Search, and LangChain, and give you a step-by-step deployment walkthrough you can follow today. By the end, you’ll understand not just the how, but the why behind every design decision.Table of contentsWhat is RAG and why does it matter now?System architecture overviewThe ingestion pipeline: from file upload to vector indexThe query pipeline: from question to grounded answerInfrastructure as code with TerraformStep-by-step: deploying Super_RAG V1 from scratchReal-world use casesCompetitor comparison: GCP vs AWS vs Azure vs DIYPerformance, cost, and optimization tipsSecurity considerationsConclusion and next stepsWhat is RAG and why does it matter now?Before jumping into the architecture, let’s align on what RAG actually is and why it’s become the dominant pattern for enterprise AI this yearLarge Language Models like Gemini, GPT-5, and Claude are remarkable at reasoning, summarization, and language generation. But they have a fundamental limitation: their knowledge is frozen at training time. Ask GPT-5 about your company’s specific contract templates, your internal runbook, or a document uploaded last Tuesday , and you’ll get either a hallucination or a polite refusal.Fine-tuning solves part of this, but it’s expensive, slow, and doesn’t update in real time. RAG is the elegant alternative.RagSystem architecture overviewthe project is an event-driven, fully managed RAG system on GCP. Here’s the high-level picture:Rag architectureThe architecture separates cleanly into two pipelines:The ingestion pipeline handles the “write” side of the system. A document upload to a GCS bucket fires an Eventarc trigger, which invokes a Cloud Run service (rag-ingestor). This service determines which RAG corpus the document belongs to (based on folder name), then calls the Vertex AI RAG API to parse, chunk, and embed the document into a managed vector index.The query pipeline handles the “read” side. An end user sends a natural language question to the adk-agent Cloud Run service. The agent retrieves the top-K most relevant document chunks from Vertex AI, constructs a grounded prompt, and sends it to Gemini 2.5 flash, which generates a cited, factual answer.This decoupled architecture means ingestion and querying scale independently, documents are indexed in near-real-time, and no single failure point brings down the whole system.The ingestion pipeline: from file upload to vector indexGCS bucket with folder-based domain routingThe entry point is dead simple: a GCS bucket with three domain-specific folders.gs://{project-id}-rag-documents/├── legal/ → maps to legal-corpus├── technical/ → maps to technical-corpus└── training/ → maps to training-corpusThis folder structure encodes business logic without a single line of application code. The rag-ingestor service reads the folder prefix from the object path and maps it to the appropriate Vertex AI corpus. New domains? Add a folder. Extend the corpus map in the service. Done.Eventarc: the nervous system of the pipelineWhen a file lands in the bucket, GCS emits an Object Finalize event. Eventarc : GCP's eventing fabric , captures this and pushes a CloudEvent payload to the rag-ingestor Cloud Run endpoint.rag flowThe beauty of this pattern is that the rag-ingestor is completely stateless. It receives an event, does one job, and exits. There's no long-running process to manage, no polling loop, no cron job. Eventarc handles all the fan-out, retry logic, and dead-letter queue behavior.Inside the rag-ingestor serviceThe Cloud Run service is a lean Python application. Here’s the key logic at a high level:# corpus_mapper.pyCORPUS_MAP = { "legal": os.getenv("LEGAL_CORPUS_NAME"), "technical": os.getenv("TECHNICAL_CORPUS_NAME"), "training": os.getenv("TRAINING_CORPUS_NAME"),}def get_corpus_for_path(object_path: str) -> str: folder = object_path.split("/")[0] corpus = CORPUS_MAP.get(folder) if not corpus: raise ValueError(f"Unknown folder: {folder}") return corpus# vertex_client.pyfrom google.cloud.aiplatform import ragdef ingest_document(corpus_name: str, gcs_uri: str): rag.import_files( corpus_name=corpus_name, paths=[rag.GcsSource(uris=[gcs_uri])], chunk_size=1000, # tokens per chunk chunk_overlap=200, # overlap for context continuity )The chunk_size and chunk_overlap parameters are critical tuning knobs. Larger chunks preserve more context per passage but reduce precision in retrieval. Smaller chunks improve precision but may break semantic continuity. The default configuration of 1000 tokens with 200 overlap is a solid starting point for most document types.Vertex AI RAG Engine: what happens under the hoodWhen import_files() is called, Vertex AI handles a four-stage pipeline entirely managed:vertex ai chunk creationThe embedding model , text-embedding-004 ,produces 768-dimensional dense vectors that capture semantic meaning. Cosine similarity between vectors determines relevance. Two chunks discussing "indemnification clauses" and "liability protection" will be close in vector space even if they share no exact words. That's the power of semantic search over keyword matching.The query pipeline: from question to grounded answerThe adk-agent: orchestrator of the query flowThe adk-agent Cloud Run service is the user-facing brain of the system. It accepts REST requests, orchestrates retrieval, and generates grounded responses.Rag queryA typical query request looks like this:curl -X POST ${ADK_AGENT_URL}/query \ -H "Authorization: Bearer $(gcloud auth print-identity-token)" \ -H "Content-Type: application/json" \ -d '{ "query": "What are the key indemnification clauses in our enterprise contracts?", "corpus_filter": ["legal"], "include_citations": true }'The corpus_filter parameter is a practical power feature. A lawyer only needs to search legal corpus. A developer asking about API specs hits technical. A manager checking onboarding procedures queries training. Users get faster, more relevant results because the vector search space is scoped correctly.Retrieval configuration and relevance tuningThe RAG retriever is configured with similarity_top_k = 5, meaning it retrieves the 5 most semantically similar chunks for any given query. In practice, this means:The top chunks are formatted as context blocks with source attributionChunks from multiple documents can be combined in a single responseGemini receives a structured prompt like: [Source: contract_2024.pdf, page 3]\nThis explicit source attribution is what enables citations in the final answera critical requirement for legal and compliance use cases.Gemini configuration for factual responsesThe Gemini model is configured with a low temperature (0.2) and high top_p (0.95). This creates a model behavior that strongly prefers factual, retrieved content over creative generation —,exactly what you want for a document Q&A system.generation_config = GenerationConfig( temperature=0.2, # low = more deterministic, factual top_p=0.95, # high = considers broad probability mass max_output_tokens=2048,)Infrastructure as code with TerraformOne of the hallmarks of a production-ready system is that the infrastructure itself is version-controlled, repeatable, and auditable. this project uses Terraform to manage every GCP resource.Infrastructure as codeThe modular structure means each component can be deployed, updated, or destroyed independently. IAM roles follow the principle of least privilege: rag-ingestor gets roles/aiplatform.user and roles/storage.objectViewer, nothing more. The adk-agent gets roles/aiplatform.user. No over-permissioned service accounts that could be exploited if compromised.The Terraform state is stored remotely in a dedicated GCS bucket, enabling team collaboration and preventing state drift.Step-by-step: deploying The proect from scratchLet’s walk through a real deployment scenario: a legal team at a mid-size law firm wants to build an internal document assistant for their contract library.Step 1: prerequisitesMake sure you have the following installed and configured:gcloud CLI authenticated to your GCP projectTerraform >= 1.5.0Docker (for local development)Python 3.11+gcloud auth logingcloud config set project YOUR_PROJECT_IDStep 2: enable required APIsexport GCP_PROJECT_ID="law-firm-rag-prod"export GCP_REGION="us-central1"chmod +x scripts/setup-gcp-project.sh./scripts/setup-gcp-project.shThis script enables Cloud Run, Eventarc, Vertex AI, Artifact Registry, Cloud Storage, and Cloud Build APIs in one shot. It also configures the GCS service account to publish to Pub/Sub a prerequisite for Eventarc triggers.Step 3: create Terraform backendchmod +x scripts/create-tf-backend.sh./scripts/create-tf-backend.shThis creates a versioned GCS bucket for Terraform state. With versioning enabled, you can roll back to any previous infrastructure state, critical for production environments.Step 4: configure Terraform variablescd terraformcp terraform.tfvars.example terraform.tfvarsEdit terraform.tfvars with your project-specific values:project_id = "law-firm-rag-prod"region = "us-central1"environment = "production"# Cloud Run configurationrag_ingestor_min_instances = 0 # scales to zero when idleadk_agent_min_instances = 1 # always-on for low latency# Document retentionstorage_lifecycle_days = 90 # move to Nearline after 90 daysStep 5: deploy infrastructureterraform initterraform plan # always review before applyingterraform applyThis creates all GCP resources: the GCS bucket with domain folders, Cloud Run service stubs, Eventarc trigger, IAM bindings, and the Vertex AI corpus configurations.Step 6: create Vertex AI RAG corporaBefore ingesting documents, the RAG corpora must exist. Run this once:from google.cloud.aiplatform import ragfor domain, description in [ ("legal", "Legal contracts, NDAs, and compliance documents"), ("technical", "Technical specifications and architecture docs"), ("training", "Employee training and onboarding materials"),]: corpus = rag.create_corpus( display_name=f"{domain.capitalize()} Documents Corpus", description=description ) print(f"Created {domain} corpus: {corpus.name}")Copy the corpus resource names into your terraform.tfvars and re-run terraform apply to propagate them as Cloud Run environment variables.Step 7: build and deploy services# Deploy the ingestion servicegcloud builds submit --config=cloudbuild/cloudbuild-ingestor.yaml# Deploy the query agentgcloud builds submit --config=cloudbuild/cloudbuild-agent.yamlEach Cloud Build configuration runs tests, builds a Docker image, pushes it to Artifact Registry, deploys to Cloud Run, and runs a health check. This CI/CD-native deployment means every service update is traceable back to a git commit.Step 8: upload your first document and test# Upload a contract to the legal corpusgsutil cp sample_contract.pdf gs://${GCP_PROJECT_ID}-rag-documents/legal/# Wait ~30 seconds for ingestion# Query the agentADK_URL=$(gcloud run services describe adk-agent \ --region ${GCP_REGION} --format 'value(status.url)')curl -X POST ${ADK_URL}/query \ -H "Authorization: Bearer $(gcloud auth print-identity-token)" \ -H "Content-Type: application/json" \ -d '{ "query": "What is the payment term in the contract?", "corpus_filter": ["legal"], "include_citations": true }'Expected response:{ "answer": "The contract specifies net-30 payment terms, with a 1.5% monthly late fee applied to overdue balances after the grace period. This is defined in Section 4.2 of the agreement.", "citations": [ { "source": "sample_contract.pdf", "page": 3, "chunk_id": "chunk_042", "relevance_score": 0.94 } ], "processing_time_ms": 1240}The entire flow , from question to cited answer — completes in under 1.5 seconds. That’s the baseline for a warm Cloud Run instance against a small corpus. With a larger document set and cold starts factored in, p95 latency typically lands around 3–5 seconds.Step 9: monitor and validate# Check ingestion logsgcloud run services logs read rag-ingestor --region ${GCP_REGION} --limit 50# Check agent logsgcloud run services logs read adk-agent --region ${GCP_REGION} --limit 50# Verify Eventarc trigger is activegcloud eventarc triggers describe gcs-rag-ingestor-trigger \ --location ${GCP_REGION}Real-world use casesLegal document intelligenceA law firm ingests all client contracts into the legal corpus. Associates use the query interface to instantly find specific clauses, compare indemnification language across agreements, or flag unusual terms. What previously took hours of manual review takes seconds , with citations the lawyer can verify immediately.Technical knowledge baseA software company uploads architecture decision records, API specs, and runbooks to the technical corpus. Engineers ask natural language questions during incidents: "What's the retry logic for the payments service?" The agent returns the exact runbook section, cited by filename and chunk.Employee onboarding assistantHR uploads training materials, benefits guides, and policy documents to the training corpus. New employees interact with a chatbot backed by the agent. Questions like "How many PTO days do I get in year two?" return accurate, sourced answers without HR fielding the same questions repeatedly.Competitor comparison: GCP vs AWS vs Azure vs DIYThis is where things get interesting. the project is built entirely on GCP services, but it’s worth understanding what you’re getting ,and what you’re giving up ,compared to the alternatives.RAG Platform Comparison: Ease vs ControlGCP Vertex AI RAG EngineStrengths:Fully managed vector index — no infrastructure to provision or maintainNative integration with Gemini, the most capable multimodal model familyEventarc + Cloud Run creates a truly serverless, event-driven pipelineBuilt-in chunking, parsing, and embedding — no glue codeTerraform modules cover the entire infrastructure stackData residency: your documents never leave GCPWeaknesses:Lock-in: the Vertex AI RAG API is proprietary. Migrating to another platform means rebuilding the ingestion and retrieval layersCorpus count limits per project (check current Vertex AI quotas)Less flexibility for custom embedding models compared to DIY approachesVertex AI RAG is a newer product; some edge cases in the API are still roughBest for: Organizations already on GCP, teams that want operational simplicity, regulated industries that need data to stay within a specific cloud environment.AWS Bedrock Knowledge BasesAmazon’s equivalent is Bedrock Knowledge Bases, which integrates with S3 for document storage and OpenSearch Serverless for the vector backend.Strengths:Deep AWS ecosystem integration (Lambda triggers, S3 events, CloudWatch)Choice of embedding models: Titan Embeddings, Cohere EmbedKnowledge Bases for Amazon Bedrock now supports metadata filteringStrong enterprise compliance certifications (FedRAMP, HIPAA)Weaknesses:The managed vector backend (OpenSearch Serverless) is more expensive than Vertex AI’s managed index at scaleOpenSearch Serverless has a minimum cost floor (~$700/month for two OCUs) that makes it cost-prohibitive for small deploymentsThe S3 → Lambda → Bedrock pipeline requires more wiring than GCP’s Eventarc approachBedrock’s RAG configuration is less flexible for custom chunking strategiesCost comparison: For a small deployment (5,000 documents, 1,000 queries/day), AWS Bedrock + OpenSearch Serverless runs approximately $750–1,200/month. Super_RAG V1 on GCP runs approximately $165–470/month. That’s a meaningful difference for startups and mid-market companies.Best for: AWS-native organizations, teams heavily using Claude or Titan models, regulated US government workloads needing FedRAMP authorization.Azure AI Search + Azure OpenAIMicrosoft’s approach pairs Azure AI Search (formerly Cognitive Search) as the vector store with Azure OpenAI for the LLM layer.Strengths:Best-in-class hybrid search: combines BM25 keyword search with vector semantic searchSemantic ranking layer adds a second-pass re-ranker that meaningfully improves precisionAzure OpenAI gives access to GPT-4o, the strongest purely text model currently availableStrong enterprise identity integration (Azure Active Directory, Entra ID)Power Platform connectors for no-code integrationWeaknesses:The Azure ecosystem is complex. Getting AI Search, Azure OpenAI, Blob Storage, and Azure Functions working together correctly requires significant configurationAzure AI Search pricing scales with the number of search units; can get expensive at high query volumesAzure OpenAI is rate-limited; quota requests can take weeks to approveTerraform support for Azure AI Search is mature but the azure_search_service resource has historical bugs around semantic ranking tier changesUnique advantage: Azure’s hybrid retrieval (BM25 + vector) outperforms pure vector search for queries with specific entity names, dates, and identifiers. If your use case involves querying for specific contract numbers, employee IDs, or product SKUs, Azure’s approach may return more precise results than Vertex AI’s pure semantic search.Best for: Microsoft-native enterprises, organizations on M365, teams needing hybrid search for structured data alongside documents.DIY: LangChain / LlamaIndex + Pinecone / Weaviate / QdrantThe open-source RAG stack gives you maximum flexibility and zero vendor lock-in. A typical setup uses LangChain or LlamaIndex for orchestration, an open embedding model like bge-large-en or nomic-embed-text, and a self-hosted or managed vector database like Pinecone, Weaviate, or Qdrant.Strengths:Complete control over every component: embedding model, chunking strategy, retrieval algorithm, re-rankingNo vendor lock-in — swap any component independentlyCan run entirely on-premises for maximum data sovereigntyThe open-source ecosystem is moving incredibly fast; new retrieval techniques (HyDE, RAG-Fusion, RAPTOR) are available as soon as they’re publishedAdvanced techniques like hybrid BM25 + dense retrieval, cross-encoder re-ranking, and multi-hop reasoning are much easier to implementWeaknesses:Operational burden is significant. You’re responsible for scaling, monitoring, updating, and maintaining every servicePinecone’s managed service is expensive at scale; Weaviate and Qdrant self-hosted add DevOps overheadLangChain’s rapid development pace means breaking changes are frequentBuilding a production-grade ingestion pipeline with event triggers, error handling, dead-letter queues, and retry logic from scratch takes weeksWhen to choose DIY: If your team has strong ML engineering capacity, you need techniques beyond what managed platforms offer (multi-vector retrieval, custom re-rankers, late interaction models like ColBERT), or you’re in an air-gapped environment that can’t use cloud AI services.Performance, cost, and optimization tips {#cost}The current architecture is optimized for a starting monthly cost of $165–470. Here’s where that money goes and how to control it:Cloud Run costs are the most predictable. The rag-ingestor scales to zero when no documents are being ingested, meaning it costs nothing during idle periods. The adk-agent runs a minimum of one instance to avoid cold start latency on queries. With 1,000 queries/day at an average 1.5s processing time, Cloud Run costs are negligible — well under $50/month.Vertex AI embedding costs scale with the number of tokens embedded during ingestion. For a 10,000-page document corpus (roughly 5 million tokens), the one-time embedding cost is approximately $0.50. Re-indexing is only needed when documents change.Gemini generation costs are the primary variable. At $0.00025 per input token for Gemini 1.5 Flash (the cheaper alternative to Pro), 1,000 queries/day with an average 2,000-token prompt context costs roughly $15/month. Gemini 1.5 Pro at $0.00125/input token would be $75/month for the same load.Optimization levers:Switch to gemini-1.5-flash for most queries; escalate to gemini-1.5-pro only for complex multi-document reasoningReduce similarity_top_k from 5 to 3 for simpler factual queries — fewer input tokens, lower cost, same accuracyEnable GCS lifecycle rules to move older documents to Nearline storage after 90 days (included in the Terraform config)Set Cloud Run max_instances caps to prevent unexpected scaling costs during traffic spikesSecurity considerations {#security}Security in Super_RAG V1 is built on three principles: least privilege, defense in depth, and no plaintext secrets.Identity and access management is the first line of defense. The rag-ingestor service account has exactly two IAM roles: roles/aiplatform.user (to call Vertex AI) and roles/storage.objectViewer (to read documents). It cannot create resources, delete files, or access any other GCP service. The same minimalism applies to adk-agent. This means a compromised service can do almost nothing beyond its designed function.Network isolation is enforced at the Cloud Run level. The rag-ingestor is configured with ingress: internal, meaning it can only be reached by Eventarc — not the public internet. The adk-agent is configured as authenticated, meaning every request must carry a valid Google identity token. Raw internet access is impossible.Secret management follows GCP best practices: no sensitive values in environment variables or Docker images. Connection strings, API keys for any external services, and other secrets should live in Secret Manager and be accessed at runtime via the Secret Manager API. The provided .env.example file documents which values need this treatment.Uniform bucket-level access on GCS prevents per-object ACL overrides, ensuring that IAM policies are the single source of truth for bucket permissions.Conclusion and next stepsSuper_RAG V1 represents a production pattern, not a toy. It’s event-driven, serverless, infrastructure-as-code-managed, and built on enterprise-grade managed services that handle the hard parts — parsing, chunking, embedding, vector indexing — so your team can focus on the application layer.The system is opinionated in its GCP-native design, and that’s a feature, not a bug, for teams already on the platform. The Eventarc + Cloud Run + Vertex AI trio is a genuinely elegant combination: documents flow from storage to knowledge base without polling loops or cron jobs, and queries return grounded, cited answers in under 1.5 seconds.That said, the choice of platform matters. If your organization is AWS-native and needs FedRAMP authorization, Bedrock Knowledge Bases is the right call. If you need hybrid keyword + vector search for structured document queries, Azure AI Search’s semantic ranking tier is worth the extra complexity. And if you have an ML engineering team that wants to push the state of the art in retrieval techniques, the open-source LangChain + Qdrant stack gives you a ceiling that no managed service can match.Whatever platform you choose, the architecture principles here hold: separate ingestion from querying, use event-driven triggers over polling, scope retrieval to relevant corpora, and ground your LLM on cited context rather than hoping it remembers.Your next steps:Clone the Super_RAG V1 repository and run ./scripts/setup-gcp-project.sh on a dev projectUpload 5–10 documents from your domain and test retrieval qualityTune chunk_size and similarity_top_k for your specific document typesEvaluate whether Gemini 1.5 Flash is sufficient for your use cases before committing to Pro pricingSet up Cloud Build triggers for automatic deployment on every push to mainThe documents your organization has accumulated over years are a competitive asset. A production RAG system is how you turn that asset into an intelligent, always-available knowledge layer. The architecture is here. The time to build it is now.Interesting links and further reading📖 Vertex AI RAG Engine official documentation — the authoritative reference for the RAG API used in this architecture🔬 RAG vs Fine-tuning: a technical deep dive — academic comparison of retrieval-based vs parametric knowledge approaches⚡ Eventarc documentation and patterns — everything you need to know about GCP’s eventing backbone🏗️ Terraform Google provider reference — complete IaC reference for all GCP resources🔍 BEIR benchmark for retrieval evaluation — the standard benchmark suite for comparing retrieval systems; useful for validating your RAG quality🧠 ColBERT: late interaction retrieval explained — the research behind one of the most accurate retrieval models available; context for when you outgrow managed RAG💡 Google ADK (Agent Development Kit) overview — the framework powering the adk-agent in this architecture📊 AWS Bedrock Knowledge Bases pricing — for the cost comparison section reference🔐 GCP IAM best practices — the complete guide to least-privilege service account design🛠️ LangChain RAG tutorial — the starting point for DIY RAG if you want maximum flexibilityThis article was written based on the Super_RAG V1 codebase. Architecture diagrams reflect the actual implementation. All cost estimates are approximations based on GCP pricing as of early 2025 and will vary with usage patterns and pricing changes.Building a production-ready Agentic RAG system on GCP: (Vertex AI, ADK, Terraform) was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.