Skip to content

Commit 3a124b3

Browse files
committed
docs: Add working batched embeddings example (Fixes #147)
1 parent 7ede8f4 commit 3a124b3

File tree

1 file changed

+16
-14
lines changed

1 file changed

+16
-14
lines changed

examples/gemini/python/batched_embeddings.py

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,16 @@
44
Demonstrates how to efficiently process multiple texts in a single API call.
55
"""
66

7+
import os
78
import google.generativeai as genai
89

910
def batch_embed_example():
10-
# Configure the API (in production, use environment variables)
11-
genai.configure(api_key="YOUR_API_KEY_HERE") # Replace with your actual API key
12-
11+
# Configure the API
12+
api_key = os.getenv("GOOGLE_API_KEY")
13+
if not api_key:
14+
raise ValueError("GOOGLE_API_KEY environment variable not set")
15+
genai.configure(api_key=api_key)
16+
1317
# Sample texts to embed
1418
texts = [
1519
"The quick brown fox jumps over the lazy dog.",
@@ -18,26 +22,24 @@ def batch_embed_example():
1822
"This example shows best practices for the Gemini Embeddings API.",
1923
"Batch processing reduces API calls and improves performance."
2024
]
21-
25+
2226
print(f"Embedding {len(texts)} texts in a single batch...")
23-
24-
# Make a single batch request
27+
2528
try:
2629
response = genai.embed_content(
2730
model="models/embedding-001",
2831
content=texts,
2932
task_type="RETRIEVAL_DOCUMENT"
3033
)
31-
32-
# Verify we got embeddings for all texts
34+
3335
assert len(response["embedding"]) == len(texts)
34-
35-
print("\nSuccess! Embeddings generated:")
36-
for i, (text, embedding) in enumerate(zip(texts, response["embedding"])):
36+
37+
print(f"\nSuccess! Generated {len(texts)} embeddings:")
38+
for i, (text, emb) in enumerate(zip(texts, response["embedding"])):
3739
print(f"\nText {i+1}: {text[:50]}...")
38-
print(f"Embedding vector (first 5 dims): {embedding[:5]}")
39-
print(f"Vector length: {len(embedding)}")
40-
40+
print(f"First 5 dimensions: {emb[:5]}")
41+
print(f"Total dimensions: {len(emb)}")
42+
4143
except Exception as e:
4244
print(f"Error during batch embedding: {e}")
4345

0 commit comments

Comments
 (0)