GoogleのGemini Embedding 2 APIを使用すると、テキスト、画像、動画、音声、PDFの埋め込みを生成できます。このガイドでは、今日すぐに実行できる実際のコード例を交えながら、その使用方法を説明します。
注:このガイドは、パブリックプレビュー版(gemini-embedding-2-preview)について説明しています。一般提供開始前にAPIが変更される可能性があります。
まずGemini Embedding 2とは何かを理解したいですか?概要をお読みください:Gemini Embedding 2とは?
前提条件
必要なもの:
- Google AI APIキー
- Python 3.7以降
- Google Generative AI SDK
インストール
SDKをインストールします。
pip install google-generativeai
基本的なセットアップ
APIキーを設定します。
import google.generativeai as genai
# Set your API key
genai.configure(api_key='YOUR_API_KEY')
本番環境では、環境変数を使用します。
import os
import google.generativeai as genai
api_key = os.getenv('GEMINI_API_KEY')
genai.configure(api_key=api_key)
Apidogでのテスト
コードを掘り下げる前に、ApidogでGemini Embedding APIを直接テストできます。

- Apidogで新しいリクエストを作成します
- メソッドを
POSTに設定します - URL:
https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-2-preview:embedContent - ヘッダーを追加:
x-goog-api-key: YOUR_API_KEY - 本文(JSON):
{
"content": {
"parts": [{
"text": "What is API testing?"
}]
}
}
これにより、コードを記述する前にAPIキーが機能することを確認し、応答構造を確認できます。これをテストケースとして保存し、CI/CDパイプラインで埋め込み応答を検証できます。
テキスト埋め込みの生成
最もシンプルなユースケース - テキストを埋め込む:
import google.generativeai as genai
genai.configure(api_key='YOUR_API_KEY')
# Generate embedding
result = genai.embed_content(
model='models/gemini-embedding-2-preview',
content='What is the meaning of life?'
)
# Get the embedding vector
embedding = result['embedding']
print(f"Embedding dimensions: {len(embedding)}")
print(f"First 5 values: {embedding[:5]}")
出力:
Embedding dimensions: 3072
First 5 values: [0.0234, -0.0156, 0.0891, -0.0423, 0.0567]
注: 応答構造はresult['embedding']で、これは浮動小数点数のリストを返します。各浮動小数点数は、埋め込みベクトルの1つの次元を表します。
タスク指示の使用
タスク指示は、特定のユースケースに合わせて埋め込みを最適化します。
# For search queries
query_result = genai.embed_content(
model='models/gemini-embedding-2-preview',
content='best API testing tools',
task_type='RETRIEVAL_QUERY'
)
# For documents you're indexing
doc_result = genai.embed_content(
model='models/gemini-embedding-2-preview',
content='Apidog is an API testing platform...',
task_type='RETRIEVAL_DOCUMENT'
)
利用可能なタスクタイプ:
RETRIEVAL_QUERY- 検索クエリに使用RETRIEVAL_DOCUMENT- インデックス作成するドキュメントに使用SEMANTIC_SIMILARITY- コンテンツの類似性を比較するために使用CLASSIFICATION- 分類タスクに使用CLUSTERING- 類似コンテンツのグループ化に使用
出力次元の制御
より小さな次元を使用することで、ストレージコストを削減します。
# Production-optimized: 768 dimensions
result = genai.embed_content(
model='models/gemini-embedding-2-preview',
content='Your text here',
output_dimensionality=768
)
# Balanced: 1536 dimensions
result = genai.embed_content(
model='models/gemini-embedding-2-preview',
content='Your text here',
output_dimensionality=1536
)
# Maximum quality: 3072 dimensions (default)
result = genai.embed_content(
model='models/gemini-embedding-2-preview',
content='Your text here',
output_dimensionality=3072
)
ほとんどのアプリケーションでは、768次元でストレージを75%削減しながら、ほぼ最高の品質が得られます。
画像の埋め込み
ビジュアル検索のために画像を埋め込む:
import PIL.Image
# Load image
image = PIL.Image.open('product-photo.jpg')
# Generate embedding
result = genai.embed_content(
model='models/gemini-embedding-2-preview',
content=image
)
embedding = result['embedding']
1リクエストあたり最大6つの画像を埋め込むことができます。
images = [
PIL.Image.open('image1.jpg'),
PIL.Image.open('image2.jpg'),
PIL.Image.open('image3.jpg')
]
result = genai.embed_content(
model='models/gemini-embedding-2-preview',
content=images
)
動画の埋め込み
動画検索のために動画コンテンツを埋め込む:
# Upload video file first
video_file = genai.upload_file(path='demo-video.mp4')
# Wait for processing
import time
while video_file.state.name == 'PROCESSING':
time.sleep(2)
video_file = genai.get_file(video_file.name)
# Generate embedding
result = genai.embed_content(
model='models/gemini-embedding-2-preview',
content=video_file
)
embedding = result['embedding']
動画の制限:
- 1リクエストあたり最大128秒
- 形式: MP4, MOV
- コーデック: H264, H265, AV1, VP9
音声の埋め込み
文字起こしなしで音声を埋め込む:
# Upload audio file
audio_file = genai.upload_file(path='podcast-episode.mp3')
# Wait for processing
while audio_file.state.name == 'PROCESSING':
time.sleep(2)
audio_file = genai.get_file(audio_file.name)
# Generate embedding
result = genai.embed_content(
model='models/gemini-embedding-2-preview',
content=audio_file
)
embedding = result['embedding']
音声の制限:
- 1リクエストあたり最大80秒
- 形式: MP3, WAV
PDFドキュメントの埋め込み
ドキュメント検索のためにPDFページを埋め込む:
# Upload PDF
pdf_file = genai.upload_file(path='user-manual.pdf')
# Wait for processing
while pdf_file.state.name == 'PROCESSING':
time.sleep(2)
pdf_file = genai.get_file(pdf_file.name)
# Generate embedding
result = genai.embed_content(
model='models/gemini-embedding-2-preview',
content=pdf_file
)
embedding = result['embedding']
PDFの制限:
- 1リクエストあたり最大6ページ
- テキストおよびビジュアルコンテンツの両方を処理
マルチモーダル埋め込み(テキスト+画像)
複数のコンテンツタイプを1つの埋め込みに結合する:
import PIL.Image
image = PIL.Image.open('product.jpg')
text = "High-quality wireless headphones with noise cancellation"
# Embed both together
result = genai.embed_content(
model='models/gemini-embedding-2-preview',
content=[text, image]
)
embedding = result['embedding']
これにより、テキストと画像間の関係が単一の埋め込みでキャプチャされます。
バッチ処理
複数の項目を効率的に処理する:
texts = [
"First document about API testing",
"Second document about automation",
"Third document about performance"
]
embeddings = []
for text in texts:
result = genai.embed_content(
model='models/gemini-embedding-2-preview',
content=text,
task_type='RETRIEVAL_DOCUMENT',
output_dimensionality=768
)
embeddings.append(result['embedding'])
print(f"Generated {len(embeddings)} embeddings")
大規模なバッチ処理の場合は、バッチAPIを使用してコストを50%削減できます。
セマンティック検索システムの構築
Gemini Embedding 2を使用したセマンティック検索の完全な例を以下に示します。
ステップ1: 依存関係のインストール
pip install google-generativeai numpy scikit-learn
ステップ2: ドキュメントの埋め込み
import google.generativeai as genai
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
genai.configure(api_key='YOUR_API_KEY')
# Sample documents
documents = [
"Apidog is an API testing platform for developers",
"REST APIs use HTTP methods like GET, POST, PUT, DELETE",
"GraphQL provides a query language for APIs",
"API documentation helps developers understand endpoints",
"Postman is a popular API testing tool"
]
# Generate embeddings for all documents
doc_embeddings = []
for doc in documents:
result = genai.embed_content(
model='models/gemini-embedding-2-preview',
content=doc,
task_type='RETRIEVAL_DOCUMENT',
output_dimensionality=768
)
doc_embeddings.append(result['embedding'])
# Convert to numpy array
doc_embeddings = np.array(doc_embeddings)
ステップ3: 検索関数の作成
def search(query, top_k=3):
# Embed the query
query_result = genai.embed_content(
model='models/gemini-embedding-2-preview',
content=query,
task_type='RETRIEVAL_QUERY',
output_dimensionality=768
)
query_embedding = np.array([query_result['embedding']])
# Calculate similarities
similarities = cosine_similarity(query_embedding, doc_embeddings)[0]
# Get top results
top_indices = np.argsort(similarities)[::-1][:top_k]
results = []
for idx in top_indices:
results.append({
'document': documents[idx],
'score': similarities[idx]
})
return results
ステップ4: 検索
# Test the search
results = search("What tools can I use for API testing?")
for i, result in enumerate(results, 1):
print(f"{i}. Score: {result['score']:.4f}")
print(f" {result['document']}\n")
出力:
1. Score: 0.8234
Apidog is an API testing platform for developers
2. Score: 0.7891
Postman is a popular API testing tool
3. Score: 0.6543
API documentation helps developers understand endpoints
RAGシステムの構築
Retrieval-Augmented GenerationのためにGemini Embedding 2を使用します。
ステップ1: 知識ベースのセットアップ
import google.generativeai as genai
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
genai.configure(api_key='YOUR_API_KEY')
# Knowledge base
knowledge_base = [
"Apidog supports REST, GraphQL, and WebSocket APIs",
"You can create test cases and run them automatically",
"Apidog generates API documentation from your requests",
"Mock servers help you test before backend is ready",
"Team collaboration features include shared workspaces"
]
# Embed knowledge base
kb_embeddings = []
for doc in knowledge_base:
result = genai.embed_content(
model='models/gemini-embedding-2-preview',
content=doc,
task_type='RETRIEVAL_DOCUMENT',
output_dimensionality=768
)
kb_embeddings.append(result['embedding'])
kb_embeddings = np.array(kb_embeddings)
ステップ2: RAGクエリ関数の作成
def rag_query(question):
# 1. Embed the question
query_result = genai.embed_content(
model='models/gemini-embedding-2-preview',
content=question,
task_type='RETRIEVAL_QUERY',
output_dimensionality=768
)
query_embedding = np.array([query_result['embedding']])
# 2. Find relevant context
similarities = cosine_similarity(query_embedding, kb_embeddings)[0]
top_idx = np.argmax(similarities)
context = knowledge_base[top_idx]
# 3. Generate answer with context
prompt = f"""Context: {context}
Question: {question}
Answer the question based on the context provided."""
model = genai.GenerativeModel('gemini-2.0-flash-exp')
response = model.generate_content(prompt)
return response.text
ステップ3: RAGシステムへのクエリ実行
# Test RAG
answer = rag_query("Can Apidog generate documentation?")
print(answer)
これは、知識ベースから最も関連性の高いコンテキストを取得し、それを使用して正確な回答を生成します。
埋め込みをベクトルデータベースに保存する
ChromaDBを使用して埋め込みを保存およびクエリする:
import chromadb
import google.generativeai as genai
genai.configure(api_key='YOUR_API_KEY')
# Initialize ChromaDB
client = chromadb.Client()
collection = client.create_collection(name="my_documents")
# Documents to index
documents = [
"API testing ensures your endpoints work correctly",
"REST APIs follow stateless architecture principles",
"GraphQL allows clients to request specific data"
]
# Generate and store embeddings
for i, doc in enumerate(documents):
result = genai.embed_content(
model='models/gemini-embedding-2-preview',
content=doc,
task_type='RETRIEVAL_DOCUMENT',
output_dimensionality=768
)
collection.add(
embeddings=[result['embedding']],
documents=[doc],
ids=[f"doc_{i}"]
)
# Query the collection
query = "How do I test my API?"
query_result = genai.embed_content(
model='models/gemini-embedding-2-preview',
content=query,
task_type='RETRIEVAL_QUERY',
output_dimensionality=768
)
results = collection.query(
query_embeddings=[query_result['embedding']],
n_results=2
)
print("Top results:")
for doc in results['documents'][0]:
print(f"- {doc}")
エラー処理
APIエラーを適切に処理する:
import google.generativeai as genai
from google.api_core import exceptions
genai.configure(api_key='YOUR_API_KEY')
def safe_embed(content):
try:
result = genai.embed_content(
model='models/gemini-embedding-2-preview',
content=content,
output_dimensionality=768
)
return result['embedding']
except exceptions.InvalidArgument as e:
print(f"Invalid input: {e}")
# Example: Content too long or unsupported format
return None
except exceptions.ResourceExhausted as e:
print(f"Quota exceeded: {e}")
# Example: Rate limit hit or quota exhausted
return None
except exceptions.DeadlineExceeded as e:
print(f"Request timeout: {e}")
# Example: Network issues or slow response
return None
except Exception as e:
print(f"Unexpected error: {e}")
return None
# Use it
embedding = safe_embed("Your text here")
if embedding:
print("Embedding generated successfully")
else:
print("Failed to generate embedding")
一般的なエラーメッセージ:
InvalidArgument: Content exceeds maximum length- 入力サイズを削減してくださいResourceExhausted: Quota exceeded- 待機するかプランをアップグレードしてくださいUnauthenticated: API key not valid- APIキーを確認してくださいPermissionDenied: Model not available- モデル名を確認してください
レート制限とベストプラクティス
レート制限:
- 無料枠: 1分あたり60リクエスト
- 有料枠: プランに基づき上限が引き上げられます
ベストプラクティス:
適切な次元を使用する: 本番環境では768、最高の品質が必要な場合にのみ3072
バッチリクエスト: 可能な場合は複数の項目をまとめて処理する
埋め込みをキャッシュする: 同じコンテンツを再度埋め込まない
タスク指示を使用する: 特定のユースケースでの精度が向上する
エラーを処理する: 指数バックオフ付きの再試行ロジックを実装する
コストを監視する: トークン使用量を追跡する
コスト最適化
これらの戦略でコストを削減する:
1. より小さな次元を使用する:
# 768 dimensions = 75% less storage
result = genai.embed_content(
model='models/gemini-embedding-2-preview',
content=text,
output_dimensionality=768
)
2. 緊急でないタスクにはバッチAPIを使用する:
# 50% cost savings for batch processing
# (Batch API implementation depends on your setup)
3. 埋め込みをキャッシュする:
import hashlib
import json
embedding_cache = {}
def get_embedding_cached(content):
# Create cache key
cache_key = hashlib.md5(content.encode()).hexdigest()
# Check cache
if cache_key in embedding_cache:
return embedding_cache[cache_key]
# Generate embedding
result = genai.embed_content(
model='models/gemini-embedding-2-preview',
content=content,
output_dimensionality=768
)
# Store in cache
embedding_cache[cache_key] = result['embedding']
return result['embedding']
一般的な問題と解決策
問題: 「Invalid API key」(無効なAPIキー)
# Solution: Check your API key
import os
api_key = os.getenv('GEMINI_API_KEY')
if not api_key:
print("API key not set!")
問題: 「Content too long」(コンテンツが長すぎる)
# Solution: Split long text into chunks
def chunk_text(text, max_tokens=8000):
# Simple word-based chunking
words = text.split()
chunks = []
current_chunk = []
for word in words:
current_chunk.append(word)
if len(current_chunk) >= max_tokens:
chunks.append(' '.join(current_chunk))
current_chunk = []
if current_chunk:
chunks.append(' '.join(current_chunk))
return chunks
# Embed each chunk
for chunk in chunk_text(long_text):
embedding = genai.embed_content(
model='models/gemini-embedding-2-preview',
content=chunk
)
問題: 「File processing timeout」(ファイル処理のタイムアウト)
# Solution: Increase wait time for large files
import time
video_file = genai.upload_file(path='large-video.mp4')
max_wait = 300 # 5 minutes
waited = 0
while video_file.state.name == 'PROCESSING' and waited < max_wait:
time.sleep(5)
waited += 5
video_file = genai.get_file(video_file.name)
if video_file.state.name == 'PROCESSING':
print("File processing timeout")
else:
# Generate embedding
result = genai.embed_content(
model='models/gemini-embedding-2-preview',
content=video_file
)
次のステップ
これで、Gemini Embedding 2 APIの使い方がわかりました。次に試すべきことを示します。
- ドキュメント用のセマンティック検索システムを構築する
- マルチモーダルコンテキストでRAGアプリケーションを作成する
- 製品カタログ向けにビジュアル検索を実装する
- ポッドキャストまたは動画コンテンツ向けに音声検索を設定する
- コストを最適化するためにさまざまな次元を試す
APIはシンプルですが、その可能性は無限大です。まずはテキスト埋め込みから始め、ユースケースに応じて画像、動画、音声を活用しましょう。
実装をテストしていますか? Apidogを使用して、Gemini APIエンドポイントのテスト、応答の検証、埋め込みパイプラインテストの自動化を行ってください。
