Weaviate 임베딩: 텍스트 임베딩

Weaviate 임베딩: 텍스트 임베딩

Weaviate 벡터 인덱스를 Weaviate Embeddings 모델로 구성하면, Weaviate가 지정한 모델과 API 키로 여러 작업의 임베딩을 자동 생성해요. 이 기능을 벡터라이저(vectorizer) 라고 합니다. 데이터를 가져올 때는 텍스트 객체 임베딩을 만들어 인덱스에 저장하고, 벡터/하이브리드 검색을 할 때는 텍스트 쿼리를 임베딩으로 변환합니다. 이 기능은 Weaviate Cloud 전용이에요.

출처: 공식문서

사전 준비

Weaviate Embeddings를 쓰려면 Weaviate Embeddings를 지원하는 클라이언트 라이브러리가 있는 Weaviate Cloud 인스턴스가 필요합니다. 셀프호스트 사용자는 Weaviate Embeddings 벡터라이저를 쓸 수 없어요. 인증은 Weaviate Cloud 자격 증명으로 자동 처리됩니다.

import weaviate
from weaviate.classes.init import Auth
import os

# Best practice: store your credentials in environment variables
weaviate_url = os.getenv("WEAVIATE_URL")
weaviate_key = os.getenv("WEAVIATE_API_KEY")

client = weaviate.connect_to_weaviate_cloud(
    cluster_url=weaviate_url,  # Weaviate URL: "REST Endpoint" in Weaviate Cloud console
    auth_credentials=Auth.api_key(weaviate_key),  # Weaviate API key: "ADMIN" API key in Weaviate Cloud console
)
print(client.is_ready())  # Should print: `True`

# Work with Weaviate
client.close()

Weaviate 인덱스 구성

미리 정의된 모델(text2vec-weaviate)을 사용하려면 다음과 같이 컬렉션을 구성합니다.

from weaviate.classes.config import Configure

client.collections.create(
    "DemoCollection",
    vector_config=[
        Configure.Vectors.text2vec_weaviate(
            name="title_vector",
            source_properties=["title"]
        )
    ],
    # Additional parameters not shown
)

사용할 모델을 명시해서 지정할 수도 있어요. 모델을 지정하지 않으면 기본 모델이 사용됩니다.

from weaviate.classes.config import Configure

client.collections.create(
    "DemoCollection",
    vector_config=[
        Configure.Vectors.text2vec_weaviate(
            name="title_vector",
            source_properties=["title"],
            model="Snowflake/snowflake-arctic-embed-l-v2.0"
        )
    ],
    # Additional parameters not shown
)

벡터라이저 파라미터

  • model (선택): 임베딩 생성에 사용할 모델 이름
  • dimensions (선택): 생성될 임베딩의 차원 수
  • base_url (선택): Weaviate Embeddings 서비스의 기본 URL (대부분의 경우 불필요)
from weaviate.classes.config import Configure

client.collections.create(
    "DemoCollection",
    vector_config=[
        Configure.Vectors.text2vec_weaviate(
            name="title_vector",
            source_properties=["title"],
            model="Snowflake/snowflake-arctic-embed-m-v1.5",
            # Further options
            # dimensions=256
            # base_url="<custom_weaviate_embeddings_url>",
        )
    ],
    # Additional parameters not shown
)

벡터화 동작 방식

Weaviate는 컬렉션 구성과 정해진 규칙에 따라 객체를 벡터화합니다. 컬렉션 정의에서 달리 지정하지 않으면 기본 동작은 다음과 같아요.

  • text 또는 text[] 데이터 타입 속성만 벡터화 (건너뛰기로 설정된 속성 제외)
  • 값을 이어 붙이기 전에 속성을 알파벳(a-z) 순으로 정렬
  • vectorizePropertyNametrue면(기본 false) 각 속성 값 앞에 속성 이름을 붙임
  • (앞에 붙인) 속성 값을 공백으로 연결
  • vectorizeClassNamefalse가 아니면 클래스 이름을 앞에 붙임
  • 생성된 문자열을 소문자로 변환

