שימוש ב-Vertex AI Feature Store ב-RAG Engine

בדף הזה מוסבר איך להגדיר את Vertex AI Feature Store כמסד הנתונים הווקטורי לשימוש עם RAG Engine.

אפשר גם לעקוב באמצעות מחברת RAG Engine עם Vertex AI Feature Store.

שילוב של Vertex AI Feature Store כמסד נתונים וקטורי נוסף מאפשר ל-RAG Engine להשתמש ב-Vertex AI Feature Store כדי לטפל בכמויות גדולות של נתונים עם חביון נמוך, וכך לשפר את הביצועים והמדרגיות של אפליקציות RAG.

הגדרה של Vertex AI Feature Store

‫Vertex AI Feature Store, שירות מנוהל מבוסס-ענן, הוא רכיב חיוני ב-Gemini Enterprise Agent Platform. הוא מפשט את הניהול של תכונות למידת מכונה (ML) ואת ההצגה שלהן באינטרנט, כי הוא מאפשר לכם לנהל את נתוני התכונות בטבלה או בתצוגה ב-BigQuery. כך אפשר להציג תכונות אונליין עם זמן אחזור נמוך.

בFeatureOnlineStoreמקרים שבהם נוצרו מופעים עם אופטימיזציה להצגה באינטרנט, אפשר להשתמש בחיפוש דמיון וקטורי כדי לאחזר רשימה של ישויות דומות או קשורות מבחינה סמנטית, שנקראות שכנים קרובים משוערים.

בקטעים הבאים מוסבר איך להגדיר מופע של Vertex AI Feature Store לאפליקציית RAG.

יצירת סכימת טבלה ב-BigQuery

משתמשים במסוף Google Cloud כדי ליצור סכימת טבלה ב-BigQuery. הוא צריך לכלול את השדות הבאים כדי לשמש כמקור נתונים.

שם השדה סוג נתונים סטטוס
corpus_id String חובה
file_id String חובה
chunk_id String חובה
chunk_data_type String ניתן לאתחול ל-null
chunk_data String ניתן לאתחול ל-null
file_original_uri String ניתן לאתחול ל-null
embeddings Float שדה

בדוגמת הקוד הזו אפשר לראות איך מגדירים את סכימת הטבלה ב-BigQuery.

SQL

  CREATE TABLE `PROJECT_ID.input_us_central1.rag_source_new` (
    `corpus_id` STRING NOT NULL,
    `file_id` STRING NOT NULL,
    `chunk_id` STRING NOT NULL,
    `chunk_data_type` STRING,
    `chunk_data` STRING,
    `embeddings` ARRAY<FLOAT64>,
    `file_original_uri` STRING
  );

הקצאת הרשאות ידנית למכונה של FeatureOnlineStore

כדי להפעיל את האפשרות להצגת תכונות אונליין, צריך להשתמש ב-Vertex AI Feature Store CreateFeatureOnlineStore API כדי להגדיר מופע של FeatureOnlineStore. אם אתם מקצים FeatureOnlineStore בפעם הראשונה, יכול להיות שהפעולה תימשך כחמש דקות.

REST

כדי ליצור מכונה של חנות אונליין, שולחים בקשת POST באמצעות ה-method‏ featureOnlineStores.create.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • LOCATION_ID: האזור שבו רוצים ליצור את מופע FeatureOnlineStore, לדוגמה us-central1.
  • PROJECT_ID: מזהה הפרויקט.
  • FEATUREONLINESTORE_NAME: השם של מופע FeatureOnlineStore חדש.

ה-method של ה-HTTP וכתובת ה-URL:

POST https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featureOnlineStores?feature_online_store_id=FEATUREONLINESTORE_NAME

גוף בקשת JSON:

{
  "optimized": {}
}

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featureOnlineStores?feature_online_store_id=FEATUREONLINESTORE_NAME"

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featureOnlineStores?feature_online_store_id=FEATUREONLINESTORE_NAME" | Select-Object -Expand Content

אתם אמורים לקבל תגובת JSON שדומה לזו:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION_ID/featureOnlineStores/FEATUREONLINESTORE_NAME/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.aiplatform.v1.CreateFeatureOnlineStoreOperationMetadata",
    "genericMetadata": {
      "createTime": "2023-09-18T17:49:23.847496Z",
      "updateTime": "2023-09-18T17:49:23.847496Z"
    }
  }
}

