Troubleshooting Fresh 🌱
Common issues, error codes, and solutions for Gemini Embedding 2.
Diagnostic Flow
Common Errors
400 Bad Request
| Symptom | Cause | Fix |
|---|---|---|
| "Invalid content" | Empty content field | Ensure contents is non-empty |
| "Invalid MIME type" | Unsupported format | Use PNG/JPEG (image), MP4/MOV (video), MP3/WAV (audio), PDF |
| "Content too large" | Input exceeds limits | Text: 8192 tokens, video: 128s, audio: 80s, images: 6, PDF: 6 pages |
| "Invalid task type" | Typo in task_type | Use exact enum: RETRIEVAL_QUERY, RETRIEVAL_DOCUMENT, etc. |
| "Invalid dimensions" | Out of range | Use 128-3072 (integers only) |
401 Unauthorized
| Symptom | Cause | Fix |
|---|---|---|
| "API key not valid" | Invalid or expired key | Regenerate at AI Studio |
| "Missing API key" | Header not set | Add x-goog-api-key header or set GOOGLE_API_KEY env var |
| Key works in curl but not SDK | Env var name mismatch | SDK expects GOOGLE_API_KEY environment variable |
403 Forbidden
| Symptom | Cause | Fix |
|---|---|---|
| "Permission denied" | API not enabled | Enable Gemini API in Google Cloud Console |
| "Quota exceeded" | Free tier limit hit | Upgrade to paid tier or wait for quota reset |
| "Region not supported" | Geographic restriction | Use a supported region |
429 Rate Limited
| Symptom | Cause | Fix |
|---|---|---|
| "Resource exhausted" | Too many requests | Implement exponential backoff |
| Burst limit hit | Spike in traffic | Add request queuing |
| Daily quota hit | Volume limit reached | Spread 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:
raise500 Server Error
| Symptom | Cause | Fix |
|---|---|---|
| "Internal error" | Temporary server issue | Retry after 1-5 seconds |
| Consistent 500s | Service disruption | Check Google Cloud Status |
Modality-Specific Issues
Text
| Issue | Solution |
|---|---|
| Token limit exceeded | Split text into chunks under 8192 tokens |
| Poor similarity scores | Use matching task types (QUERY + DOCUMENT pairing) |
| Inconsistent results | Ensure consistent output_dimensionality across all embeddings |
| Empty embedding returned | Verify input text is not whitespace-only |
Images
| Issue | Solution |
|---|---|
| Unsupported format error | Convert to PNG or JPEG: convert input.webp output.png |
| Too many images | Max 6 per request; batch into groups of 6 |
| Base64 encoding fails | Use base64 -w 0 to avoid line wraps in cURL |
| Image not found in search | Verify image has meaningful visual content (not blank) |
Video
| Issue | Solution |
|---|---|
| Duration exceeded | Chunk into segments under 128 seconds with 10s overlap |
| Unsupported codec | Re-encode: ffmpeg -i input.avi -c:v libx264 output.mp4 |
| Unsupported format | Convert: ffmpeg -i input.webm -c copy output.mp4 |
| Large file timeout | Compress: ffmpeg -i input.mp4 -crf 28 -preset fast output.mp4 |
Audio
| Issue | Solution |
|---|---|
| Duration exceeded | Split into segments under 80 seconds with 5s overlap |
| Unsupported format | Convert: ffmpeg -i input.ogg output.mp3 |
| Silent audio | Model may still process; verify input has actual content |
| Large WAV file | Convert to MP3 for smaller payload |
PDF
| Issue | Solution |
|---|---|
| Too many pages | Split into 6-page chunks using PyPDF2 or pikepdf |
| Encrypted PDF | Decrypt first with pikepdf or PyPDF2 |
| Scanned PDF | Model handles natively; no OCR preprocessing needed |
| Corrupted file | Validate 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
| Issue | Solution |
|---|---|
| Low cosine similarity scores | Normalize vectors when using dimensions below 3072 |
| Dimension mismatch in DB | All embeddings in a collection must use the same dimensions |
| Unexpected vector length | Check 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
- API Reference — Full parameter documentation
- Getting Started — Setup verification
- Migration — Upgrade from embedding-001
- Pricing — Quota and tier information