A hands-on tutorial for building a production-grade RAG (Retrieval-Augmented Generation) system with Vertex AI Vector Search + LangChain + Gemini. We cover embedding generation, chunking, ANN search, and injection into Gemini, all with working code samples.
Documents (PDF/MD/HTML)
|
Parse (Document AI / Unstructured)
|
Chunking (512-1024 tok, overlap 100)
|
Embedding (text-embedding-005)
|
v
Vertex AI Vector Search Index
^
| (search)
User Query → Embedding → Vector Search → Top-K → Gemini Pro → Answer# pip install langchain langchain-google-vertexai google-cloud-aiplatform
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import PyPDFLoader
loader = PyPDFLoader("doc.pdf")
docs = loader.load()
splitter = RecursiveCharacterTextSplitter(
chunk_size=1024,
chunk_overlap=100,
separators=["\n\n", "\n", "。", "!", "?", " "],
)
chunks = splitter.split_documents(docs)
print(f"{len(chunks)} chunks")from langchain_google_vertexai import VertexAIEmbeddings
embeddings = VertexAIEmbeddings(model_name="text-embedding-005")
texts = [chunk.page_content for chunk in chunks]
vectors = embeddings.embed_documents(texts)
print(f"Vector dim: {len(vectors[0])}") # 768from google.cloud import aiplatform as ai
ai.init(project="my-project", location="asia-northeast1")
# Upload embeddings to GCS in JSONL format
# {"id": "doc1-chunk1", "embedding": [0.1, 0.2, ...]}
# Create the index
index = ai.MatchingEngineIndex.create_tree_ah_index(
display_name="my-rag-index",
contents_delta_uri="gs://my-bucket/embeddings/",
dimensions=768,
approximate_neighbors_count=10,
distance_measure_type="DOT_PRODUCT_DISTANCE",
)
# Deploy the endpoint
endpoint = ai.MatchingEngineIndexEndpoint.create(
display_name="my-rag-endpoint",
public_endpoint_enabled=True,
)
endpoint.deploy_index(index=index, deployed_index_id="my_rag_v1")from langchain_google_vertexai import ChatVertexAI
from langchain.prompts import ChatPromptTemplate
llm = ChatVertexAI(model_name="gemini-2.0-pro-001", temperature=0.3)
def search_and_answer(query: str) -> str:
# 1. Embed the query
query_emb = embeddings.embed_query(query)
# 2. Vector Search
response = endpoint.find_neighbors(
deployed_index_id="my_rag_v1",
queries=[query_emb],
num_neighbors=5,
)
top_chunks = [chunks[int(n.id.split("-chunk")[1])] for n in response[0]]
# 3. Generate the answer with Gemini
context = "\n\n".join([c.page_content for c in top_chunks])
prompt = ChatPromptTemplate.from_template("""
Answer the user's question based on the context below.
If the answer is not in the context, reply "I don't know."
# Context
{context}
# Question
{query}
# Answer
""")
chain = prompt | llm
result = chain.invoke({"context": context, "query": query})
return result.content
# Usage
print(search_and_answer("How do I request time off?"))from langchain.retrievers import EnsembleRetriever
from langchain_community.retrievers import BM25Retriever
# Keyword search
bm25 = BM25Retriever.from_documents(chunks)
# Vector search (Vertex AI Vector Search wrapper)
from langchain_google_vertexai import VectorSearchVectorStore
vector_retriever = VectorSearchVectorStore.from_components(
project_id="my-project",
region="asia-northeast1",
gcs_bucket_name="my-bucket",
index_id="my-rag-index",
endpoint_id="my-rag-endpoint",
).as_retriever()
# Ensemble (weighted)
ensemble = EnsembleRetriever(
retrievers=[vector_retriever, bm25],
weights=[0.7, 0.3],
)
results = ensemble.invoke("time off request")| Item | Monthly |
|---|---|
| Embedding (initial + updates) | ~$5 |
| Vector Search Index storage | ~$20 |
| Vector Search Endpoint | ~$30 |
| Vector Search queries (10K) | ~$1 |
| Gemini Pro generation (10K queries × 1K tok) | ~$50 |
| Cloud Run API | ~$5 |
| Total | ~$110/month |
What is RAG?
Retrieval-Augmented Generation. A technique that searches internal documents via embeddings, then passes the results to an LLM as context to generate answers. More flexible and cheaper than fine-tuning.
What are the strengths of Vertex AI Vector Search?
Fast ANN search built on Google ScaNN, fully managed, metadata filters, and automatic embedding sync with BigQuery. No need to implement search algorithms yourself.
Should I use LangChain or LlamaIndex?
You can use both together. LangChain is a general-purpose framework (strong in agents and tools); LlamaIndex specializes in RAG (rich index structures). Pick based on team preference.
When should I use Vertex AI Search instead?
No-code and fully managed → Vertex AI Search. Flexibility and fine-grained customization → LangChain + Vector Search. The former suits business users, the latter suits engineers.
Which embedding model should I use?
Google text-embedding-005 (768 dimensions, multilingual), OpenAI text-embedding-3-small (1536 dimensions, cheap), or Cohere multilingual-v3 (1024 dimensions). Google and Cohere lead on multilingual performance.
What chunking strategy should I use?
Recommended: 512-1024 tokens per chunk with a 100-token overlap. Split Markdown by headings and PDFs by paragraphs. Document AI can also perform semantic splitting.
How much does it cost?
1,000 single-page documents: embeddings $1-2, Vector Search storage $20/month, queries $0.0001 each, and Gemini Pro generation at $1.25 per 1M input tokens. Starts at a few thousand yen per month.
What about hybrid search?
Combining vector (semantic) search with keyword (BM25) search improves accuracy. Vertex AI Search supports this out of the box; in LangChain, use EnsembleRetriever.
Related articles: RAG / Gen AI
GCP PMLE 試験対策|Vertex AI + Gemini 生成 AI 実装パターン完全ガイド
Google Cloud Professional ML Engineer (PMLE) の Gen AI 領域を実装視点で解説。Gemini ファミリー選定、RAG パターン、Vertex AI Agent Builder、Fine-tuning、Responsible AI を網羅。
Vertex AI Agent Builder 完全ガイド|Conversational Agents・Vertex AI Search・Tool Use (GCP)
Google Cloud Vertex AI Agent Builder の全機能解説。Conversational Agents (Dialogflow CX 後継)、Vertex AI Search、Tool Use、Grounding、Playbook、料金、ChatGPT GPTs / Copilot Studio 比較を網羅。
Generative AI Leader (GAIL) 完全ガイド|Google Cloud 生成 AI 認定 (2025 年 5 月リリース新試験)
Google Cloud Generative AI Leader (GAIL、2025-05-14 リリース) の完全ガイド。4 ドメイン (生成 AI 基礎 30% / GCP 提供サービス 35% / モデル出力改善 20% / ビジネス戦略 15%)、Gemini ファミリー、Vertex AI Agent Builder、RAG、ビジネス導入観点を日本語で網羅。
Vertex AI 入門|Google Cloud 統合 ML プラットフォームの全機能 (GAIL/PMLE/PCD 必須知識)
Google Cloud Vertex AI の入門解説。Vertex AI Studio / Agent Builder / Model Garden / Search / Pipelines / Training の全機能、Gemini モデルファミリー (Pro/Flash/Ultra)、Azure OpenAI との比較、料金体系、Responsible AI 機能を日本語で整理。
* Google Cloud and Gemini are property of Google LLC; LangChain is property of LangChain, Inc.
Practice with certification-focused question sets
View GCP exam prepNicheeLab Editorial Team
NicheeLab editorial team focused on data engineering and cloud certification learning. Content is structured around practical study needs and official exam domains.
Google Cloud Certification Roadmap (2026)
Choose your GCP certification path — Foundational, Associate...
CDL Cloud Digital Leader: Complete Exam Guide (2026)
Pass the Cloud Digital Leader exam — cloud business value, G...
GAIL Generative AI Leader: Complete Exam Guide (2026)
Pass the Generative AI Leader exam — Gemini, Vertex AI, Work...
Vertex AI Fundamentals for GCP Certs (2026)
Vertex AI basics every cert candidate needs — Workbench, Pip...
Associate Cloud Engineer (ACE): Complete Guide (2026)
Pass the Associate Cloud Engineer exam — Console, gcloud, pr...