שימוש ב-Agent Platform Vector Search עם RAG Engine

בדף הזה מוסבר איך לחבר את RAG Engine ל-Gemini Enterprise Agent Platform Vector Search.

אפשר גם לעקוב אחרי ההוראות באמצעות מחברת RAG Engine with Agent Platform חיפוש וקטורי.

הגדרה של חיפוש וקטורי ב-Agent Platform

Agent Platform Vector Search מבוסס על טכנולוגיית חיפוש וקטורי שפותחה על ידי צוות המחקר של Google. בעזרת חיפוש וקטורי אפשר להשתמש באותה תשתית שמספקת בסיס למוצרי Google כמו חיפוש Google,‏ YouTube ו-Google Play.

כדי לבצע שילוב עם RAG Engine, נדרש אינדקס חיפוש וקטורי ריק.

הגדרת Vertex AI SDK

הוראות להגדרה של Vertex AI SDK מופיעות במאמר בנושא הגדרה.

יצירת אינדקס חיפוש וקטורי

כדי ליצור אינדקס של חיפוש וקטורי שתואם ל-RAG Corpus, האינדקס צריך לעמוד בקריטריונים הבאים:

  1. ‫IndexUpdateMethod חייב להיות STREAM_UPDATE, ראו יצירת אינדקס של מקור נתונים.

  2. צריך להגדיר במפורש את סוג מדד המרחק לאחד מהערכים הבאים:

    • DOT_PRODUCT_DISTANCE
    • COSINE_DISTANCE
  3. המימד של הווקטור צריך להיות עקבי עם מודל ההטמעה שמתכננים להשתמש בו במאגר המידע של RAG. אפשר לשנות פרמטרים אחרים בהתאם לבחירות שלכם, והם קובעים אם אפשר לשנות את הפרמטרים הנוספים.

Python

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

def vector_search_create_streaming_index(
    project: str, location: str, display_name: str, gcs_uri: Optional[str] = None
) -> aiplatform.MatchingEngineIndex:
    """Create a vector search index.

    Args:
        project (str): Required. Project ID
        location (str): Required. The region name
        display_name (str): Required. The index display name
        gcs_uri (str): Optional. The Google Cloud Storage uri for index content

    Returns:
        The created MatchingEngineIndex.
    """
    # Initialize the Vertex AI client
    aiplatform.init(project=project, location=location)

    # Create Index
    index = aiplatform.MatchingEngineIndex.create_tree_ah_index(
        display_name=display_name,
        contents_delta_uri=gcs_uri,
        description="Matching Engine Index",
        dimensions=100,
        approximate_neighbors_count=150,
        leaf_node_embedding_count=500,
        leaf_nodes_to_search_percent=7,
        index_update_method="STREAM_UPDATE",  # Options: STREAM_UPDATE, BATCH_UPDATE
        distance_measure_type=aiplatform.matching_engine.matching_engine_index_config.DistanceMeasureType.DOT_PRODUCT_DISTANCE,
    )

    return index

יצירה של נקודת קצה של אינדקס חיפוש וקטורי

מנוע RAG תומך בנקודות קצה ציבוריות.

Python

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

def vector_search_create_index_endpoint(
    project: str, location: str, display_name: str
) -> None:
    """Create a vector search index endpoint.

    Args:
        project (str): Required. Project ID
        location (str): Required. The region name
        display_name (str): Required. The index endpoint display name
    """
    # Initialize the Vertex AI client
    aiplatform.init(project=project, location=location)

    # Create Index Endpoint
    index_endpoint = aiplatform.MatchingEngineIndexEndpoint.create(
        display_name=display_name,
        public_endpoint_enabled=True,
        description="Matching Engine Index Endpoint",
    )

    print(index_endpoint.name)

פריסת אינדקס לנקודת קצה של אינדקס

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

Python

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

def vector_search_deploy_index(
    project: str,
    location: str,
    index_name: str,
    index_endpoint_name: str,
    deployed_index_id: str,
) -> None:
    """Deploy a vector search index to a vector search index endpoint.

    Args:
        project (str): Required. Project ID
        location (str): Required. The region name
        index_name (str): Required. The index to update. A fully-qualified index
          resource name or a index ID.  Example:
          "projects/123/locations/us-central1/indexes/my_index_id" or
          "my_index_id".
        index_endpoint_name (str): Required. Index endpoint to deploy the index
          to.
        deployed_index_id (str): Required. The user specified ID of the
          DeployedIndex.
    """
    # Initialize the Vertex AI client
    aiplatform.init(project=project, location=location)

    # Create the index instance from an existing index
    index = aiplatform.MatchingEngineIndex(index_name=index_name)

    # Create the index endpoint instance from an existing endpoint.
    index_endpoint = aiplatform.MatchingEngineIndexEndpoint(
        index_endpoint_name=index_endpoint_name
    )

    # Deploy Index to Endpoint
    index_endpoint = index_endpoint.deploy_index(
        index=index, deployed_index_id=deployed_index_id
    )

    print(index_endpoint.deployed_indexes)

