GoogleGenAIMultimodalDocumentEmbedder

GoogleGenAIMultimodalDocumentEmbedder

GoogleGenAIMultimodalDocumentEmbedder는 비텍스트 문서 리스트의 임베딩을 계산하고 얻은 벡터를 각 문서의 embedding 필드에 저장해요. 텍스트, 이미지, 비디오, 오디오를 같은 벡터 공간에 임베딩할 수 있는 Google AI 멀티모달 임베딩 모델을 사용해요.

출처: 문서

본문

GoogleGenAIMultimodalDocumentEmbedder는 meta 필드에 파일 경로를 담은 문서 리스트를 기대해요. meta 필드는 이 컴포넌트의 file_path_meta_field init 파라미터로 지정할 수 있어요. 임베더가 파일을 효율적으로 로드하고 Google AI 모델로 임베딩을 계산해 각 임베딩을 문서의 embedding 필드에 저장해요.

GoogleGenAIMultimodalDocumentEmbedder는 인덱싱 파이프라인에서 흔히 쓰여요. 검색 시점에는 Embedding Retriever를 사용하기 전에 GoogleGenAITextEmbedder로 같은 모델을 사용해 쿼리를 임베딩해야 해요.

이 컴포넌트는 Gemini 멀티모달 모델(gemini-embedding-2 및 이후 버전)과 호환돼요. 지원되는 모델 전체 목록은 Google AI 문서를 참고하세요. 텍스트 문서를 임베딩하려면 GoogleGenAIDocumentEmbedder를, 문자열을 임베딩하려면 GoogleGenAITextEmbedder를 사용해야 해요.

pip install google-genai-haystack

Authentication ​

Google Gen AI는 Gemini Developer API와 Vertex AI API 모두와 호환돼요. Google AI Studio(Developer API) 또는 Google Cloud > Vertex AI를 참고하세요. 컴포넌트는 기본적으로 GOOGLE_API_KEY 또는 GEMINI_API_KEY 환경 변수를 사용해요. 그렇지 않으면 Secret과 Secret.from_token 정적 메서드로 API 키를 전달할 수 있어요:

embedder = GoogleGenAIMultimodalDocumentEmbedder(
    api_key=Secret.from_token("<your-api-key>"),
)

Gemini Developer API (API Key Authentication) ​

from haystack_integrations.components.embedders.google_genai import (
    GoogleGenAIMultimodalDocumentEmbedder,
)

# set the environment variable (GOOGLE_API_KEY or GEMINI_API_KEY)
embedder = GoogleGenAIMultimodalDocumentEmbedder()

Vertex AI (Application Default Credentials) ​

from haystack_integrations.components.embedders.google_genai import (
    GoogleGenAIMultimodalDocumentEmbedder,
)

# Using Application Default Credentials (requires gcloud auth setup)
embedder = GoogleGenAIMultimodalDocumentEmbedder(
    api="vertex",
    vertex_ai_project="my-project",
    vertex_ai_location="us-central1",
)

Vertex AI (API Key Authentication) ​

from haystack_integrations.components.embedders.google_genai import (
    GoogleGenAIMultimodalDocumentEmbedder,
)

# set the environment variable (GOOGLE_API_KEY or GEMINI_API_KEY)
embedder = GoogleGenAIMultimodalDocumentEmbedder(api="vertex")
  • 대표적인 파이프라인 위치: 인덱싱 파이프라인에서 DocumentWriter 앞
  • 필수 init 변수: api_key — Google API 키. GOOGLE_API_KEY 또는 GEMINI_API_KEY env var로 설정 가능.
  • 필수 run 변수: documents — meta 필드에 이미지 파일 경로를 담은 문서 리스트
  • 출력 변수: documents — 임베딩으로 풍부해진 문서 리스트 / meta — 메타데이터 딕셔너리
  • API reference: Google GenAI
  • 패키지명: google-genai-haystack

Usage ​

On its own ​

Google API 키를 Secret으로 전달하거나 GOOGLE_API_KEY·GEMINI_API_KEY 환경 변수로 설정해야 해요. 아래 예시는 환경 변수를 설정했다고 전제해요.

from haystack import Document
from haystack_integrations.components.embedders.google_genai import (
    GoogleGenAIMultimodalDocumentEmbedder,
)

docs = [
    Document(meta={"file_path": "path/to/image.jpg"}),
    Document(meta={"file_path": "path/to/video.mp4"}),
    Document(meta={"file_path": "path/to/pdf.pdf", "page_number": 1}),
    Document(meta={"file_path": "path/to/pdf.pdf", "page_number": 3}),
]
document_embedder = GoogleGenAIMultimodalDocumentEmbedder()
result = document_embedder.run(documents=docs)
print(result["documents"][0].embedding)
# [0.017020374536514282, -0.023255806416273117, ...]

Setting embedding dimensions ​

gemini-embedding-2 같은 모델은 기본 임베딩 차원이 3072인데, Matryoshka Representation Learning 덕분에 비슷한 성능을 유지하면서 임베딩 크기를 줄일 수 있어요. 자세한 내용은 Google AI 문서를 확인하세요.

from haystack import Document
from haystack_integrations.components.embedders.google_genai import (
    GoogleGenAIMultimodalDocumentEmbedder,
)

docs = [Document(meta={"file_path": "path/to/image.jpg"})]
doc_multimodal_embedder = GoogleGenAIMultimodalDocumentEmbedder(
    config={"output_dimensionality": 768},
)
docs_with_embeddings = doc_multimodal_embedder.run(docs)["documents"]

In a pipeline ​

다음 예시에서 "Scaling Instruction-Finetuned Language Models" 논문(PDF 형식)에서 특정 플롯을 찾아봐요. 먼저 https://arxiv.org/pdf/2210.11416.pdf에서 PDF 파일을 다운로드해야 해요.

from haystack import Document
from haystack import Pipeline
from haystack.document_stores.in_memory import InMemoryDocumentStore
from haystack_integrations.components.embedders.google_genai import (
    GoogleGenAITextEmbedder,
)
from haystack_integrations.components.embedders.google_genai import (
    GoogleGenAIMultimodalDocumentEmbedder,
)
from haystack.components.writers import DocumentWriter
from haystack.components.retrievers.in_memory import InMemoryEmbeddingRetriever

document_store = InMemoryDocumentStore(embedding_similarity_function="cosine")
paper_path = "2210.11416.pdf"
documents = [
    Document(meta={"file_path": paper_path, "page_number": i}) for i in range(1, 16)
]

indexing_pipeline = Pipeline()
indexing_pipeline.add_component("embedder", GoogleGenAIMultimodalDocumentEmbedder())
indexing_pipeline.add_component("writer", DocumentWriter(document_store=document_store))
indexing_pipeline.connect("embedder", "writer")
indexing_pipeline.run({"embedder": {"documents": documents}})

query_pipeline = Pipeline()
query_pipeline.add_component("text_embedder", GoogleGenAITextEmbedder())
query_pipeline.add_component(
    "retriever",
    InMemoryEmbeddingRetriever(document_store=document_store),
)
query_pipeline.connect("text_embedder.embedding", "retriever.query_embedding")
query = "plot showing BBH accuracy"
result = query_pipeline.run({"text_embedder": {"text": query}})
print(result["retriever"]["documents"][0].meta)
# {'file_path': '2210.11416.pdf', 'page_number': 9}