|
| 1 | +""" |
| 2 | +Batched Embeddings Example for Gemini API |
| 3 | +
|
| 4 | +Demonstrates how to efficiently process multiple texts in a single API call. |
| 5 | +""" |
| 6 | + |
| 7 | +import os |
| 8 | +import google.generativeai as genai |
| 9 | + |
| 10 | +def batch_embed_example(): |
| 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 | + |
| 17 | + # Sample texts to embed |
| 18 | + texts = [ |
| 19 | + "The quick brown fox jumps over the lazy dog.", |
| 20 | + "Gemini's batch embeddings are more efficient than individual calls.", |
| 21 | + "Always prefer batch processing when possible.", |
| 22 | + "This example shows best practices for the Gemini Embeddings API.", |
| 23 | + "Batch processing reduces API calls and improves performance." |
| 24 | + ] |
| 25 | + |
| 26 | + print(f"Embedding {len(texts)} texts in a single batch...") |
| 27 | + |
| 28 | + try: |
| 29 | + response = genai.embed_content( |
| 30 | + model="models/embedding-001", |
| 31 | + content=texts, |
| 32 | + task_type="RETRIEVAL_DOCUMENT" |
| 33 | + ) |
| 34 | + |
| 35 | + assert len(response["embedding"]) == len(texts) |
| 36 | + |
| 37 | + print(f"\nSuccess! Generated {len(texts)} embeddings:") |
| 38 | + for i, (text, emb) in enumerate(zip(texts, response["embedding"])): |
| 39 | + print(f"\nText {i+1}: {text[:50]}...") |
| 40 | + print(f"First 5 dimensions: {emb[:5]}") |
| 41 | + print(f"Total dimensions: {len(emb)}") |
| 42 | + |
| 43 | + except Exception as e: |
| 44 | + print(f"Error during batch embedding: {e}") |
| 45 | + |
| 46 | +if __name__ == "__main__": |
| 47 | + batch_embed_example() |
0 commit comments