RAG with Google Gemini and Vertex AI

Set up the Gemini API, generate embeddings and answers with Gemini, and move to Vertex AI.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 18 · Lesson 2 of 3 · Intermediate

RAG with Google Gemini and Vertex AI

Set up the Gemini API, generate embeddings and answers with Gemini, and move to Vertex AI.

Google's Gemini models can power every part of a RAG system: Gemini embedding models for retrieval and Gemini chat models for answers. The same Python SDK, google-genai, works with the Gemini Developer API (an API key) and with Google Cloud's enterprise Gemini platform (formerly Vertex AI). This lesson sets up the SDK, generates embeddings and answers, and shows how to switch to Google Cloud.

What you will learn

  • How to get a Gemini API key and install the Google Gen AI SDK
  • How to generate text, with system instructions and streaming
  • How to create Gemini embeddings correctly for queries and documents
  • How to build a small Gemini RAG pipeline and move it to Google Cloud

Prerequisites

Checked November 2026

Model IDs and SDK details below were taken from Google's documentation in November 2026. Google's models page lists the Gemini 4 family (for example gemini-4-hydrogen, used in the quickstart) plus Flash and Flash-Lite models, and gemini-embedding-2 for embeddings. It also notes that requests to older gemini-2.5-* model IDs are rerouted from 1 December 2026. Always check the current models page.

Step 1: Install and authenticate

pip install -U "google-genai<3.0.0" numpy python-dotenv

The SDK's README recommends pinning below version 3 for now, because version 3 changes some defaults. Create an API key in Google AI Studio and store it in .env:

.env
GEMINI_API_KEY=your-gemini-key

The client reads GEMINI_API_KEY (or GOOGLE_API_KEY, which takes priority if both are set).

Step 2: Generate text

gemini_hello.py
from dotenv import load_dotenv
from google import genai
from google.genai import types

load_dotenv()
client = genai.Client()
MODEL = "gemini-4-hydrogen"

response = client.models.generate_content(
    model=MODEL,
    contents="Explain Retrieval-Augmented Generation in two sentences.",
    config=types.GenerateContentConfig(
        system_instruction="You are a concise assistant for developers.",
        max_output_tokens=300,
    ),
)
print(response.text)

To stream, call client.models.generate_content_stream(...) with the same arguments and print chunk.text for each chunk.

Step 3: Embeddings

Two details from Google's embedding documentation matter for RAG:

  • gemini-embedding-2 combines a list of inputs into one embedding. To get one vector per chunk, embed each text in its own call (or as a separate content item), or use gemini-embedding-001, which returns one embedding per string.
  • Task prefixes instead of a task type. gemini-embedding-2 expects queries as task: search result | query: ... and documents as title: ... | text: ... (use title: none when there is no title).
import numpy as np

EMBED_MODEL = "gemini-embedding-2"
DIMS = 768                              # 768, 1536 or 3072 (default) are recommended

def embed_one(text: str) -> np.ndarray:
    result = client.models.embed_content(
        model=EMBED_MODEL, contents=text,
        config=types.EmbedContentConfig(output_dimensionality=DIMS))
    v = np.array(result.embeddings[0].values, dtype=np.float32)
    return v / np.linalg.norm(v)        # normalise (important for reduced dimensions)

def embed_document(text: str, title: str = "none") -> np.ndarray:
    return embed_one(f"title: {title} | text: {text}")

def embed_query(question: str) -> np.ndarray:
    return embed_one(f"task: search result | query: {question}")

Step 4: A small Gemini RAG pipeline

gemini_rag.py
CHUNKS = [
    ("Leave policy", "Employees get 18 days of paid leave in their first year."),
    ("Leave policy", "Up to 5 unused leave days can be carried over."),
    ("Expense policy", "Expense claims must be submitted within 30 days."),
]
doc_vectors = np.vstack([embed_document(text, title) for title, text in CHUNKS])

def answer(question: str, k: int = 2) -> str:
    scores = doc_vectors @ embed_query(question)
    top = np.argsort(-scores)[:k]
    sources = "\n".join(f'<source id="{n}" title="{CHUNKS[i][0]}">{CHUNKS[i][1]}</source>'
                        for n, i in enumerate(top, start=1))
    response = client.models.generate_content(
        model=MODEL,
        contents=f"<sources>\n{sources}\n</sources>\n\nQuestion: {question}",
        config=types.GenerateContentConfig(
            system_instruction="Answer only from the sources, citing ids like [1]. "
                               "If the sources do not contain the answer, say so."),
    )
    return response.text

print(answer("Can I carry over unused leave?"))
Yes, you can carry over up to 5 unused leave days [1].

Step 5: Move to Google Cloud

For enterprise use (Google Cloud IAM, regions, VPC controls, billing through your cloud account), the same SDK talks to Google Cloud's Gemini platform. Authenticate with Application Default Credentials (gcloud auth application-default login), enable the API in your project, then create the client with:

client = genai.Client(enterprise=True, project="your-project-id", location="global")

or set the environment variables GOOGLE_GENAI_USE_ENTERPRISE=true, GOOGLE_CLOUD_PROJECT and GOOGLE_CLOUD_LOCATION and keep genai.Client(). Older tutorials use vertexai=True; follow the current SDK documentation for your installed version. The rest of the code stays the same.

Common errors and troubleshooting

  • API key not valid: check which variable is set; GOOGLE_API_KEY overrides GEMINI_API_KEY.
  • Only one embedding returned for a list: expected with gemini-embedding-2; embed texts individually.
  • Poor retrieval: missing query/document prefixes, or mixing embeddings of different dimensions.
  • Model not found: confirm the current model ID on the models page; older IDs are retired or rerouted.
  • Permission denied on Google Cloud: enable the API and grant your account the required IAM role in the project.

Key takeaways

  • google-genai serves both the Gemini Developer API and Google Cloud's enterprise platform.
  • Generate with client.models.generate_content, reading response.text; set behaviour with system_instruction.
  • Embed with client.models.embed_content; follow the model's prefix rules and one-text-per-call behaviour.
  • Switch to Google Cloud with genai.Client(enterprise=True, project=..., location=...).

Frequently asked questions

Can I use Gemini embeddings with Claude or OpenAI answers?

Yes. Retrieval and generation are independent; mix providers as needed (Model-Agnostic RAG).

Is there a managed RAG service on Google Cloud?

Google Cloud offers managed retrieval and search products; evaluate them against a self-built pipeline on your own test set.

Practice exercises

  1. Compare retrieval quality with 768 and 3072 dimensions on ten questions.
  2. Stream the answer with generate_content_stream.

Related tutorials