데이터 가져오기

벡터라이저를 구성한 뒤 데이터를 가져오면 Weaviate가 지정한 모델로 텍스트 객체의 임베딩을 생성합니다.

source_objects = [
    {"title": "The Shawshank Redemption", "description": "A wrongfully imprisoned man forms an inspiring friendship while finding hope and redemption in the darkest of places."},
    {"title": "The Godfather", "description": "A powerful mafia family struggles to balance loyalty, power, and betrayal in this iconic crime saga."},
    {"title": "The Dark Knight", "description": "Batman faces his greatest challenge as he battles the chaos unleashed by the Joker in Gotham City."},
    {"title": "Jingle All the Way", "description": "A desperate father goes to hilarious lengths to secure the season's hottest toy for his son on Christmas Eve."},
    {"title": "A Christmas Carol", "description": "A miserly old man is transformed after being visited by three ghosts on Christmas Eve in this timeless tale of redemption."}
]

collection = client.collections.use("DemoCollection")
with collection.batch.fixed_size(batch_size=200) as batch:
    for src_obj in source_objects:
        # The model provider integration will automatically vectorize the object
        batch.add_object(
            properties={
                "title": src_obj["title"],
                "description": src_obj["description"],
            },
            # vector=vector  # Optionally provide a pre-obtained vector
        )
    if batch.number_errors > 10:
        print("Batch import stopped due to excessive errors.")
        break

failed_objects = collection.batch.failed_objects
if failed_objects:
    print(f"Number of failed imports: {len(failed_objects)}")
    print(f"First failed object: {failed_objects[0]}")

검색하기

벡터 검색

벡터 검색을 수행하면 Weaviate가 텍스트 쿼리를 지정한 모델로 임베딩으로 변환하고, 데이터베이스에서 가장 유사한 객체를 반환합니다. 아래 쿼리는 limit으로 지정한 n개의 가장 유사한 객체를 돌려줘요.

collection = client.collections.use("DemoCollection")
response = collection.query.near_text(
    query="A holiday film",  # The model provider integration will automatically vectorize the query
    limit=2,
)
for obj in response.objects:
    print(obj.properties["title"])

하이브리드 검색

하이브리드 검색은 벡터 검색과 키워드(BM25) 검색을 수행한 뒤 결과를 결합해 가장 잘 맞는 객체를 반환해요. 역시 텍스트 쿼리를 지정한 모델로 임베딩으로 변환합니다.

collection = client.collections.use("DemoCollection")
response = collection.query.hybrid(
    query="A holiday film",  # The model provider integration will automatically vectorize the query
    limit=2,
)
for obj in response.objects:
    print(obj.properties["title"])

사용 가능한 모델

  • Snowflake/snowflake-arctic-embed-l-v2.0: 5억 6800만 파라미터, 1024차원의 다국어 엔터프라이즈 검색 모델. Matryoshka Representation Learning으로 학습해 벡터 차원을 줄여도 손실이 적어요. 스칼라 양자화 + 256차원으로 양자화 없이 풀프리시전 성능의 99%를 유지합니다. 허용 dimensions: 1024(기본), 256
  • Snowflake/snowflake-arctic-embed-m-v1.5: 1억 900만 파라미터, 768차원의 영어 엔터프라이즈 검색 모델. 역시 Matryoshka 학습 기반이며 양자화 친화적입니다. 허용 dimensions: 768(기본), 256

입력 절단

현재 모델의 컨텍스트 윈도우를 초과하는 입력은 오른쪽(입력의 끝)에서 잘립니다.

기존 벡터 재사용하기

이미 호환 가능한 모델 벡터를 갖고 있다면 Weaviate에 직접 제공할 수 있어요. 같은 모델로 이미 임베딩을 생성해 두었고, 다른 시스템에서 데이터를 마이그레이션해 오는 상황 등에서 유용합니다.

더 알아보기 (Learn more)