Skip to content

Added Examples for Batched Text Embeddings #571

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions examples/gemini/python/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## Embedding Examples

- [batched_embeddings.py](./batched_embeddings.py) - Demonstrates efficient batch processing of multiple texts in a single API call
47 changes: 47 additions & 0 deletions examples/gemini/python/batched_embeddings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""
Batched Embeddings Example for Gemini API

Demonstrates how to efficiently process multiple texts in a single API call.
"""

import os
import google.generativeai as genai

def batch_embed_example():
# Configure the API
api_key = os.getenv("GOOGLE_API_KEY")
if not api_key:
raise ValueError("GOOGLE_API_KEY environment variable not set")
genai.configure(api_key=api_key)

# Sample texts to embed
texts = [
"The quick brown fox jumps over the lazy dog.",
"Gemini's batch embeddings are more efficient than individual calls.",
"Always prefer batch processing when possible.",
"This example shows best practices for the Gemini Embeddings API.",
"Batch processing reduces API calls and improves performance."
]

print(f"Embedding {len(texts)} texts in a single batch...")

try:
response = genai.embed_content(
model="models/embedding-001",
content=texts,
task_type="RETRIEVAL_DOCUMENT"
)

assert len(response["embedding"]) == len(texts)

print(f"\nSuccess! Generated {len(texts)} embeddings:")
for i, (text, emb) in enumerate(zip(texts, response["embedding"])):
print(f"\nText {i+1}: {text[:50]}...")
print(f"First 5 dimensions: {emb[:5]}")
print(f"Total dimensions: {len(emb)}")

except Exception as e:
print(f"Error during batch embedding: {e}")

if __name__ == "__main__":
batch_embed_example()