Google Cloud Vertex Feature StoreGoogle Cloud BigQuery에 있는 데이터를 낮은 지연 시간으로 서빙할 수 있도록 하여, 임베딩에 대한 근사 이웃 검색 기능까지 포함해 ML feature 관리와 온라인 서빙 프로세스를 간소화합니다.
이 튜토리얼은 BigQuery 데이터로부터 직접 저지연 벡터 검색과 근사 최근접 이웃 검색을 손쉽게 수행하는 방법을 보여줍니다. 최소한의 설정으로 강력한 ML 애플리케이션을 구현할 수 있습니다. 우리는 이를 VertexFSVectorStore 클래스를 사용해 진행합니다. 이 클래스는 Google Cloud에서 통합 데이터 스토리지와 유연한 벡터 검색을 제공하는 2가지 클래스 세트의 일부입니다:
  • BigQuery Vector Search: 인프라 설정 없이 빠른 프로토타이핑과 배치 검색에 이상적인 BigQueryVectorStore 클래스.
  • Feature Store Online Store: 수동 또는 예약 데이터 동기화를 통해 저지연 검색을 가능하게 하는 VertexFSVectorStore 클래스. 사용자 지향의 프로덕션 준비 GenAI 애플리케이션에 적합합니다.
Diagram BQ-VertexFS

시작하기

라이브러리 설치

pip install -qU  langchain langchain-google-vertexai "langchain-google-community[featurestore]"
이 Jupyter 런타임에서 새로 설치한 패키지를 사용하려면 런타임을 재시작해야 합니다. 아래 셀을 실행하여 현재 커널을 재시작할 수 있습니다.
import IPython

app = IPython.Application.instance()
app.kernel.do_shutdown(True)

시작 전 준비

프로젝트 ID 설정

프로젝트 ID를 모르는 경우 다음을 시도하세요:
PROJECT_ID = ""  # @param {type:"string"}

# Set the project id
! gcloud config set project {PROJECT_ID}

리전 설정

BigQuery에서 사용하는 REGION 변수도 변경할 수 있습니다. BigQuery 리전에 대해 자세히 알아보세요.
REGION = "us-central1"  # @param {type: "string"}

Dataset 및 Table 이름 설정

이들이 BigQuery Vector Store가 됩니다.
DATASET = "my_langchain_dataset"  # @param {type: "string"}
TABLE = "doc_and_vectors"  # @param {type: "string"}

노트북 환경 인증

  • 이 노트북을 Colab에서 실행 중이라면, 아래 셀의 주석을 해제하고 진행하세요.
  • Vertex AI Workbench를 사용 중이라면, 여기의 설정 안내를 확인하세요.
# from google.colab import auth as google_auth

# google_auth.authenticate_user()

데모: VertexFSVectorStore

Embedding 클래스 인스턴스 생성

프로젝트에서 Vertex AI API를 활성화해야 할 수 있습니다. 다음을 실행하세요: gcloud services enable aiplatform.googleapis.com --project {PROJECT_ID} ({PROJECT_ID}를 프로젝트 이름으로 대체) 어떤 LangChain embeddings 모델이든 사용할 수 있습니다.
from langchain_google_vertexai import VertexAIEmbeddings

embedding = VertexAIEmbeddings(
    model_name="textembedding-gecko@latest", project=PROJECT_ID
)

VertexFSVectorStore 초기화

BigQuery Dataset과 Table은 존재하지 않을 경우 자동으로 생성됩니다. 선택 가능한 모든 매개변수는 클래스 정의에서 확인하세요.
from langchain_google_community import VertexFSVectorStore

store = VertexFSVectorStore(
    project_id=PROJECT_ID,
    dataset_name=DATASET,
    table_name=TABLE,
    location=REGION,
    embedding=embedding,
)

텍스트 추가

참고: 첫 동기화 프로세스는 Feature Online Store 생성으로 인해 약 20분 정도 소요됩니다.
all_texts = ["Apples and oranges", "Cars and airplanes", "Pineapple", "Train", "Banana"]
metadatas = [{"len": len(t)} for t in all_texts]

store.add_texts(all_texts, metadatas=metadatas)
sync_data 메서드를 실행하여 온디맨드로 동기화를 시작할 수도 있습니다.
store.sync_data()
프로덕션 환경에서는 cron_schedule 클래스 매개변수를 사용해 자동 예약 동기화를 설정할 수도 있습니다. 예:
store = VertexFSVectorStore(cron_schedule="TZ=America/Los_Angeles 00 13 11 8 *", ...)

문서 검색

query = "I'd like a fruit."
docs = store.similarity_search(query)
print(docs)

벡터로 문서 검색

query_vector = embedding.embed_query(query)
docs = store.similarity_search_by_vector(query_vector, k=2)
print(docs)

메타데이터 필터로 문서 검색

# This should only return "Banana" document.
docs = store.similarity_search_by_vector(query_vector, filter={"len": 6})
print(docs)

임베딩과 함께 텍스트 추가

add_texts_with_embeddings 메서드를 사용하여 직접 생성한 임베딩을 함께 제공할 수도 있습니다. 이는 임베딩 생성 전에 커스텀 전처리가 필요할 수 있는 멀티모달 데이터에 특히 유용합니다.
items = ["some text"]
embs = embedding.embed(items)

ids = store.add_texts_with_embeddings(
    texts=["some text"], embs=embs, metadatas=[{"len": 1}]
)

BigQuery로 배치 서빙

.to_bq_vector_store() 메서드를 사용하면 간단히 BigQueryVectorStore 객체를 얻을 수 있으며, 이는 배치 사용 사례에 최적화된 성능을 제공합니다. 필수 매개변수는 기존 클래스에서 자동으로 전달됩니다. 사용할 수 있는 모든 매개변수는 클래스 정의에서 확인하세요. .to_vertex_fs_vector_store() 메서드를 사용하면 BigQueryVectorStore로부터 다시 VertexFSVectorStore로 손쉽게 전환할 수 있습니다.
store.to_bq_vector_store()  # pass optional VertexFSVectorStore parameters as arguments

Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I