Python

במאמר התקנת Vertex AI SDK ל-Python מוסבר איך להתקין או לעדכן את Vertex AI SDK ל-Python. מידע נוסף מופיע ב מאמרי העזרה של Python API.


from google.cloud import aiplatform
from vertexai.resources.preview import feature_store


def create_optimized_public_feature_online_store_sample(
    project: str,
    location: str,
    feature_online_store_id: str,
):
    aiplatform.init(project=project, location=location)
    fos = feature_store.FeatureOnlineStore.create_optimized_store(
        feature_online_store_id
    )
    return fos

  • project: מזהה הפרויקט.
  • location: האזור שבו רוצים ליצור את מופע FeatureOnlineStore, לדוגמה us-central1.
  • feature_online_store_id: השם של מופע FeatureOnlineStore חדש.

יצירת משאב FeatureView

כדי לקשר את הטבלה ב-BigQuery, שבה מאוחסן מקור הנתונים של התכונות, למופע FeatureOnlineStore, קוראים ל-CreateFeatureView API כדי ליצור משאב FeatureView. כשיוצרים משאב FeatureView, בוחרים את מדד המרחק שמוגדר כברירת מחדל DOT_PRODUCT_DISTANCE, שהוא הערך השלילי של המכפלה הסקלרית (ערך DOT_PRODUCT_DISTANCE קטן יותר מציין דמיון גבוה יותר).

בדוגמת הקוד הזו אפשר לראות איך יוצרים משאב FeatureView.

REST

  # TODO(developer): Update and uncomment the following lines:
  # Set feature_view_id
  # Example: "feature_view_test"
  # FEATURE_VIEW_ID = "your-feature-view-id"
  #
  # The big_query_uri generated in the above BigQuery table schema creation step
  # The format should be "bq://" + BigQuery table ID
  # Example: "bq://tester.ragtest1.rag_testdata"
  # BIG_QUERY_URI=YOUR_BIG_QUERY_URI

  # Call CreateFeatureView API to create a FeatureView
  curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" -H "Content-Type: application/json" \
  https://us-central1-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/us-central1/featureOnlineStores/${FEATURE_ONLINE_STORE_ID}/featureViews?feature_view_id=${FEATURE_VIEW_ID} \
    -d '{
          "vertex_rag_source": {
            "uri": '\""${BIG_QUERY_URI}"\"'
          }
      }'

  # Call ListFeatureViews API to verify the FeatureView is created successfully
  curl -X GET -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" -H "Content-Type: application/json" https://us-central1-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/us-central1/featureOnlineStores/${FEATURE_ONLINE_STORE_ID}/featureViews

Python

במאמר התקנת Vertex AI SDK ל-Python מוסבר איך להתקין או לעדכן את Vertex AI SDK ל-Python. מידע נוסף מופיע ב מאמרי העזרה של Python API.


from google.cloud import aiplatform
from vertexai.resources.preview import feature_store


def create_feature_view_from_rag_source(
    project: str,
    location: str,
    existing_feature_online_store_id: str,
    feature_view_id: str,
    bq_table_uri: str,
):
    aiplatform.init(project=project, location=location)
    fos = feature_store.FeatureOnlineStore(existing_feature_online_store_id)
    fv = fos.create_feature_view(
        name=feature_view_id,
        source=feature_store.utils.FeatureViewVertexRagSource(uri=bq_table_uri),
    )
    return fv

העלאת נתונים והצגה אונליין

ממשק ה-API של RAG מטפל בהעלאת נתונים ובהצגתם באינטרנט. מידע נוסף על RAG Engine ב-Gemini Enterprise Agent Platform API

שימוש ב-Vertex AI Feature Store ב-RAG Engine

אחרי שמגדירים את המופע של Vertex AI Feature Store, בקטעים הבאים מוסבר איך להגדיר אותו כמסד הנתונים הווקטורי לשימוש עם אפליקציית RAG.

שימוש במופע של Vertex AI Feature Store כמסד נתונים וקטורי ליצירת קורפוס RAG

כדי ליצור את מאגר המידע של RAG, צריך להשתמש ב-FEATURE_VIEW_RESOURCE_NAME. מאגר המידע של RAG נוצר ומשויך אוטומטית למופע של Vertex AI Feature Store. ממשקי RAG API משתמשים ב-rag_corpus_id שנוצר כדי לטפל בהעלאת הנתונים למופע של Vertex AI Feature Store וכדי לאחזר הקשרים רלוונטיים מ-rag_corpus_id.