אם זו הפעם הראשונה שאתם פורסים אינדקס לנקודת קצה של אינדקס, ייקח בערך 30 דקות עד שהקצה העורפי ייבנה ויופעל באופן אוטומטי, ורק אז אפשר יהיה לאחסן את האינדקס. אחרי הפריסה הראשונה, האינדקס מוכן תוך שניות. כדי לראות את סטטוס הפריסה של האינדקס, פותחים את Vector Search Console, בוחרים בכרטיסייה Index endpoints (נקודות קצה של אינדקסים) ובוחרים את נקודת הקצה של האינדקס.

מזהים את שם המשאב של האינדקס ושל נקודת הקצה של האינדקס, בפורמטים הבאים:

  • projects/${PROJECT_NUMBER}/locations/${LOCATION_ID}/indexes/${INDEX_ID}
  • projects/${PROJECT_NUMBER}/locations/${LOCATION_ID}/indexEndpoints/${INDEX_ENDPOINT_ID}.

שימוש בחיפוש וקטורי ב-Agent Platform ב-RAG Engine

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

הגדרת מסד נתונים וקטורי ליצירת מאגר מידע של RAG

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

Python

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Pythonההוראות להגדרה במאמר מדריך למתחילים של Agent Platform באמצעות ספריות לקוח.

כדי לבצע אימות ב-Agent Platform, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

לפני שמריצים דוגמאות קוד, צריך להגדיר את משתנה הסביבה GOOGLE_CLOUD_UNIVERSE_DOMAIN לערך s3nsapis.fr.


import agentplatform
from agentplatform import types

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# vector_search_index_name = "projects/{PROJECT_ID}/locations/{LOCATION}/indexes/{INDEX_ID}"
# vector_search_index_endpoint_name = "projects/{PROJECT_ID}/locations/{LOCATION}/indexEndpoints/{INDEX_ENDPOINT_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)
embedding_model_config = types.RagEmbeddingModelConfig(
    vertex_prediction_endpoint=types.RagEmbeddingModelConfigVertexPredictionEndpoint(
        endpoint="publishers/google/models/text-embedding-005"
    )
)

# Configure Vector DB
vector_db = types.RagVectorDbConfigVertexVectorSearch(
    index=vector_search_index_name,
    index_endpoint=vector_search_index_endpoint_name
)

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

REST

  # TODO(developer): Update and un-comment the following lines:
  # CORPUS_DISPLAY_NAME = "YOUR_CORPUS_DISPLAY_NAME"
  # Full index/indexEndpoint resource name
  # Index: projects/${PROJECT_NUMBER}/locations/${LOCATION_ID}/indexes/${INDEX_ID}
  # IndexEndpoint: projects/${PROJECT_NUMBER}/locations/${LOCATION_ID}/indexEndpoints/${INDEX_ENDPOINT_ID}
  # INDEX_RESOURCE_NAME = "YOUR_INDEX_ENDPOINT_RESOURCE_NAME"
  # INDEX_NAME = "YOUR_INDEX_RESOURCE_NAME"
  # Call CreateRagCorpus API to create a new RagCorpus
  curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" -H "Content-Type: application/json" https://${LOCATION_ID}-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_NUMBER}/locations/${LOCATION_ID}/ragCorpora -d '{
        "display_name" : '\""${CORPUS_DISPLAY_NAME}"\"',
        "rag_vector_db_config" : {
                "vertex_vector_search": {
                  "index":'\""${INDEX_NAME}"\"'
              "index_endpoint":'\""${INDEX_ENDPOINT_NAME}"\"'
                }
          }
    }'

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

ייבוא קבצים באמצעות RAG API

משתמשים בשיטת ragFiles.import API כדי לייבא קבצים מ-Cloud Storage או מ-Google Drive לאינדקס החיפוש הווקטורי. הקבצים מוטמעים ומאוחסנים באינדקס החיפוש הווקטורי.

REST

# TODO(developer): Update and uncomment the following lines:
# RAG_CORPUS_ID = "your-rag-corpus-id"
#
# Cloud de Confiance by S3NS 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_NUMBER}/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_NUMBER}/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.

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

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

REST

# TODO(developer): Update and uncomment the following lines:
# RETRIEVAL_QUERY="your-retrieval-query"
#
# Full RAG corpus resource name
# Format:
# "projects/${PROJECT_NUMBER}/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_NUMBER}/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

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

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_NUMBER}/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,
        "vector_distance_threshold": 0.32
      }
    }
  }
}'

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....
#   ...

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