שימוש בחיפוש בסוכן כקצה עורפי לאחזור באמצעות מנוע RAG

בדף הזה מוסבר איך לשלב את Agent Search עם RAG Engine.

‫Agent Search הוא פתרון לאחזור ולניהול נתונים באפליקציות RAG ב-Gemini Enterprise Agent Platform. שימוש ב-Agent Search כ-backend לאחזור יכול לשפר את הביצועים, את יכולת ההתאמה לעומס ואת קלות השילוב.

  • ביצועים משופרים ויכולת התאמה לעומס (scaling): Agent Search נועד לטפל בכמויות גדולות של נתונים עם זמן אחזור נמוך במיוחד. כך אפשר לקצר את זמני התגובה ולשפר את הביצועים של אפליקציות RAG, במיוחד כשמדובר במאגרי ידע מורכבים או נרחבים.

  • ניהול נתונים פשוט יותר: אתם יכולים לייבא את הנתונים ממקורות שונים, כמו אתרים, מערכי נתונים ב-BigQuery וקטגוריות של Cloud Storage, וכך לייעל את תהליך הטמעת הנתונים.

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

  • שיפור איכות הפלט של מודל ה-LLM: יכולות האחזור של Agent Search עוזרות לוודא שאפליקציית ה-RAG מאחזרת את המידע הכי רלוונטי מהקורפוס, וכך הפלט שנוצר על ידי מודל ה-LLM מדויק ואינפורמטיבי יותר.

Agent Search משלב אחזור מידע מעמיק, עיבוד שפה טבעית והתכונות העדכניות ביותר של עיבוד מודל שפה גדול (LLM), שעוזרים להבין את כוונת המשתמש ולהחזיר את התוצאות הכי רלוונטיות למשתמש.

בעזרת Agent Search, אתם יכולים ליצור אפליקציית חיפוש באיכות של Google באמצעות נתונים שבשליטתכם.

כדי להגדיר חיפוש סוכן:

  1. יוצרים מאגר נתונים לחיפוש.

  2. יוצרים אפליקציית חיפוש.

שימוש ב-Agent Search כ-backend לאחזור ב-RAG Engine

אחרי שמגדירים את Agent Search, פועלים לפי השלבים הבאים כדי להגדיר אותו כ-backend לאחזור של אפליקציית ה-RAG.

הגדרת Agent Search כקצה העורפי לאחזור כדי ליצור קורפוס RAG

דוגמאות הקוד האלה מראות איך להגדיר את Agent Search בתור הקצה העורפי לאחזור של קורפוס RAG.

REST

כדי ליצור קורפוס RAG באמצעות שורת הפקודה:

  1. יצירת קורפוס RAG

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

    • ‫PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • ‫LOCATION: האזור שבו הבקשה תעובד.
    • ‫DISPLAY_NAME: השם המוצג של קורפוס ה-RAG שרוצים ליצור.
    • ‫ENGINE_NAME: שם המשאב המלא של מנוע החיפוש של הסוכן או של מאגר הנתונים של החיפוש של הסוכן. לדוגמה,

      projects/PROJECT_NUMBER/locations/LOCATION/collections/default_collection/engines/ENGINE_NAME/servingConfigs/default_search

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/ragCorpora" \
    -d '{
      "display_name" : "DISPLAY_NAME",
      "vertex_ai_search_config" : {
        "serving_config": "ENGINE_NAME/servingConfigs/default_search"
      }
    }'
    
  2. מעקב אחרי ההתקדמות

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

    • ‫PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • ‫LOCATION: האזור שבו הבקשה תעובד.
    • ‫OPERATION_ID: המזהה של פעולת היצירה של מסד הנתונים ל-RAG.
    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID"
    

Python

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

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


import agentplatform
from agentplatform import types

# TODO(developer): Update and un-comment below lines
# PROJECT_ID = "your-project-id"
# vertex_ai_search_engine_name = "projects/{PROJECT_ID}/locations/{LOCATION}/collections/default_collection/engines/{ENGINE_ID}"
# display_name = "test_corpus"
# description = "Corpus Description"

# Initialize Agent Platform client once per session.
# See https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/rag-engine/rag-overview#supported-regions
client = agentplatform.Client(project=PROJECT_ID, location="us-east5")

# Configure Search
vertex_ai_search_config = types.VertexAiSearchConfig(
    serving_config=f"{vertex_ai_search_engine_name}/servingConfigs/default_search",
)

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

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

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

REST

דוגמת הקוד הזו מראה איך לאחזר הקשרים באמצעות REST.

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

  • ‫PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
  • ‫LOCATION: האזור שבו הבקשה תעובד.
  • ‫RAG_CORPUS_RESOURCE: השם של משאב קורפוס ה-RAG.

    פורמט: projects/{project}/locations/{location}/ragCorpora/{rag_corpus}.

  • ‫TEXT: טקסט השאילתה לקבלת הקשרים רלוונטיים.
curl -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION:retrieveContexts" \
  -d '{
    "vertex_rag_store": {
      "rag_resources": {
        "rag_corpus": "RAG_CORPUS_RESOURCE"
      }
    },
    "query": {
      "text": "TEXT"
    }
  }'

Python

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


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-east5/ragCorpora/[rag_corpus_id]"

# Initialize Agent Platform client once per session.
# See https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/rag-engine/rag-overview#supported-regions
client = agentplatform.Client(project=PROJECT_ID, location="us-east5")

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

REST

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

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

  • ‫PROJECT_ID: מזהה הפרויקט ב- Google Cloud .

  • ‫LOCATION: האזור שבו הבקשה תעובד.

  • ‫MODEL_ID: מודל LLM ליצירת תוכן. לדוגמה, gemini-3.8-flash.

  • ‫GENERATION_METHOD: שיטת LLM ליצירת תוכן. לדוגמה, generateContent, streamGenerateContent.

  • ‫INPUT_PROMPT: הטקסט שנשלח ל-LLM ליצירת תוכן. כדאי לנסות להשתמש בהנחיה שרלוונטית למסמכים ב-Agent Search.

  • ‫RAG_CORPUS_RESOURCE: השם של משאב קורפוס ה-RAG. פורמט: projects/{project}/locations/{location}/ragCorpora/{rag_corpus}.

  • ‫SIMILARITY_TOP_K: אופציונלי: מספר ההקשרים המובילים שרוצים לאחזר.

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:GENERATION_METHOD" \
    -d '{
      "contents": {
        "role": "user",
        "parts": {
          "text": "INPUT_PROMPT"
        }
      },
      "tools": {
        "retrieval": {
          "disable_attribution": false,
          "vertex_rag_store": {
            "rag_resources": {
                "rag_corpus": "RAG_CORPUS_RESOURCE"
              },
            "similarity_top_k": SIMILARITY_TOP_K
          }
        }
      }
    }'
    

Python

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


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-east5/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(vertexai=True, project=PROJECT_ID, location="global")

response = genai_client.models.generate_content(
    model="gemini-3.8-flash",
    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....
#   ...

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