AmazonBedrockDocumentEmbedder

AmazonBedrockDocumentEmbedder

Amazon Bedrock API의 모델로 문서의 임베딩을 계산하는 컴포넌트예요.

파이프라인에서 가장 흔한 위치: 인덱싱 파이프라인에서 DocumentWriter 앞 필수 init 변수: model(사용할 임베딩 모델), aws_access_key_id(AWS_ACCESS_KEY_ID 환경 변수로 설정 가능), aws_secret_access_key(AWS_SECRET_ACCESS_KEY 환경 변수로 설정 가능), aws_region_name(AWS_DEFAULT_REGION 환경 변수로 설정 가능) 필수 run 변수: documents — 임베딩할 문서 목록 출력 변수: documents — 임베딩이 추가된 문서 목록 API reference: Amazon Bedrock GitHub link: https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/amazon_bedrock Package name: amazon-bedrock-haystack

출처: 문서

본문

Overview

Amazon Bedrock은 선도 AI 스타트업과 Amazon의 언어 모델을 통합 API로 사용할 수 있게 해주는 완전 관리형 서비스예요.

Amazon Titan과 Cohere 임베딩 모델이 지원됩니다. 예를 들어 amazon.titan-embed-text-v1, amazon.titan-embed-text-v2:0, amazon.titan-embed-image-v1, cohere.embed-english-v3, cohere.embed-multilingual-v3, cohere.embed-v4:0 등이 있죠. 지원되는 모든 모델을 보려면 Amazon Bedrock 문서에서 "embedding"으로 필터하고 Amazon Titan과 Cohere 시리즈 모델을 선택하세요.

Batch Inference 배치 추론을 지원하는 것은 Cohere 모델뿐이라는 점을 기억하세요 — 같은 요청으로 더 많은 문서의 임베딩을 계산하는 방식이죠.

이 컴포넌트는 문서 목록을 임베딩할 때 사용해야 해요. 문자열을 임베딩하려면 AmazonBedrockTextEmbedder를 사용하세요.

Authentication

AmazonBedrockDocumentEmbedder는 인증에 AWS를 사용해요. 자격 증명을 컴포넌트에 파라미터로 직접 제공하거나, AWS CLI를 쓰고 IAM으로 인증할 수 있습니다. IAM 아이덴티티 기반 정책을 설정하는 방법은 공식 문서를 참고하세요. AmazonBedrockDocumentEmbedder를 초기화하고 자격 증명을 제공해 인증하려면 model 이름과 aws_access_key_id, aws_secret_access_key, aws_region_name을 제공하세요. 나머지 파라미터는 선택이에요. API reference에서 확인할 수 있습니다.

Model-specific parameters

Haystack이 통합 인터페이스를 제공하더라도 Bedrock이 제공하는 각 모델은 특정 파라미터를 받아들일 수 있어요. 이 파라미터들을 초기화 때 전달할 수 있습니다.

예를 들어 Cohere 모델은 Bedrock 문서에서 볼 수 있듯 input_type과 truncate를 지원해요.

from haystack_integrations.components.embedders.amazon_bedrock import (
    AmazonBedrockDocumentEmbedder,
)

embedder = AmazonBedrockDocumentEmbedder(
    model="cohere.embed-english-v3",
    input_type="search_document",
    truncate="LEFT",
)

Embedding Metadata

텍스트 문서에는 보통 메타데이터가 따라와요. 메타데이터가 구별적이고 의미적으로 가치 있다면, 문서 텍스트와 함께 임베딩하면 검색 품질을 높일 수 있어요.

Document Embedder로 쉽게 할 수 있습니다:

from haystack import Document
from haystack_integrations.components.embedders.amazon_bedrock import (
    AmazonBedrockDocumentEmbedder,
)

doc = Document(content="some text", meta={"title": "relevant title", "page number": 18})
embedder = AmazonBedrockDocumentEmbedder(
    model="cohere.embed-english-v3",
    meta_fields_to_embed=["title"],
)
docs_w_embeddings = embedder.run(documents=[doc])["documents"]

Usage

Installation

AmazonBedrockDocumentEmbedder를 쓰려면 amazon-bedrock-haystack 패키지를 설치해야 해요:

pip install amazon-bedrock-haystack

On its own

기본 사용법:

import os
from haystack import Document
from haystack_integrations.components.embedders.amazon_bedrock import (
    AmazonBedrockDocumentEmbedder,
)

os.environ["AWS_ACCESS_KEY_ID"] = "..."
os.environ["AWS_SECRET_ACCESS_KEY"] = "..."
os.environ["AWS_DEFAULT_REGION"] = "us-east-1"  # just an example

doc = Document(content="I love pizza!")
embedder = AmazonBedrockDocumentEmbedder(
    model="cohere.embed-english-v3",
    input_type="search_document",
)
result = embedder.run(documents=[doc])
print(result["documents"][0].embedding)
# [0.017020374536514282, -0.023255806416273117, ...]

In a pipeline

RAG 파이프라인에서:

from haystack import Document, Pipeline
from haystack.document_stores.in_memory import InMemoryDocumentStore
from haystack_integrations.components.embedders.amazon_bedrock import (
    AmazonBedrockDocumentEmbedder,
    AmazonBedrockTextEmbedder,
)
from haystack.components.retrievers.in_memory import InMemoryEmbeddingRetriever
from haystack.components.writers import DocumentWriter

document_store = InMemoryDocumentStore(embedding_similarity_function="cosine")
documents = [
    Document(content="My name is Wolfgang and I live in Berlin"),
    Document(content="I saw a black horse running"),
    Document(content="Germany has many big cities"),
]

indexing_pipeline = Pipeline()
indexing_pipeline.add_component(
    "embedder",
    AmazonBedrockDocumentEmbedder(model="cohere.embed-english-v3"),
)
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",
    AmazonBedrockTextEmbedder(model="cohere.embed-english-v3"),
)
query_pipeline.add_component(
    "retriever",
    InMemoryEmbeddingRetriever(document_store=document_store),
)
query_pipeline.connect("text_embedder.embedding", "retriever.query_embedding")

query = "Who lives in Berlin?"
result = query_pipeline.run({"text_embedder": {"text": query}})
print(result["retriever"]["documents"][0])
# Document(id=..., content: 'My name is Wolfgang and I live in Berlin')

더 알아보기 (Learn more)

🧑‍🍳 쿡북: PDF-Based Question Answering with Amazon Bedrock and Haystack