Skip to content

Getting Started Fresh 🌱

Set up your environment and generate your first embedding with Gemini Embedding 2.

Overview

Prerequisites

  • Google Cloud account or AI Studio access
  • Python 3.9+ or Node.js 18+
  • A Gemini API key from Google AI Studio

Step 1: Obtain Your API Key

  1. Navigate to Google AI Studio
  2. Sign in with your Google account
  3. Click Create API Key
  4. Copy and store your key securely
bash
# Set as environment variable
export GEMINI_API_KEY="your-api-key-here"

Step 2: Install the SDK

bash
pip install google-genai
bash
npm install @google/genai

Step 3: Generate Your First Embedding

python
from google import genai

client = genai.Client()

result = client.models.embed_content(
    model='gemini-embedding-2-preview',
    contents='What is the meaning of life?'
)

print(f"Dimensions: {len(result.embeddings[0].values)}")
print(f"First 5 values: {result.embeddings[0].values[:5]}")
javascript
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

const response = await ai.models.embedContent({
    model: 'gemini-embedding-2-preview',
    contents: 'What is the meaning of life?',
});

console.log(`Dimensions: ${response.embeddings[0].values.length}`);
console.log(`First 5 values: ${response.embeddings[0].values.slice(0, 5)}`);
bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-2-preview:embedContent" \
    -H "Content-Type: application/json" \
    -H "x-goog-api-key: ${GEMINI_API_KEY}" \
    -d '{"content": {"parts": [{"text": "What is the meaning of life?"}]}}'

Step 4: Customize with Task Type and Dimensions

python
from google import genai
from google.genai import types

client = genai.Client()

result = client.models.embed_content(
    model='gemini-embedding-2-preview',
    contents='search query here',
    config=types.EmbedContentConfig(
        task_type='RETRIEVAL_QUERY',
        output_dimensionality=768
    )
)

Verification Checklist

  • [ ] API key obtained and stored as environment variable
  • [ ] SDK installed (google-genai for Python, @google/genai for Node.js)
  • [ ] First embedding generated successfully
  • [ ] Output dimensions match expected value (3072 default)
  • [ ] Task type parameter tested

Troubleshooting

IssueSolution
API key not validVerify key in AI Studio, check for whitespace
ModuleNotFoundErrorRun pip install google-genai (not google-generativeai)
Permission deniedEnable the Gemini API in your Google Cloud project
Empty responseEnsure content parameter is not empty

See Also

Built with VitePress. Not affiliated with Google.