בדוגמת הקוד הזו נדגים איך להשתמש במופע של Vertex AI Feature Store כמסד נתונים וקטורי כדי ליצור מאגר מידע של RAG.

REST

# TODO(developer): Update and uncomment the following lines:
# CORPUS_DISPLAY_NAME = "your-corpus-display-name"
#
# Full feature view resource name
# Format: projects/${PROJECT_ID}/locations/us-central1/featureOnlineStores/${FEATURE_ONLINE_STORE_ID}/featureViews/${FEATURE_VIEW_ID}
# FEATURE_VIEW_RESOURCE_NAME = "your-feature-view-resource-name"

# Call CreateRagCorpus API to create a new RAG corpus
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
  https://us-central1-aiplatform.googleapis.com/v1beta1/projects/{PROJECT_ID}/locations/us-central1/ragCorpora -d '{
    "display_name" : '\""${CORPUS_DISPLAY_NAME}"\"',
    "rag_vector_db_config" : {
      "vertex_feature_store": {
        "feature_view_resource_name":'\""${FEATURE_VIEW_RESOURCE_NAME}"\"'
      }
    }
  }'

# Call ListRagCorpora API to verify the RAG corpus is created successfully
curl -sS -X GET \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://us-central1-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/us-central1/ragCorpora"

Python

במאמר התקנת Vertex AI SDK ל-Python מוסבר איך להתקין או לעדכן את Vertex AI SDK ל-Python. מידע נוסף מופיע ב מאמרי העזרה של Python API.


import agentplatform
from agentplatform import types

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# feature_view_name = "projects/{PROJECT_ID}/locations/{LOCATION}/featureOnlineStores/{FEATURE_ONLINE_STORE_ID}/featureViews/{FEATURE_VIEW_ID}"
# display_name = "test_corpus"
# description = "Corpus Description"

# Initialize Agent Platform client once per session
client = agentplatform.Client(project=PROJECT_ID, location="us-central1")

# Configure embedding model (Optional)
backend_config = types.RagVectorDbConfig(
    rag_embedding_model_config=types.RagEmbeddingModelConfig(
        vertex_prediction_endpoint=types.RagEmbeddingModelConfigVertexPredictionEndpoint(
            endpoint="publishers/google/models/text-embedding-005"
        ),
    ),
    vertex_feature_store=types.RagVectorDbConfigVertexFeatureStore(
        feature_view_resource_name=feature_view_name
    )
)

corpus = client.rag.create_corpus(
    rag_corpus=types.RagCorpus(
        display_name=display_name,
        description=description,
        rag_vector_db_config=backend_config,
    )
)
print(corpus)
# Example response:
# RagCorpus(name='projects/1234567890/locations/us-central1/ragCorpora/1234567890',
# display_name='test_corpus', description='Corpus Description', embedding_model_config=...
# ...

ייבוא קבצים לטבלה ב-BigQuery באמצעות RAG API

משתמשים ב-ImportRagFiles API כדי לייבא קבצים מ- Google Cloud Storage או מ-Google Drive לטבלת BigQuery של מופע Vertex AI Feature Store. הקבצים מוטמעים ומאוחסנים בטבלה ב-BigQuery.

בדוגמת הקוד הזו אפשר לראות איך מייבאים קבצים לטבלת BigQuery באמצעות RAG API.

REST

# TODO(developer): Update and uncomment the following lines:
# RAG_CORPUS_ID = "your-rag-corpus-id"
#
# Google Cloud Storage bucket/file location.
# For example, "gs://rag-fos-test/"
# GCS_URIS= "your-gcs-uris"

# Call ImportRagFiles API to embed files and store in the BigQuery table
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://us-central1-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/us-central1/ragCorpora/${RAG_CORPUS_ID}/ragFiles:import \
-d '{
  "import_rag_files_config": {
    "gcs_source": {
      "uris": '\""${GCS_URIS}"\"'
    },
    "rag_file_chunking_config": {
      "chunk_size": 512
    }
  }
}'

# Call ListRagFiles API to verify the files are imported successfully
curl -X GET \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
https://us-central1-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/us-central1/ragCorpora/${RAG_CORPUS_ID}/ragFiles

