Skip to content

Troubleshooting Fresh 🌱

Common issues, error codes, and solutions for Gemini Embedding 2.

Diagnostic Flow

Common Errors

400 Bad Request

SymptomCauseFix
"Invalid content"Empty content fieldEnsure contents is non-empty
"Invalid MIME type"Unsupported formatUse PNG/JPEG (image), MP4/MOV (video), MP3/WAV (audio), PDF
"Content too large"Input exceeds limitsText: 8192 tokens, video: 128s, audio: 80s, images: 6, PDF: 6 pages
"Invalid task type"Typo in task_typeUse exact enum: RETRIEVAL_QUERY, RETRIEVAL_DOCUMENT, etc.
"Invalid dimensions"Out of rangeUse 128-3072 (integers only)

401 Unauthorized

SymptomCauseFix
"API key not valid"Invalid or expired keyRegenerate at AI Studio
"Missing API key"Header not setAdd x-goog-api-key header or set GOOGLE_API_KEY env var
Key works in curl but not SDKEnv var name mismatchSDK expects GOOGLE_API_KEY environment variable

403 Forbidden

SymptomCauseFix
"Permission denied"API not enabledEnable Gemini API in Google Cloud Console
"Quota exceeded"Free tier limit hitUpgrade to paid tier or wait for quota reset
"Region not supported"Geographic restrictionUse a supported region

429 Rate Limited

SymptomCauseFix
"Resource exhausted"Too many requestsImplement exponential backoff
Burst limit hitSpike in trafficAdd request queuing
Daily quota hitVolume limit reachedSpread requests or upgrade plan

Exponential backoff implementation:

python
import time
import random

def embed_with_retry(client, contents, max_retries=5):
    for attempt in range(max_retries):
        try:
            return client.models.embed_content(
                model='gemini-embedding-2-preview',
                contents=contents
            )
        except Exception as e:
            if '429' in str(e) and attempt < max_retries - 1:
                wait = (2 ** attempt) + random.uniform(0, 1)
                print(f"Rate limited. Waiting {wait:.1f}s...")
                time.sleep(wait)
            else:
                raise

500 Server Error

SymptomCauseFix
"Internal error"Temporary server issueRetry after 1-5 seconds
Consistent 500sService disruptionCheck Google Cloud Status

Modality-Specific Issues

Text

IssueSolution
Token limit exceededSplit text into chunks under 8192 tokens
Poor similarity scoresUse matching task types (QUERY + DOCUMENT pairing)
Inconsistent resultsEnsure consistent output_dimensionality across all embeddings
Empty embedding returnedVerify input text is not whitespace-only

Images

IssueSolution
Unsupported format errorConvert to PNG or JPEG: convert input.webp output.png
Too many imagesMax 6 per request; batch into groups of 6
Base64 encoding failsUse base64 -w 0 to avoid line wraps in cURL
Image not found in searchVerify image has meaningful visual content (not blank)

Video

IssueSolution
Duration exceededChunk into segments under 128 seconds with 10s overlap
Unsupported codecRe-encode: ffmpeg -i input.avi -c:v libx264 output.mp4
Unsupported formatConvert: ffmpeg -i input.webm -c copy output.mp4
Large file timeoutCompress: ffmpeg -i input.mp4 -crf 28 -preset fast output.mp4

Audio

IssueSolution
Duration exceededSplit into segments under 80 seconds with 5s overlap
Unsupported formatConvert: ffmpeg -i input.ogg output.mp3
Silent audioModel may still process; verify input has actual content
Large WAV fileConvert to MP3 for smaller payload

PDF

IssueSolution
Too many pagesSplit into 6-page chunks using PyPDF2 or pikepdf
Encrypted PDFDecrypt first with pikepdf or PyPDF2
Scanned PDFModel handles natively; no OCR preprocessing needed
Corrupted fileValidate with PyPDF2.PdfReader; re-export from source

Cross-Model Compatibility

Incompatible Embedding Spaces

Embeddings from gemini-embedding-001 and gemini-embedding-2-preview are NOT compatible.

  • Cannot compare vectors from different models
  • Cannot mix in the same vector database collection
  • Must re-embed all data when migrating

Dimension and Normalization Issues

IssueSolution
Low cosine similarity scoresNormalize vectors when using dimensions below 3072
Dimension mismatch in DBAll embeddings in a collection must use the same dimensions
Unexpected vector lengthCheck output_dimensionality parameter; default is 3072

Normalization code:

python
import numpy as np

def normalize(vector):
    vec = np.array(vector)
    norm = np.linalg.norm(vec)
    if norm == 0:
        return vec
    return (vec / norm).tolist()

Debugging Checklist

  • [ ] API key is valid and set correctly
  • [ ] Gemini API is enabled in Google Cloud Console
  • [ ] Input content is non-empty and within size limits
  • [ ] MIME type matches actual file format
  • [ ] Task type is a valid enum value
  • [ ] Dimensions are between 128 and 3072
  • [ ] Same model used for all embeddings in a collection
  • [ ] Normalization applied for dimensions below 3072
  • [ ] Rate limiting handled with exponential backoff
  • [ ] Error responses logged for debugging

See Also

Built with VitePress. Not affiliated with Google.