Python

במאמר התקנת Vertex AI SDK ל-Python מוסבר איך להתקין או לעדכן את Vertex AI SDK ל-Python. מידע נוסף מופיע ב מאמרי העזרה של Python API.


import agentplatform
from agentplatform import types

from google.genai import types as genai_types

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# corpus_name = "projects/{PROJECT_ID}/locations/us-central1/ragCorpora/{rag_corpus_id}"

# Supports Google Cloud Storage and Google Drive Links
# paths = ["https://drive.google.com/file/d/123", "gs://my_bucket/my_files_dir/*"]

# Initialize Agent Platform client once per session
client = agentplatform.Client(project=PROJECT_ID, location="us-central1")

response = client.rag.import_files(
    name=corpus_name,
    import_config=types.ImportRagFilesConfig(
        gcs_source=genai_types.GcsSource(uris=[paths[1]]),
        google_drive_source=types.GoogleDriveSource(
            resource_ids=[
                types.GoogleDriveSourceResourceId(
                    resource_id=paths[0],
                    resource_type=types.ResourceType.RESOURCE_TYPE_FILE
                )
            ]
        ), # optional
        rag_file_transformation_config=types.RagFileTransformationConfig(
            rag_file_chunking_config=types.RagFileChunkingConfig(
                chunk_size=512,
                chunk_overlap=100,
            )
        ), # optional
        max_embedding_requests_per_min=900, # optional
    )
)

print(f"Imported {response.imported_rag_files_count} files.")
# Example response:
# Imported 2 files.

מריצים תהליך סנכרון כדי ליצור אינדקס של FeatureOnlineStore

אחרי שמעלים את הנתונים לטבלת BigQuery, מפעילים תהליך סנכרון כדי שהנתונים יהיו זמינים להצגה באינטרנט. צריך ליצור אינדקס FeatureOnlineStore באמצעות FeatureView, ותהליך הסנכרון עשוי להימשך 20 דקות.

בדוגמת הקוד הזו אפשר לראות איך מריצים תהליך סנכרון כדי ליצור אינדקס FeatureOnlineStore.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • LOCATION_ID: האזור שבו נמצאת חנות האונליין, למשל us-central1.
  • PROJECT_ID: מזהה הפרויקט.
  • FEATUREONLINESTORE_NAME: השם של החנות אונליין שמכילה את תצוגת התכונות.
  • FEATUREVIEW_NAME: השם של תצוגת התכונות שבה רוצים להתחיל את סנכרון הנתונים באופן ידני.

ה-method של ה-HTTP וכתובת ה-URL:

POST https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featureOnlineStores/FEATUREONLINESTORE_NAME/featureViews/FEATUREVIEW_NAME:sync

כדי לשלוח את הבקשה אתם צריכים לבחור אחת מהאפשרויות הבאות:

curl

מריצים את הפקודה הבאה:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d "" \
"https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featureOnlineStores/FEATUREONLINESTORE_NAME/featureViews/FEATUREVIEW_NAME:sync"

PowerShell

מריצים את הפקודה הבאה:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-Uri "https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/featureOnlineStores/FEATUREONLINESTORE_NAME/featureViews/FEATUREVIEW_NAME:sync" | Select-Object -Expand Content

אתם אמורים לקבל תגובת JSON שדומה לזו:

{
  "featureViewSync": "projects/PROJECT_ID/locations/LOCATION_ID/featureOnlineStores/FEATUREONLINESTORE_NAME/featureViews/FEATUREVIEW_NAME/featureViewSyncs/OPERATION_ID"
}

אחזור הקשרים רלוונטיים באמצעות RAG API

אחרי שתהליך הסנכרון יסתיים, תוכלו לאחזר הקשרים רלוונטיים ממדד FeatureOnlineStore באמצעות RetrieveContexts API.

REST

# TODO(developer): Update and uncomment the following lines:
# RETRIEVAL_QUERY="your-retrieval-query"
#
# Full RAG corpus resource name
# Format:
# "projects/${PROJECT_ID}/locations/us-central1/ragCorpora/${RAG_CORPUS_ID}"
# RAG_CORPUS_RESOURCE="your-rag-corpus-resource"

# Call RetrieveContexts API to retrieve relevant contexts
curl -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
https://us-central1-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/us-central1:retrieveContexts \
  -d '{
    "vertex_rag_store": {
      "rag_resources": {
          "rag_corpus": '\""${RAG_CORPUS_RESOURCE}"\"',
        },
    },
    "query": {
      "text": '\""${RETRIEVAL_QUERY}"\"',
      "similarity_top_k": 10
    }
  }'

Python

במאמר התקנת Vertex AI SDK ל-Python מוסבר איך להתקין או לעדכן את Vertex AI SDK ל-Python. מידע נוסף מופיע ב מאמרי העזרה של Python API.


import agentplatform

from agentplatform import types
from google.genai import types as genai_types

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# corpus_name = "projects/[PROJECT_ID]/locations/us-central1/ragCorpora/[rag_corpus_id]"

# Initialize Agent Platform client once per session
client = agentplatform.Client(project=PROJECT_ID, location="us-east4")

response = client.rag.retrieve_contexts(
    vertex_rag_store=genai_types.VertexRagStore(
        rag_resources=[
            genai_types.VertexRagStoreRagResource(
                rag_corpus=corpus_name,
                # Optional: supply IDs from `rag.list_files()`.
                # rag_file_ids=["rag-file-1", "rag-file-2", ...],
            )
        ],
    ),
    query=types.RagQuery(
        text="Hello World!",
        rag_retrieval_config=genai_types.RagRetrievalConfig(
            top_k=10,
            filter=genai_types.RagRetrievalConfigFilter(
                vector_distance_threshold=0.5
            ),
        ),
    )
)
print(response)
# Example response:
# contexts {
#   contexts {
#     source_uri: "gs://your-bucket-name/file.txt"
#     text: "....
#   ....

יצירת תוכן באמצעות Agent Platform Gemini API

קוראים ל-Agent Platform GenerateContent API כדי להשתמש במודלים של Gemini ליצירת תוכן, ומציינים RAG_CORPUS_RESOURCE בבקשה כדי לאחזר נתונים מהאינדקס FeatureOnlineStore.

REST

# TODO(developer): Update and uncomment the following lines:
# MODEL_ID=gemini-2.5-flash
# GENERATE_CONTENT_PROMPT="your-generate-content-prompt"

# GenerateContent with contexts retrieved from the FeatureStoreOnline index
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json"  https://us-central1-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/us-central1/publishers/google/models/${MODEL_ID}:generateContent \
-d '{
  "contents": {
    "role": "user",
    "parts": {
      "text": '\""${GENERATE_CONTENT_PROMPT}"\"'
    }
  },
  "tools": {
    "retrieval": {
      "vertex_rag_store": {
        "rag_resources": {
            "rag_corpus": '\""${RAG_CORPUS_RESOURCE}"\"',
          },
        "similarity_top_k": 8,
      }
    }
  }
}'

Python

במאמר התקנת Vertex AI SDK ל-Python מוסבר איך להתקין או לעדכן את Vertex AI SDK ל-Python. מידע נוסף מופיע ב מאמרי העזרה של Python API.


from google import genai
from google.genai import types as genai_types

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# corpus_name = "projects/{PROJECT_ID}/locations/us-central1/ragCorpora/{rag_corpus_id}"

rag_retrieval_tool = genai_types.Tool(
    retrieval=genai_types.Retrieval(
        vertex_rag_store=genai_types.VertexRagStore(
            rag_resources=[
                genai_types.VertexRagStoreRagResource(
                    rag_corpus=corpus_name
                )
            ],
            rag_retrieval_config=genai_types.RagRetrievalConfig(
                top_k=10,
                filter=genai_types.RagRetrievalConfigFilter(
                    vector_distance_threshold=0.5
                ),
            ),
        ),
    )
)

# Create a GenAI SDK client to make a generate_content request
genai_client = genai.Client(enterprise=True, project=PROJECT_ID, location="us-central1")

response = genai_client.models.generate_content(
    model="gemini-2.5-pro",
    contents="Why is the sky blue?",
    config=genai_types.GenerateContentConfig(
        tools=[rag_retrieval_tool]
    )
)
print(response.text)
# Example response:
#   The sky appears blue due to a phenomenon called Rayleigh scattering.
#   Sunlight, which contains all colors of the rainbow, is scattered
#   by the tiny particles in the Earth's atmosphere....
#   ...

המאמרים הבאים