קבלת תשובות ופריטים להמשך טיפול

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

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

תכונות של שיטת התשובה

התכונות העיקריות של שיטת התשובה הן:

  • היכולת ליצור תשובות לשאילתות מורכבות. לדוגמה, שיטת התשובה יכולה לפרק שאילתות מורכבות, כמו השאילתה הבאה, לכמה שאילתות קטנות יותר כדי להחזיר תוצאות טובות יותר שמשמשות ליצירת תשובות טובות יותר:

    • "מה ההכנסות של Google Cloud ושל Google Ads בשנת 2024?"
    • "כמה שנים אחרי ההקמה שלה, Google הגיעה להכנסות של מיליארד דולר?"
  • היכולת לשלב חיפוש ויצירת תשובות בשיחה רב-שלבית על ידי קריאה לשיטת התשובה בכל תפנית.

  • האפשרות לשלב עם שיטת החיפוש כדי לצמצם את זמן האחזור של החיפוש. אפשר להתקשר לשיטת החיפוש ולשיטת התשובה בנפרד, ולהציג את תוצאות החיפוש והתשובות ב-iframe שונים בזמנים שונים. המשמעות היא שאתם יכולים להציג למשתמשים את תוצאות החיפוש (10 הקישורים הכחולים) תוך אלפיות שנייה. לא צריך לחכות ליצירת התשובות כדי להציג את תוצאות החיפוש.

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

מתי כדאי להשתמש בתשובה ומתי כדאי להשתמש בחיפוש

לחיפוש מבוסס סוכנים יש שתי שיטות שמשמשות לשליחת שאילתות לאפליקציות. יש להם תכונות שונות אבל חופפות.

משתמשים בשיטה answer כשרוצים:

  • אתם רוצים תשובה (או סיכום) שנוצרו על ידי AI לתוצאות החיפוש.

  • אתם רוצים לבצע חיפוש רב-שלבי, כלומר חיפושים ששומרים על ההקשר ומאפשרים לשאול שאלות המשך.

משתמשים בשיטת החיפוש במקרים הבאים:

  • אתם צריכים רק תוצאות חיפוש, ולא תשובה שנוצרה על ידי AI.

  • יש לכם אחד מהפריטים הבאים:

    • נתוני מדיה או נתונים רפואיים
    • הטמעות משלכם
    • פקדים של מילים נרדפות או הפניה אוטומטית
    • מאפיינים
    • קודי המדינות של המשתמשים
  • צריך לעיין בנתונים במאגר הנתונים הכללי.

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

  • אתם רוצים לקבל יותר מעשר תוצאות חיפוש, וגם לקבל תשובה שנוצרה על ידי AI.

  • יש לכם בעיות של זמן אחזור ואתם רוצים לחזור ולהציג תוצאות חיפוש במהירות לפני שהתשובה שנוצרה מוחזרת.

תכונות של שלב השאילתה

תכונת התשובה וההמשך תומכת בעיבוד של שאילתות בשפה טבעית.

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

ניסוח מחדש של שאילתה

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

  • לפצל שאילתות מורכבות לכמה שאילתות ולבצע שאילתות משנה סינכרוניות.

    לדוגמה: שאילתה מורכבת מחולקת לארבע שאילתות קטנות ופשוטות יותר.

    קלט של משתמשים שאילתות משנה שנוצרו מהשאילתה המורכבת
    מה משותף לתחביבים ולעבודות של אנדי ראם וארנו קלמנט?
    • Andie Ram occupation
    • Arnaud Clément occupation
    • Andie Ram hobby
    • התחביב של ארנו קלמנט
  • לסנתז שאילתות רב-שלביות, כדי ליצור שאלות המשך שמודעות להקשר ועם שמירת מצב.

    לדוגמה: שאילתות שנוצרו מקלט של משתמש בכל תור יכולות להיראות כך:

    קלט של משתמשים השאילתה סוכמה
    ‫Turn 1: מחשבים ניידים לבית הספר מחשבים ניידים לבית הספר
    תור 2: לא Mac מחשבים ניידים לבית הספר, לא Mac
    תור 3: מסך גדול יותר, ואני צריך גם מקלדת ועכבר אלחוטיים מחשבים ניידים עם מסך גדול יותר לבית הספר, לא מקבוק, עם מקלדת ועכבר אלחוטיים
    תור 4: ותיק גב בשבילו מחשבים ניידים עם מסך גדול יותר לבית הספר, לא מקבוק, עם מקלדת ועכבר אלחוטיים ותיק בשבילו
  • לפשט שאילתות ארוכות כדי לשפר את השליפה (נדרשת האפשרות תשובות גנרטיביות).

    לדוגמה: שאילתה ארוכה מקוצרת לשאילתה רגילה.

    קלט של משתמשים השאילתה פשוטה
    אני מנסה להבין למה הלחצן 'הוספה לעגלת הקניות' באתר שלנו לא פועל כמו שצריך. נראה שכאשר משתמש לוחץ על הלחצן, הפריט לא מתווסף לעגלת הקניות והוא מקבל הודעת שגיאה. בדקתי את הקוד ונראה שהוא תקין, לכן אני לא בטוח מה הבעיה. תוכל לעזור לי לפתור את הבעיה הזו? הלחצן 'הוספה לעגלת הקניות' לא פועל באתר.
  • ביצוע חשיבה רציונלית רב-שלבית

    הסקה מרובת שלבים מבוססת על פרדיגמת ReAct (חשיבה + פעולה), שמאפשרת למודלים גדולים של שפה (LLM) לפתור משימות מורכבות באמצעות חשיבה בשפה טבעית. כברירת מחדל, מספר השלבים המקסימלי הוא חמישה.

    לדוגמה:

    קלט של משתמשים שני שלבים ליצירת התשובה
    כמה שנים אחרי ההקמה שלה, Google הגיעה להכנסות של מיליארד דולר? שלב 1:
    [מחשבה]: אני צריך לדעת מתי Google נוסדה, ואז אוכל לשאול מה ההכנסות שלה מאז.
    [פעולה] חיפוש: מתי הוקמה Google?[התבוננות בתוצאות החיפוש]: '1998'

    שלב 2:
    [מחשבה]: עכשיו צריך לחפש את ההכנסות השנתיות של Google מאז 1998, ולגלות מתי הן חצו לראשונה את רף מיליארד הדולר.
    [Act] Search: Google revenue since 1998
    [Observe Search Results] Google revenue in 1998, Google revenue in 1999…..
    [תשובה]: ההכנסות של Google הגיעו ליותר ממיליארד דולר בשנת 2003 [1], 5 שנים אחרי שהחברה נוסדה בשנת 1998 [2].

    כדי להשתמש בהסקה רב-שלבית, צריך להפעיל את האפשרות תשובות גנרטיביות.

סיווג שאילתות

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

מידע נוסף על שאילתות שמנסות להטעות את המודל ועל שאילתות שלא מחפשות סיכום זמין במאמרים התעלמות משאילתות שמנסות להטעות את המודל והתעלמות משאילתות שלא מחפשות סיכום.

תכונות של שלב החיפוש

בחיפוש, שיטת התשובה כוללת את אותן אפשרויות כמו שיטת החיפוש. לדוגמה:

תכונות בשלב התשובה

במהלך שלב התשובה, כשנוצרות תשובות מתוצאות החיפוש, אפשר להפעיל את אותן התכונות כמו בשיטת החיפוש. לדוגמה:

תכונות נוספות של שלב התשובה שלא זמינות בשיטת החיפוש:

  • קבלת ציון תמיכה לכל טענה (משפט בתשובה שנוצרה). ציון התמיכה הוא ערך נקודה צפה בטווח [0,1] שמציין עד כמה הטענה מבוססת על הנתונים במאגר הנתונים. מידע נוסף זמין במאמר החזרת ציוני תמיכה בהארקה.

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

  • תחזיר רק תשובות שמבוססות על מידע מהימן. אתם יכולים לבחור להחזיר רק את התשובות שעומדות בסף מסוים של ציון התמיכה. מידע נוסף זמין במאמר בנושא הצגת תשובות שמבוססות על מידע מהימן בלבד.

  • בוחרים להחזיר שאלות קשורות. שאלות קשורות הן הצעות שהמשתמשים יכולים לבחור במקום להקליד שאלות משלהם.

  • הוספת מידע להתאמה אישית לשאילתות כדי שהתשובות יוכלו להיות מותאמות למשתמשים ספציפיים. מידע נוסף זמין במאמר בנושא התאמה אישית של תשובות.

כדי לקבל תשובות מולטי-מודאליות שכוללות תרשימים או תמונות בנוסף לטקסט, אפשר להשתמש באפשרויות הבאות:

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

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

לפני שמתחילים

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

  • אם יש לכם אפליקציה לחיפוש נתונים מובְנים, לא מובְנים או אתרים, מפעילים את האפשרויות הבאות:

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

חיפוש ומענה (בסיסי)

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

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

REST

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

  1. מריצים את פקודת ה-curl הבאה:

    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"}
          }'
    

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

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים שרוצים לשלוח אליה שאילתה.
    • QUERY: מחרוזת טקסט חופשי שמכילה את השאלה או את שאילתת החיפוש. לדוגמה, "השוואה בין מסדי הנתונים של BigQuery ו-Spanner".

Python

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Python.

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

from google.api_core.client_options import ClientOptions
from google.cloud import discoveryengine_v1 as discoveryengine

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION"                    # Values: "global", "us", "eu"
# engine_id = "YOUR_APP_ID"


def answer_query_sample(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.AnswerQueryResponse:
    #  For more information, refer to:
    # https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store
    client_options = (
        ClientOptions(api_endpoint=f"{location}-discoveryengine.googleapis.com")
        if location != "global"
        else None
    )

    # Create a client
    client = discoveryengine.ConversationalSearchServiceClient(
        client_options=client_options
    )

    # The full resource name of the Search serving config
    serving_config = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/servingConfigs/default_serving_config"

    # Optional: Options for query phase
    # The `query_understanding_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/QueryUnderstandingSpec
    query_understanding_spec = discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec(
        query_rephraser_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec(
            disable=False,  # Optional: Disable query rephraser
            max_rephrase_steps=1,  # Optional: Number of rephrase steps
        ),
        # Optional: Classify query types
        query_classification_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec(
            types=[
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.ADVERSARIAL_QUERY,
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.NON_ANSWER_SEEKING_QUERY,
            ]  # Options: ADVERSARIAL_QUERY, NON_ANSWER_SEEKING_QUERY or both
        ),
    )

    # Optional: Options for answer phase
    # The `answer_generation_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/AnswerGenerationSpec
    answer_generation_spec = discoveryengine.AnswerQueryRequest.AnswerGenerationSpec(
        ignore_adversarial_query=False,  # Optional: Ignore adversarial query
        ignore_non_answer_seeking_query=False,  # Optional: Ignore non-answer seeking query
        ignore_low_relevant_content=False,  # Optional: Return fallback answer when content is not relevant
        model_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.ModelSpec(
        # Use the 2026 stable production model for answer generation
        model_version="gemini-2.5-flash/answer_gen/stable",
        ),
        prompt_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.PromptSpec(
            preamble="Give a detailed answer.",  # Optional: Natural language instructions for customizing the answer.
        ),
        include_citations=True,  # Optional: Include citations in the response
        answer_language_code="en",  # Optional: Language code of the answer
    )

    # Initialize request argument(s)
    request = discoveryengine.AnswerQueryRequest(
        serving_config=serving_config,
        query=discoveryengine.Query(text="What is Vertex AI Search?"),
        session=None,  # Optional: include previous session ID to continue a conversation
        query_understanding_spec=query_understanding_spec,
        answer_generation_spec=answer_generation_spec,
        user_pseudo_id="user-pseudo-id",  # Optional: Add user pseudo-identifier for queries.
    )

    # Make the request
    response = client.answer_query(request)

    # Handle the response
    print(response)

    return response

פקודות של שלב השאילתה

בקטע הזה מוסבר איך מציינים אפשרויות לשלב השאילתה של הפעלת method answer.

חיפוש ותשובה (ניסוח מחדש מושבת)

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

REST

כדי לחפש ולקבל תוצאות עם תשובה שנוצרה על ידי AI בלי לשנות את ניסוח השאילתה:

  1. מריצים את פקודת ה-curl הבאה:

    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "queryUnderstandingSpec": {
               "queryRephraserSpec": {
                  "disable": true
            }
        }
          }'
    
    

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

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים.
    • QUERY: מחרוזת טקסט חופשי שמכילה את השאלה או את שאילתת החיפוש. לדוגמה, "השוואה בין מסדי הנתונים של BigQuery ו-Spanner".

Python

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Python.

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

from google.api_core.client_options import ClientOptions
from google.cloud import discoveryengine_v1 as discoveryengine

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION"                    # Values: "global", "us", "eu"
# engine_id = "YOUR_APP_ID"


def answer_query_sample(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.AnswerQueryResponse:
    #  For more information, refer to:
    # https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store
    client_options = (
        ClientOptions(api_endpoint=f"{location}-discoveryengine.googleapis.com")
        if location != "global"
        else None
    )

    # Create a client
    client = discoveryengine.ConversationalSearchServiceClient(
        client_options=client_options
    )

    # The full resource name of the Search serving config
    serving_config = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/servingConfigs/default_serving_config"

    # Optional: Options for query phase
    # The `query_understanding_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/QueryUnderstandingSpec
    query_understanding_spec = discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec(
        query_rephraser_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec(
            disable=False,  # Optional: Disable query rephraser
            max_rephrase_steps=1,  # Optional: Number of rephrase steps
        ),
        # Optional: Classify query types
        query_classification_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec(
            types=[
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.ADVERSARIAL_QUERY,
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.NON_ANSWER_SEEKING_QUERY,
            ]  # Options: ADVERSARIAL_QUERY, NON_ANSWER_SEEKING_QUERY or both
        ),
    )

    # Optional: Options for answer phase
    # The `answer_generation_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/AnswerGenerationSpec
    answer_generation_spec = discoveryengine.AnswerQueryRequest.AnswerGenerationSpec(
        ignore_adversarial_query=False,  # Optional: Ignore adversarial query
        ignore_non_answer_seeking_query=False,  # Optional: Ignore non-answer seeking query
        ignore_low_relevant_content=False,  # Optional: Return fallback answer when content is not relevant
        model_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.ModelSpec(
        # Use the 2026 stable production model for answer generation
        model_version="gemini-2.5-flash/answer_gen/stable",
        ),
        prompt_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.PromptSpec(
            preamble="Give a detailed answer.",  # Optional: Natural language instructions for customizing the answer.
        ),
        include_citations=True,  # Optional: Include citations in the response
        answer_language_code="en",  # Optional: Language code of the answer
    )

    # Initialize request argument(s)
    request = discoveryengine.AnswerQueryRequest(
        serving_config=serving_config,
        query=discoveryengine.Query(text="What is Vertex AI Search?"),
        session=None,  # Optional: include previous session ID to continue a conversation
        query_understanding_spec=query_understanding_spec,
        answer_generation_spec=answer_generation_spec,
        user_pseudo_id="user-pseudo-id",  # Optional: Add user pseudo-identifier for queries.
    )

    # Make the request
    response = client.answer_query(request)

    # Handle the response
    print(response)

    return response

חיפוש ומענה (ציון מספר השלבים המקסימלי)

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

REST

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

  1. מריצים את פקודת ה-curl הבאה:

    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "queryUnderstandingSpec": {
                "queryRephraserSpec": {
                    "maxRephraseSteps": MAX_REPHRASE
                 }
             }
          }'
    

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

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים שרוצים לשלוח אליה שאילתה.
    • QUERY: מחרוזת טקסט חופשי שמכילה את השאלה או את שאילתת החיפוש. לדוגמה, "השוואה בין מסדי הנתונים של BigQuery ו-Spanner".
    • MAX_REPHRASE: המספר המקסימלי של שלבי הניסוח מחדש. הערך המקסימלי המותר הוא 5. אם לא מגדירים ערך או אם מגדירים ערך נמוך מ-1, הערך יהיה ברירת המחדל, 1.

Python

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Python.

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

from google.api_core.client_options import ClientOptions
from google.cloud import discoveryengine_v1 as discoveryengine

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION"                    # Values: "global", "us", "eu"
# engine_id = "YOUR_APP_ID"


def answer_query_sample(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.AnswerQueryResponse:
    #  For more information, refer to:
    # https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store
    client_options = (
        ClientOptions(api_endpoint=f"{location}-discoveryengine.googleapis.com")
        if location != "global"
        else None
    )

    # Create a client
    client = discoveryengine.ConversationalSearchServiceClient(
        client_options=client_options
    )

    # The full resource name of the Search serving config
    serving_config = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/servingConfigs/default_serving_config"

    # Optional: Options for query phase
    # The `query_understanding_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/QueryUnderstandingSpec
    query_understanding_spec = discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec(
        query_rephraser_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec(
            disable=False,  # Optional: Disable query rephraser
            max_rephrase_steps=1,  # Optional: Number of rephrase steps
        ),
        # Optional: Classify query types
        query_classification_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec(
            types=[
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.ADVERSARIAL_QUERY,
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.NON_ANSWER_SEEKING_QUERY,
            ]  # Options: ADVERSARIAL_QUERY, NON_ANSWER_SEEKING_QUERY or both
        ),
    )

    # Optional: Options for answer phase
    # The `answer_generation_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/AnswerGenerationSpec
    answer_generation_spec = discoveryengine.AnswerQueryRequest.AnswerGenerationSpec(
        ignore_adversarial_query=False,  # Optional: Ignore adversarial query
        ignore_non_answer_seeking_query=False,  # Optional: Ignore non-answer seeking query
        ignore_low_relevant_content=False,  # Optional: Return fallback answer when content is not relevant
        model_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.ModelSpec(
        # Use the 2026 stable production model for answer generation
        model_version="gemini-2.5-flash/answer_gen/stable",
        ),
        prompt_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.PromptSpec(
            preamble="Give a detailed answer.",  # Optional: Natural language instructions for customizing the answer.
        ),
        include_citations=True,  # Optional: Include citations in the response
        answer_language_code="en",  # Optional: Language code of the answer
    )

    # Initialize request argument(s)
    request = discoveryengine.AnswerQueryRequest(
        serving_config=serving_config,
        query=discoveryengine.Query(text="What is Vertex AI Search?"),
        session=None,  # Optional: include previous session ID to continue a conversation
        query_understanding_spec=query_understanding_spec,
        answer_generation_spec=answer_generation_spec,
        user_pseudo_id="user-pseudo-id",  # Optional: Add user pseudo-identifier for queries.
    )

    # Make the request
    response = client.answer_query(request)

    # Handle the response
    print(response)

    return response

חיפוש ומתן תשובה באמצעות סיווג שאילתות

הפקודה הבאה מראה איך להפעיל את השיטה answer כדי לבדוק אם שאילתה היא עוינת, לא מחפשת תשובה או לא זה ולא זה.

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

REST

כדי לקבוע אם שאילתה היא עוינת או לא מכוונת לקבלת תשובה:

  1. מריצים את פקודת ה-curl הבאה:

    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "queryUnderstandingSpec": {
                "queryClassificationSpec": {
                    "types": ["QUERY_CLASSIFICATION_TYPE"]
                 }
             }
          }'
    

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

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים שרוצים לשלוח אליה שאילתה.
    • QUERY: מחרוזת טקסט חופשי שמכילה את השאלה או את שאילתת החיפוש. לדוגמה, "שלום".
    • QUERY_CLASSIFICATION_TYPE: סוגי השאילתות שרוצים לזהות: ADVERSARIAL_QUERY, ‏NON_ANSWER_SEEKING_QUERY או שניהם.

Python

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Python.

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

from google.api_core.client_options import ClientOptions
from google.cloud import discoveryengine_v1 as discoveryengine

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION"                    # Values: "global", "us", "eu"
# engine_id = "YOUR_APP_ID"


def answer_query_sample(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.AnswerQueryResponse:
    #  For more information, refer to:
    # https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store
    client_options = (
        ClientOptions(api_endpoint=f"{location}-discoveryengine.googleapis.com")
        if location != "global"
        else None
    )

    # Create a client
    client = discoveryengine.ConversationalSearchServiceClient(
        client_options=client_options
    )

    # The full resource name of the Search serving config
    serving_config = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/servingConfigs/default_serving_config"

    # Optional: Options for query phase
    # The `query_understanding_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/QueryUnderstandingSpec
    query_understanding_spec = discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec(
        query_rephraser_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec(
            disable=False,  # Optional: Disable query rephraser
            max_rephrase_steps=1,  # Optional: Number of rephrase steps
        ),
        # Optional: Classify query types
        query_classification_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec(
            types=[
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.ADVERSARIAL_QUERY,
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.NON_ANSWER_SEEKING_QUERY,
            ]  # Options: ADVERSARIAL_QUERY, NON_ANSWER_SEEKING_QUERY or both
        ),
    )

    # Optional: Options for answer phase
    # The `answer_generation_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/AnswerGenerationSpec
    answer_generation_spec = discoveryengine.AnswerQueryRequest.AnswerGenerationSpec(
        ignore_adversarial_query=False,  # Optional: Ignore adversarial query
        ignore_non_answer_seeking_query=False,  # Optional: Ignore non-answer seeking query
        ignore_low_relevant_content=False,  # Optional: Return fallback answer when content is not relevant
        model_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.ModelSpec(
        # Use the 2026 stable production model for answer generation
        model_version="gemini-2.5-flash/answer_gen/stable",
        ),
        prompt_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.PromptSpec(
            preamble="Give a detailed answer.",  # Optional: Natural language instructions for customizing the answer.
        ),
        include_citations=True,  # Optional: Include citations in the response
        answer_language_code="en",  # Optional: Language code of the answer
    )

    # Initialize request argument(s)
    request = discoveryengine.AnswerQueryRequest(
        serving_config=serving_config,
        query=discoveryengine.Query(text="What is Vertex AI Search?"),
        session=None,  # Optional: include previous session ID to continue a conversation
        query_understanding_spec=query_understanding_spec,
        answer_generation_spec=answer_generation_spec,
        user_pseudo_id="user-pseudo-id",  # Optional: Add user pseudo-identifier for queries.
    )

    # Make the request
    response = client.answer_query(request)

    # Handle the response
    print(response)

    return response

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

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

הפקודה הבאה מראה איך להפעיל את המתודה answer ולציין אפשרויות שונות לגבי אופן החזרת תוצאת החיפוש. (תוצאות החיפוש לא קשורות לתשובה).

REST

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

  1. מריצים את פקודת ה-curl הבאה:

    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
              "searchSpec": {
              "searchParams": {
                "maxReturnResults": MAX_RETURN_RESULTS,
                "filter": "FILTER",
                "boostSpec": BOOST_SPEC,
                "orderBy": "ORDER_BY",
                "searchResultMode": SEARCH_RESULT_MODE
               }
             }
          }'
    

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

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים שרוצים לשלוח אליה שאילתה.
    • QUERY: מחרוזת טקסט חופשי שמכילה את השאלה או את שאילתת החיפוש. לדוגמה, "השוואה בין מסדי הנתונים של BigQuery ו-Spanner".
    • MAX_RETURN_RESULTS: מספר תוצאות החיפוש שיוחזרו. ערך ברירת המחדל הוא 10. הערך המקסימלי הוא 25.
    • FILTER: המסנן מציין אילו מסמכים נכללים בשאילתה. אם המטא-נתונים של מסמך מסוים עומדים בדרישות הסינון, המסמך ייכלל בשאילתה. מידע נוסף, כולל תחביר של מסננים, זמין במאמר סינון נתונים מובְנים או לא מובְנים בחיפוש מותאם אישית.
    • BOOST_SPEC: הגדרת ההגברה מאפשרת לכם להגביר את ההדגשה של מסמכים מסוימים בתוצאות החיפוש, מה שיכול להשפיע על התשובה. מידע נוסף, כולל התחביר של הגדרת ההדגשה, זמין במאמר בנושא הדגשת תוצאות חיפוש.
    • ORDER_BY: סדר החזרת המסמכים. אפשר להזמין מסמכים לפי שדה באובייקט Document. הביטוי orderBy הוא תלוי אותיות רישיות. אם השדה הזה לא מזוהה, מוחזר INVALID_ARGUMENT.
    • SEARCH_RESULT_MODE: מציין את מצב תוצאות החיפוש: DOCUMENTS או CHUNKS. מידע נוסף זמין במאמרים ניתוח מסמכים וחלוקה שלהם לחלקים ו-ContentSearchSpec. השדה הזה זמין רק בגרסה v1alpha של ה-API.

Python

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Python.

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

from google.api_core.client_options import ClientOptions
from google.cloud import discoveryengine_v1 as discoveryengine

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION"                    # Values: "global", "us", "eu"
# engine_id = "YOUR_APP_ID"


def answer_query_sample(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.AnswerQueryResponse:
    #  For more information, refer to:
    # https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store
    client_options = (
        ClientOptions(api_endpoint=f"{location}-discoveryengine.googleapis.com")
        if location != "global"
        else None
    )

    # Create a client
    client = discoveryengine.ConversationalSearchServiceClient(
        client_options=client_options
    )

    # The full resource name of the Search serving config
    serving_config = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/servingConfigs/default_serving_config"

    # Optional: Options for query phase
    # The `query_understanding_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/QueryUnderstandingSpec
    query_understanding_spec = discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec(
        query_rephraser_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec(
            disable=False,  # Optional: Disable query rephraser
            max_rephrase_steps=1,  # Optional: Number of rephrase steps
        ),
        # Optional: Classify query types
        query_classification_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec(
            types=[
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.ADVERSARIAL_QUERY,
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.NON_ANSWER_SEEKING_QUERY,
            ]  # Options: ADVERSARIAL_QUERY, NON_ANSWER_SEEKING_QUERY or both
        ),
    )

    # Optional: Options for answer phase
    # The `answer_generation_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/AnswerGenerationSpec
    answer_generation_spec = discoveryengine.AnswerQueryRequest.AnswerGenerationSpec(
        ignore_adversarial_query=False,  # Optional: Ignore adversarial query
        ignore_non_answer_seeking_query=False,  # Optional: Ignore non-answer seeking query
        ignore_low_relevant_content=False,  # Optional: Return fallback answer when content is not relevant
        model_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.ModelSpec(
        # Use the 2026 stable production model for answer generation
        model_version="gemini-2.5-flash/answer_gen/stable",
        ),
        prompt_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.PromptSpec(
            preamble="Give a detailed answer.",  # Optional: Natural language instructions for customizing the answer.
        ),
        include_citations=True,  # Optional: Include citations in the response
        answer_language_code="en",  # Optional: Language code of the answer
    )

    # Initialize request argument(s)
    request = discoveryengine.AnswerQueryRequest(
        serving_config=serving_config,
        query=discoveryengine.Query(text="What is Vertex AI Search?"),
        session=None,  # Optional: include previous session ID to continue a conversation
        query_understanding_spec=query_understanding_spec,
        answer_generation_spec=answer_generation_spec,
        user_pseudo_id="user-pseudo-id",  # Optional: Add user pseudo-identifier for queries.
    )

    # Make the request
    response = client.answer_query(request)

    # Handle the response
    print(response)

    return response

פקודות בשלב התשובה

בקטע הזה מוסבר איך להתאים אישית את הפעלת ה-method answer. אפשר לשלב בין האפשרויות הבאות לפי הצורך.

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

הפקודה הבאה מראה איך להימנע ממענה לשאילתות מתנגדות ולשאילתות שלא מחפשות תשובה כשמפעילים את המתודה answer.

REST

כדי לדלג על מענה לשאילתות שהן עוינות או לא מכוונות למציאת תשובה, צריך לבצע את הפעולות הבאות:

  1. מריצים את פקודת ה-curl הבאה:

    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "answerGenerationSpec": {
               "ignoreAdversarialQuery": true,
               "ignoreNonAnswerSeekingQuery": true
            }
          }'
    

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

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים שרוצים לשלוח אליה שאילתה.
    • QUERY: מחרוזת טקסט חופשי שמכילה את השאלה או את שאילתת החיפוש.

Python

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Python.

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

from google.api_core.client_options import ClientOptions
from google.cloud import discoveryengine_v1 as discoveryengine

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION"                    # Values: "global", "us", "eu"
# engine_id = "YOUR_APP_ID"


def answer_query_sample(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.AnswerQueryResponse:
    #  For more information, refer to:
    # https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store
    client_options = (
        ClientOptions(api_endpoint=f"{location}-discoveryengine.googleapis.com")
        if location != "global"
        else None
    )

    # Create a client
    client = discoveryengine.ConversationalSearchServiceClient(
        client_options=client_options
    )

    # The full resource name of the Search serving config
    serving_config = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/servingConfigs/default_serving_config"

    # Optional: Options for query phase
    # The `query_understanding_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/QueryUnderstandingSpec
    query_understanding_spec = discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec(
        query_rephraser_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec(
            disable=False,  # Optional: Disable query rephraser
            max_rephrase_steps=1,  # Optional: Number of rephrase steps
        ),
        # Optional: Classify query types
        query_classification_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec(
            types=[
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.ADVERSARIAL_QUERY,
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.NON_ANSWER_SEEKING_QUERY,
            ]  # Options: ADVERSARIAL_QUERY, NON_ANSWER_SEEKING_QUERY or both
        ),
    )

    # Optional: Options for answer phase
    # The `answer_generation_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/AnswerGenerationSpec
    answer_generation_spec = discoveryengine.AnswerQueryRequest.AnswerGenerationSpec(
        ignore_adversarial_query=False,  # Optional: Ignore adversarial query
        ignore_non_answer_seeking_query=False,  # Optional: Ignore non-answer seeking query
        ignore_low_relevant_content=False,  # Optional: Return fallback answer when content is not relevant
        model_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.ModelSpec(
        # Use the 2026 stable production model for answer generation
        model_version="gemini-2.5-flash/answer_gen/stable",
        ),
        prompt_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.PromptSpec(
            preamble="Give a detailed answer.",  # Optional: Natural language instructions for customizing the answer.
        ),
        include_citations=True,  # Optional: Include citations in the response
        answer_language_code="en",  # Optional: Language code of the answer
    )

    # Initialize request argument(s)
    request = discoveryengine.AnswerQueryRequest(
        serving_config=serving_config,
        query=discoveryengine.Query(text="What is Vertex AI Search?"),
        session=None,  # Optional: include previous session ID to continue a conversation
        query_understanding_spec=query_understanding_spec,
        answer_generation_spec=answer_generation_spec,
        user_pseudo_id="user-pseudo-id",  # Optional: Add user pseudo-identifier for queries.
    )

    # Make the request
    response = client.answer_query(request)

    # Handle the response
    print(response)

    return response

הצגת תשובות רלוונטיות בלבד

התכונה 'חיפוש באמצעות סוכן' יכולה להעריך את מידת הרלוונטיות של התוצאות לשאילתה. אם לא נמצאו תוצאות רלוונטיות מספיק, במקום ליצור תשובה מתוצאות לא רלוונטיות או רלוונטיות באופן מינימלי, אפשר לבחור להחזיר תשובת ברירת מחדל: We do not have a summary for your query.

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

REST

כדי להחזיר תשובה חלופית אם לא נמצאו תוצאות רלוונטיות, צריך לבצע את הפעולות הבאות:

  1. מריצים את פקודת ה-curl הבאה:

    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "answerGenerationSpec": {
               "ignoreLowRelevantContent": true
            }
          }'
    

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

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים שרוצים לשלוח אליה שאילתה.
    • QUERY: מחרוזת טקסט חופשי שמכילה את השאלה או את שאילתת החיפוש.

Python

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Python.

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

from google.api_core.client_options import ClientOptions
from google.cloud import discoveryengine_v1 as discoveryengine

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION"                    # Values: "global", "us", "eu"
# engine_id = "YOUR_APP_ID"


def answer_query_sample(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.AnswerQueryResponse:
    #  For more information, refer to:
    # https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store
    client_options = (
        ClientOptions(api_endpoint=f"{location}-discoveryengine.googleapis.com")
        if location != "global"
        else None
    )

    # Create a client
    client = discoveryengine.ConversationalSearchServiceClient(
        client_options=client_options
    )

    # The full resource name of the Search serving config
    serving_config = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/servingConfigs/default_serving_config"

    # Optional: Options for query phase
    # The `query_understanding_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/QueryUnderstandingSpec
    query_understanding_spec = discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec(
        query_rephraser_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec(
            disable=False,  # Optional: Disable query rephraser
            max_rephrase_steps=1,  # Optional: Number of rephrase steps
        ),
        # Optional: Classify query types
        query_classification_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec(
            types=[
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.ADVERSARIAL_QUERY,
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.NON_ANSWER_SEEKING_QUERY,
            ]  # Options: ADVERSARIAL_QUERY, NON_ANSWER_SEEKING_QUERY or both
        ),
    )

    # Optional: Options for answer phase
    # The `answer_generation_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/AnswerGenerationSpec
    answer_generation_spec = discoveryengine.AnswerQueryRequest.AnswerGenerationSpec(
        ignore_adversarial_query=False,  # Optional: Ignore adversarial query
        ignore_non_answer_seeking_query=False,  # Optional: Ignore non-answer seeking query
        ignore_low_relevant_content=False,  # Optional: Return fallback answer when content is not relevant
        model_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.ModelSpec(
        # Use the 2026 stable production model for answer generation
        model_version="gemini-2.5-flash/answer_gen/stable",
        ),
        prompt_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.PromptSpec(
            preamble="Give a detailed answer.",  # Optional: Natural language instructions for customizing the answer.
        ),
        include_citations=True,  # Optional: Include citations in the response
        answer_language_code="en",  # Optional: Language code of the answer
    )

    # Initialize request argument(s)
    request = discoveryengine.AnswerQueryRequest(
        serving_config=serving_config,
        query=discoveryengine.Query(text="What is Vertex AI Search?"),
        session=None,  # Optional: include previous session ID to continue a conversation
        query_understanding_spec=query_understanding_spec,
        answer_generation_spec=answer_generation_spec,
        user_pseudo_id="user-pseudo-id",  # Optional: Add user pseudo-identifier for queries.
    )

    # Make the request
    response = client.answer_query(request)

    # Handle the response
    print(response)

    return response

החזרת ציוני עיגון

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

מידע כללי על הארקה ב-Vertex AI זמין במאמר בדיקת הארקה באמצעות RAG. השיטה groundingConfigs.check מופעלת על ידי השיטה answer.

REST

כדי לקבל ציון תמיכה לכל טענה (משפט בתשובה) וציון תמיכה מצטבר לתשובה, מבצעים את הפעולות הבאות:

  1. מריצים את פקודת ה-curl הבאה:

    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "groundingSpec": {
               "includeGroundingSupports": true,
            }
          }'
    

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

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים שרוצים לשלוח אליה שאילתה.
    • QUERY: מחרוזת טקסט חופשי שמכילה את השאלה או את שאילתת החיפוש.

הצגת תשובות שמבוססות על מידע מהימן בלבד

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

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

מידע כללי על הארקה ב-Vertex AI זמין במאמר בדיקת הארקה באמצעות RAG. השיטה groundingConfigs.check מופעלת על ידי השיטה answer.

REST

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

  1. מריצים את פקודת ה-curl הבאה:

    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "groundingSpec": {
               "filteringLevel": "FILTER_LEVEL"
            }
          }'
    

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

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים שרוצים לשלוח אליה שאילתה.
    • QUERY: מחרוזת טקסט חופשי שמכילה את השאלה או את שאילתת החיפוש.
    • FILTER_LEVEL: ספירה לסינון תשובות על סמך ציון התמיכה בהצגת מקורות. האפשרויות הן: FILTERING_LEVEL_LOW ו-FILTERING_LEVEL_HIGH. אם לא מצוין filteringLevel, לא מוחל על התשובה מסנן של ציון התמיכה.

ציון מודל התשובה

הפקודה הבאה מראה איך לשנות את גרסת המודל שמשמשת ליצירת תשובות.

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

REST

כדי ליצור תשובה באמצעות מודל ששונה ממודל ברירת המחדל:

  1. מריצים את פקודת ה-curl הבאה:

    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "answerGenerationSpec": {
               "modelSpec": {
                  "modelVersion": "MODEL_VERSION",
               }
             }
          }'
    

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

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים שרוצים לשלוח אליה שאילתה.
    • QUERY: מחרוזת טקסט חופשי שמכילה את השאלה או את שאילתת החיפוש.
    • MODEL_VERSION: גרסת המודל שרוצים להשתמש בה כדי ליצור את התשובה. מידע נוסף זמין במאמר גרסאות של מודלים ליצירת תשובות ומחזור החיים שלהן.

Python

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Python.

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

from google.api_core.client_options import ClientOptions
from google.cloud import discoveryengine_v1 as discoveryengine

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION"                    # Values: "global", "us", "eu"
# engine_id = "YOUR_APP_ID"


def answer_query_sample(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.AnswerQueryResponse:
    #  For more information, refer to:
    # https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store
    client_options = (
        ClientOptions(api_endpoint=f"{location}-discoveryengine.googleapis.com")
        if location != "global"
        else None
    )

    # Create a client
    client = discoveryengine.ConversationalSearchServiceClient(
        client_options=client_options
    )

    # The full resource name of the Search serving config
    serving_config = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/servingConfigs/default_serving_config"

    # Optional: Options for query phase
    # The `query_understanding_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/QueryUnderstandingSpec
    query_understanding_spec = discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec(
        query_rephraser_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec(
            disable=False,  # Optional: Disable query rephraser
            max_rephrase_steps=1,  # Optional: Number of rephrase steps
        ),
        # Optional: Classify query types
        query_classification_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec(
            types=[
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.ADVERSARIAL_QUERY,
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.NON_ANSWER_SEEKING_QUERY,
            ]  # Options: ADVERSARIAL_QUERY, NON_ANSWER_SEEKING_QUERY or both
        ),
    )

    # Optional: Options for answer phase
    # The `answer_generation_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/AnswerGenerationSpec
    answer_generation_spec = discoveryengine.AnswerQueryRequest.AnswerGenerationSpec(
        ignore_adversarial_query=False,  # Optional: Ignore adversarial query
        ignore_non_answer_seeking_query=False,  # Optional: Ignore non-answer seeking query
        ignore_low_relevant_content=False,  # Optional: Return fallback answer when content is not relevant
        model_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.ModelSpec(
        # Use the 2026 stable production model for answer generation
        model_version="gemini-2.5-flash/answer_gen/stable",
        ),
        prompt_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.PromptSpec(
            preamble="Give a detailed answer.",  # Optional: Natural language instructions for customizing the answer.
        ),
        include_citations=True,  # Optional: Include citations in the response
        answer_language_code="en",  # Optional: Language code of the answer
    )

    # Initialize request argument(s)
    request = discoveryengine.AnswerQueryRequest(
        serving_config=serving_config,
        query=discoveryengine.Query(text="What is Vertex AI Search?"),
        session=None,  # Optional: include previous session ID to continue a conversation
        query_understanding_spec=query_understanding_spec,
        answer_generation_spec=answer_generation_spec,
        user_pseudo_id="user-pseudo-id",  # Optional: Add user pseudo-identifier for queries.
    )

    # Make the request
    response = client.answer_query(request)

    # Handle the response
    print(response)

    return response

ציון פתיח בהתאמה אישית

הפקודה הבאה מראה איך מגדירים מבוא לתשובה שנוצרה. ההקדמה מכילה הוראות בשפה טבעית להתאמה אישית של התשובה. אתם יכולים לבקש התאמות אישיות כמו אורך, רמת פירוט, סגנון פלט (למשל, "פשוט"), שפת פלט, מוקד התשובה ופורמט (למשל, טבלאות, תבליטים ו-XML). לדוגמה, הקדמה יכולה להיות "תסביר את זה כמו לילד בן עשר".

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

REST

כדי ליצור תשובה באמצעות מודל ששונה ממודל ברירת המחדל:

  1. מריצים את פקודת ה-curl הבאה:

    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "answerGenerationSpec": {
               "promptSpec": {
                   "preamble": "PREAMBLE",
               }
            }
          }'
    

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

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים שרוצים לשלוח אליה שאילתה.
    • QUERY: מחרוזת טקסט חופשי שמכילה את השאלה או את שאילתת החיפוש.
    • PREAMBLE: הוראה בשפה טבעית להתאמה אישית של התשובה. לדוגמה, אפשר לנסות show the answer format in an ordered list או give a very detailed answer.

Python

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Python.

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

from google.api_core.client_options import ClientOptions
from google.cloud import discoveryengine_v1 as discoveryengine

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION"                    # Values: "global", "us", "eu"
# engine_id = "YOUR_APP_ID"


def answer_query_sample(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.AnswerQueryResponse:
    #  For more information, refer to:
    # https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store
    client_options = (
        ClientOptions(api_endpoint=f"{location}-discoveryengine.googleapis.com")
        if location != "global"
        else None
    )

    # Create a client
    client = discoveryengine.ConversationalSearchServiceClient(
        client_options=client_options
    )

    # The full resource name of the Search serving config
    serving_config = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/servingConfigs/default_serving_config"

    # Optional: Options for query phase
    # The `query_understanding_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/QueryUnderstandingSpec
    query_understanding_spec = discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec(
        query_rephraser_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec(
            disable=False,  # Optional: Disable query rephraser
            max_rephrase_steps=1,  # Optional: Number of rephrase steps
        ),
        # Optional: Classify query types
        query_classification_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec(
            types=[
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.ADVERSARIAL_QUERY,
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.NON_ANSWER_SEEKING_QUERY,
            ]  # Options: ADVERSARIAL_QUERY, NON_ANSWER_SEEKING_QUERY or both
        ),
    )

    # Optional: Options for answer phase
    # The `answer_generation_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/AnswerGenerationSpec
    answer_generation_spec = discoveryengine.AnswerQueryRequest.AnswerGenerationSpec(
        ignore_adversarial_query=False,  # Optional: Ignore adversarial query
        ignore_non_answer_seeking_query=False,  # Optional: Ignore non-answer seeking query
        ignore_low_relevant_content=False,  # Optional: Return fallback answer when content is not relevant
        model_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.ModelSpec(
        # Use the 2026 stable production model for answer generation
        model_version="gemini-2.5-flash/answer_gen/stable",
        ),
        prompt_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.PromptSpec(
            preamble="Give a detailed answer.",  # Optional: Natural language instructions for customizing the answer.
        ),
        include_citations=True,  # Optional: Include citations in the response
        answer_language_code="en",  # Optional: Language code of the answer
    )

    # Initialize request argument(s)
    request = discoveryengine.AnswerQueryRequest(
        serving_config=serving_config,
        query=discoveryengine.Query(text="What is Vertex AI Search?"),
        session=None,  # Optional: include previous session ID to continue a conversation
        query_understanding_spec=query_understanding_spec,
        answer_generation_spec=answer_generation_spec,
        user_pseudo_id="user-pseudo-id",  # Optional: Add user pseudo-identifier for queries.
    )

    # Make the request
    response = client.answer_query(request)

    # Handle the response
    print(response)

    return response

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

כדי לקבל שאלות קשורות, צריך לציין את הכללתן בכל שאילתה, והן מוחזרות כתצורת מערך של מחרוזות בתגובה.

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

לפני שמתחילים

מוודאים שהאפשרות תשובות גנרטיביות מופעלת באפליקציה.

התהליך

הפקודה הבאה מראה איך לבקש לכלול בשאלה שאלות קשורות.

REST

כדי לקבל שאלות קשורות עם תשובה שנוצרה:

  1. מריצים את פקודת ה-curl הבאה:

    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "relatedQuestionsSpec": { "enable": true }
          }'
    

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

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים שרוצים לשלוח אליה שאילתה.
    • QUERY: מחרוזת טקסט חופשי שמכילה את השאלה או את שאילתת החיפוש. לדוגמה, "אילו סוגי נתונים אפשר לייבא לחיפוש באמצעות סוכן?".

הוספת ציטוטים

הפקודה הבאה מראה איך לבקש לכלול ציטוטים בתשובה.

REST

כדי ליצור תשובה באמצעות מודל ששונה ממודל ברירת המחדל:

  1. מריצים את פקודת ה-curl הבאה:

    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "answerGenerationSpec": {
               "includeCitations": INCLUDE_CITATIONS
            }
          }'
    

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

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים שרוצים לשלוח אליה שאילתה.
    • QUERY: מחרוזת טקסט חופשי שמכילה את השאלה או את שאילתת החיפוש.
    • INCLUDE_CITATIONS: מציין אם לכלול במענה מטא-נתונים של ציטוט. ערך ברירת המחדל הוא false.

Python

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Python.

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

from google.api_core.client_options import ClientOptions
from google.cloud import discoveryengine_v1 as discoveryengine

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION"                    # Values: "global", "us", "eu"
# engine_id = "YOUR_APP_ID"


def answer_query_sample(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.AnswerQueryResponse:
    #  For more information, refer to:
    # https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store
    client_options = (
        ClientOptions(api_endpoint=f"{location}-discoveryengine.googleapis.com")
        if location != "global"
        else None
    )

    # Create a client
    client = discoveryengine.ConversationalSearchServiceClient(
        client_options=client_options
    )

    # The full resource name of the Search serving config
    serving_config = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/servingConfigs/default_serving_config"

    # Optional: Options for query phase
    # The `query_understanding_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/QueryUnderstandingSpec
    query_understanding_spec = discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec(
        query_rephraser_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec(
            disable=False,  # Optional: Disable query rephraser
            max_rephrase_steps=1,  # Optional: Number of rephrase steps
        ),
        # Optional: Classify query types
        query_classification_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec(
            types=[
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.ADVERSARIAL_QUERY,
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.NON_ANSWER_SEEKING_QUERY,
            ]  # Options: ADVERSARIAL_QUERY, NON_ANSWER_SEEKING_QUERY or both
        ),
    )

    # Optional: Options for answer phase
    # The `answer_generation_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/AnswerGenerationSpec
    answer_generation_spec = discoveryengine.AnswerQueryRequest.AnswerGenerationSpec(
        ignore_adversarial_query=False,  # Optional: Ignore adversarial query
        ignore_non_answer_seeking_query=False,  # Optional: Ignore non-answer seeking query
        ignore_low_relevant_content=False,  # Optional: Return fallback answer when content is not relevant
        model_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.ModelSpec(
        # Use the 2026 stable production model for answer generation
        model_version="gemini-2.5-flash/answer_gen/stable",
        ),
        prompt_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.PromptSpec(
            preamble="Give a detailed answer.",  # Optional: Natural language instructions for customizing the answer.
        ),
        include_citations=True,  # Optional: Include citations in the response
        answer_language_code="en",  # Optional: Language code of the answer
    )

    # Initialize request argument(s)
    request = discoveryengine.AnswerQueryRequest(
        serving_config=serving_config,
        query=discoveryengine.Query(text="What is Vertex AI Search?"),
        session=None,  # Optional: include previous session ID to continue a conversation
        query_understanding_spec=query_understanding_spec,
        answer_generation_spec=answer_generation_spec,
        user_pseudo_id="user-pseudo-id",  # Optional: Add user pseudo-identifier for queries.
    )

    # Make the request
    response = client.answer_query(request)

    # Handle the response
    print(response)

    return response

הגדרת קוד השפה של התשובה

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

REST

כדי ליצור תשובה באמצעות מודל ששונה ממודל ברירת המחדל:

  1. מריצים את פקודת ה-curl הבאה:

    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "answerGenerationSpec": {
               "answerLanguageCode": "ANSWER_LANGUAGE_CODE"
               }
          }'
    

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

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים שרוצים לשלוח אליה שאילתה.
    • QUERY: מחרוזת טקסט חופשי שמכילה את השאלה או את שאילתת החיפוש.
    • ANSWER_LANGUAGE_CODE: קוד שפה לתשובה. צריך להשתמש בתגי שפה שמוגדרים ב-BCP47: תגים לזיהוי שפות.

Python

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Python.

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

from google.api_core.client_options import ClientOptions
from google.cloud import discoveryengine_v1 as discoveryengine

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION"                    # Values: "global", "us", "eu"
# engine_id = "YOUR_APP_ID"


def answer_query_sample(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.AnswerQueryResponse:
    #  For more information, refer to:
    # https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store
    client_options = (
        ClientOptions(api_endpoint=f"{location}-discoveryengine.googleapis.com")
        if location != "global"
        else None
    )

    # Create a client
    client = discoveryengine.ConversationalSearchServiceClient(
        client_options=client_options
    )

    # The full resource name of the Search serving config
    serving_config = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/servingConfigs/default_serving_config"

    # Optional: Options for query phase
    # The `query_understanding_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/QueryUnderstandingSpec
    query_understanding_spec = discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec(
        query_rephraser_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryRephraserSpec(
            disable=False,  # Optional: Disable query rephraser
            max_rephrase_steps=1,  # Optional: Number of rephrase steps
        ),
        # Optional: Classify query types
        query_classification_spec=discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec(
            types=[
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.ADVERSARIAL_QUERY,
                discoveryengine.AnswerQueryRequest.QueryUnderstandingSpec.QueryClassificationSpec.Type.NON_ANSWER_SEEKING_QUERY,
            ]  # Options: ADVERSARIAL_QUERY, NON_ANSWER_SEEKING_QUERY or both
        ),
    )

    # Optional: Options for answer phase
    # The `answer_generation_spec` below includes all available query phase options.
    # For more details, refer to https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/AnswerGenerationSpec
    answer_generation_spec = discoveryengine.AnswerQueryRequest.AnswerGenerationSpec(
        ignore_adversarial_query=False,  # Optional: Ignore adversarial query
        ignore_non_answer_seeking_query=False,  # Optional: Ignore non-answer seeking query
        ignore_low_relevant_content=False,  # Optional: Return fallback answer when content is not relevant
        model_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.ModelSpec(
        # Use the 2026 stable production model for answer generation
        model_version="gemini-2.5-flash/answer_gen/stable",
        ),
        prompt_spec=discoveryengine.AnswerQueryRequest.AnswerGenerationSpec.PromptSpec(
            preamble="Give a detailed answer.",  # Optional: Natural language instructions for customizing the answer.
        ),
        include_citations=True,  # Optional: Include citations in the response
        answer_language_code="en",  # Optional: Language code of the answer
    )

    # Initialize request argument(s)
    request = discoveryengine.AnswerQueryRequest(
        serving_config=serving_config,
        query=discoveryengine.Query(text="What is Vertex AI Search?"),
        session=None,  # Optional: include previous session ID to continue a conversation
        query_understanding_spec=query_understanding_spec,
        answer_generation_spec=answer_generation_spec,
        user_pseudo_id="user-pseudo-id",  # Optional: Add user pseudo-identifier for queries.
    )

    # Make the request
    response = client.answer_query(request)

    # Handle the response
    print(response)

    return response

התאמה אישית של תשובות

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

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

כדי להוסיף מידע אישי על המשתמש שמבצע שאילתה וליצור תשובה שמתחשבת במידע האישי, צריך לבצע את הפעולות הבאות:

  1. מריצים את פקודת ה-curl הבאה:

    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
    -d '{
        "query": { "text": "QUERY"},
        "endUserSpec": {
           "endUserMetadata": [
             {
               "chunkInfo": {
                  "content": "PERSONALIZED_INFO",
                  "documentMetadata":  { "title": "INFO_DESCRIPTION"}
               }
             }
           ]
        }
      }'
    

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

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים שרוצים לשלוח אליה שאילתה.
    • QUERY: מחרוזת טקסט חופשי שמכילה את השאלה או את שאילתת החיפוש.
    • PERSONALIZATION_INFO: מחרוזת שמכילה מידע ספציפי למשתמש שמבצע את השאילתה. לדוגמה, This customer has a Pixel 6 Pro purchased over a period of 24-months starting 2023-01-15. This customer is on the Business Plus International plan. No payment is due at this time. המחרוזת הזו יכולה להכיל עד 8,000 תווים.
    • INFO_DESCRIPTION: מחרוזת שמתארת בקצרה את פרטי ההתאמה האישית – לדוגמה, Customer profile data, including model, plan, and billing status. המודל משתמש גם בתיאור הזה וגם בפרטי ההתאמה האישית כדי ליצור תשובה מותאמת לשאילתה.

יצירת תרשימים לתשובות

השיטה answer יכולה ליצור תרשימים ולהחזיר אותם כחלק מהתשובה לשאילתה.

אתם יכולים לבקש באופן ספציפי שהתשובה תכלול תרשים. לדוגמה: "Plot the year-on-year growth rate of small business payments over years with available data" (צור תרשים של קצב הצמיחה השנתי של תשלומים לעסקים קטנים לאורך השנים עם הנתונים הזמינים). אם המערכת קובעת שיש מספיק נתונים, היא מחזירה תרשים. בדרך כלל, מוצג טקסט של תשובה כלשהי לצד התרשים.

בנוסף, אם יש מספיק נתונים ליצירת תרשים, שיטת התשובה יכולה להחזיר תרשים גם אם השאילתה לא ביקשה במפורש תרשים. לדוגמה, ‫"What was the improvement in HDI scores associated with more access to clean drinking water in the decade between 2010 and 2020?"‎

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

תרשים מורכב שמכיל ארבעה תרשימים קטנים יותר

מגבלה

השאילתות צריכות להיות באנגלית.

תרחישים נפוצים של כשלים

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

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

לפני שמתחילים

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

התהליך

REST

כדי לקבל תשובה שיכולה לכלול תרשים שנוצר מהנתונים במאגר הנתונים, קוראים לשיטה answer באופן הבא:

  1. מריצים את פקודת ה-curl הבאה:

    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1beta/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "answerGenerationSpec": {
              "model_spec": {
                 "model_version": "MODEL_VERSION"
             },
              "multimodalSpec": {
                 "imageSource": "IMAGE_SOURCE"
                 }
            }
          }'
    

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

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים שרוצים לשלוח אליה שאילתה.
    • QUERY: מחרוזת טקסט חופשי באנגלית שמכילה את השאלה או את שאילתת החיפוש.
    • MODEL_VERSION: גרסת המודל gemini-2.0-flash-001/answer_gen/v1 ואילך. מידע נוסף זמין במאמר גרסאות של מודלים ליצירת תשובות ומחזור החיים שלהן.
    • IMAGE_SOURCE: ערך מתוך רשימה שמשמש לבקשה שהתשובה תכלול תרשים שנוצר, FIGURE_GENERATION_ONLY, או שהתשובה תכלול תרשים שנוצר או תמונה קיימת ממאגרי הנתונים, ALL_AVAILABLE_SOURCES.

אחזור תמונות קיימות ממאגר הנתונים

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

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

אם imageSource הוא CORPUS_IMAGE_ONLY או ALL_AVAILABLE_SOURCES, אפשר להשתמש בשיטה answer כדי לאחזר תמונות ממאגר הנתונים לפי הצורך. עם זאת, הפעלת ההגדרה הזו לא אומרת שתמיד יוחזרו תמונות.

מקבלים תמונה אחת (מקסימום) לכל תשובה. אפשר להוסיף כמה תמונות לציטוט.

מגבלות

  • האפליקציה שבה אתם משתמשים צריכה להיות מחוברת למאגר נתונים לא מובנה. אי אפשר להחזיר תמונות מאתרים או ממאגרי נתונים מובְנים.

  • השאילתות צריכות להיות באנגלית.

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

התהליך

REST

כדי להחזיר תשובה שיכולה לכלול תמונה ממאגר הנתונים, צריך לבצע קריאה ל-method‏ answer באופן הבא:

  1. מריצים את פקודת ה-curl הבאה:

    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1beta/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "answerGenerationSpec": {
              "model_spec": {
                 "model_version": "MODEL_VERSION"
              },
              includeCitations: true,
              "multimodalSpec": {
                 "imageSource": "IMAGE_SOURCE"
                 }
            }
          }'
    

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

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים שרוצים לשלוח אליה שאילתה.
    • QUERY: מחרוזת טקסט חופשי באנגלית שמכילה את השאלה או את שאילתת החיפוש.
    • MODEL_VERSION: גרסת המודל gemini-2.0-flash-001/answer_gen/v1 ואילך. מידע נוסף זמין במאמר גרסאות של מודלים ליצירת תשובות ומחזור החיים שלהן.
    • IMAGE_SOURCE: ערך מתוך רשימה מוגדרת מראש שמציין אם התשובה צריכה לכלול תמונה ממאגר הנתונים, CORPUS_IMAGE_ONLY, או אם התשובה יכולה לכלול תמונה ממאגר הנתונים או תרשים שנוצר, ALL_AVAILABLE_SOURCES.

פקודות לשאלות המשך

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

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

דוגמה לסשן המשך

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

  • תור 1:

    • אתה: מתי הכי כדאי לצאת לחופשה במקסיקו?

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

  • תור 2:

    • אתה: מהו שער החליפין?

    • תשובה עם שאלות המשך: דולר אחד שווה בערך ל-17.65 פסו מקסיקני.

  • תור 3:

    • אתם: מה הטמפרטורה הממוצעת בדצמבר?

    • תשובה עם שאלות המשך: הטמפרטורה הממוצעת משתנה בין 21 ל-26 מעלות צלזיוס. הטמפרטורה הממוצעת בקנקון היא ‎~ 25°C.

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

מידע על סשנים

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

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

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

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

בנוסף להודעות של השאילתה והתשובה, משאב הסשן כולל:

  • שם ייחודי (מזהה הסשן).

  • סטטוס (בתהליך או הושלם).

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

  • שעת התחלה ושעת סיום.

  • תור, שהוא זוג של שאילתה ותשובה.

לפני שמתחילים

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

שמירת פרטי הסשן וקבלת תשובות

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

REST

כדי להשתמש בשורת הפקודה כדי ליצור סשן וליצור תגובות מהקלט של המשתמש, פועלים לפי השלבים הבאים:

  1. מציינים את האפליקציה שבה רוצים לשמור את הסשן:

    curl -X POST \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/sessions" \
      -d '{
            "userPseudoId": "USER_PSEUDO_ID"
          }'
    

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

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

    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים.

    • USER_PSEUDO_ID: מחרוזת בקידוד UTF-8, שמשמשת כמזהה ייחודי פסאודונימי למעקב אחרי המשתמשים. האורך המקסימלי הוא 128 תווים. ‫Google ממליצה מאוד להשתמש בשדה הזה כי הוא משפר את הביצועים של המודל ואת איכות ההתאמה האישית. אפשר להשתמש בקובץ Cookie של HTTP בשדה הזה, כדי לזהות באופן ייחודי מבקר במכשיר יחיד. הנה כמה דברים חשובים שכדאי לזכור:

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

      מידע נוסף זמין במאמר userPseudoId.

    דוגמה לפקודה ולתוצאה

    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)"
    -H "Content-Type: application/json"
    "https://discoveryengine.googleapis.com/v1/projects/my-project-123/locations/global/collections/default_collection/engines/my-app/sessions"
    -d '{
    "userPseudoId": "test_user"
    }'
    
    { "name": "projects/123456/locations/global/collections/default_collection/engines/my-app/sessions/16002628354770206943", "state": "IN_PROGRESS", "userPseudoId": "test_user", "startTime": "2024-09-13T18:47:10.465311Z", "endTime": "2024-09-13T18:47:10.465311Z" }
  2. רושמים את מזהה הסשן, המספרים בסוף השדה name: בתגובת ה-JSON. בדוגמת התוצאה, המזהה הוא 5386462384953257772. תצטרכו את המזהה הזה בשלב הבא.

  3. ליצור תשובה ולהוסיף אותה לסשן באפליקציה:

    curl -X POST \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:answer" \
      -d '{
            "query": { "text": "QUERY"},
            "session": "projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/sessions/SESSION_ID",
              "searchSpec":{ "searchParams": {"filter": "FILTER"} }
    }'
    

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

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים.
    • QUERY: מחרוזת טקסט חופשי שמכילה את השאלה או את שאילתת החיפוש.
    • SESSION_ID: המזהה של הסשן שיצרתם בשלב 1. אלה הספרות בסוף השדה name:, שצוין בשלב 2. בסשן, צריך להשתמש באותו מזהה סשן בכל תור.
    • FILTER: שדה טקסט לסינון החיפוש באמצעות ביטוי סינון. ערך ברירת המחדל הוא מחרוזת ריקה. הדרך שבה בונים את המסנן משתנה בהתאם לסוג הנתונים שיש לכם: נתונים לא מובְנים עם מטא-נתונים, נתונים מובְנים או נתונים מאתר. מידע נוסף זמין במאמרים סינון חיפוש מותאם אישית של נתונים מובְנים או לא מובְנים וסינון חיפוש באתר.

    דוגמה לפקודה ולתוצאה

    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)"
    -H "Content-Type: application/json"
    "https://discoveryengine.googleapis.com/v1/projects/my-project-123/locations/global/collections/default_collection/engines/my-app/servingConfigs/default_search:answer"
    -d '{
    "query": { "text": "Compare bigquery with spanner database?"},
    "session":  "projects/123456/locations/global/collections/default_collection/engines/my-app/sessions/16002628354770206943",
    }'
        
    { "answer": { "name": "projects/123456/locations/global/collections/default_collection/engines/my-app/sessions/16002628354770206943/answers/4861507376861383072", "state": "SUCCEEDED", "answerText": "BigQuery and Spanner are both powerful tools that can be used together to handle transactional and analytical workloads. Spanner is a fully managed relational database optimized for transactional workloads, while BigQuery is a serverless data warehouse designed for business agility. Spanner provides seamless replication across regions in Google Cloud and processes over 1 billion requests per second at peak. BigQuery analyzes over 110 terabytes of data per second. Users can leverage federated queries to read data from Spanner and write to a native BigQuery table. \n", "steps": [ { "state": "SUCCEEDED", "description": "Rephrase the query and search.", "actions": [ { "searchAction": { "query": "Compare bigquery with spanner database?" }, "observation": { "searchResults": [ { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/ecc0e7547253f4ca3ff3328ce89995af", "uri": "https://cloud.google.com/blog/topics/developers-practitioners/how-spanner-and-bigquery-work-together-handle-transactional-and-analytical-workloads", "title": "How Spanner and BigQuery work together to handle transactional and analytical workloads | Google Cloud Blog", "snippetInfo": [ { "snippet": "Using Cloud \u003cb\u003eSpanner\u003c/b\u003e and \u003cb\u003eBigQuery\u003c/b\u003e also allows customers to build their \u003cb\u003edata\u003c/b\u003e clouds using Google Cloud, a unified, open approach to \u003cb\u003edata\u003c/b\u003e-driven transformation ...", "snippetStatus": "SUCCESS" } ] }, { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/d7e238f73608a860e00b752ef80e2941", "uri": "https://cloud.google.com/blog/products/databases/cloud-spanner-gets-stronger-with-bigquery-federated-queries", "title": "Cloud Spanner gets stronger with BigQuery-federated queries | Google Cloud Blog", "snippetInfo": [ { "snippet": "As enterprises compete for market share, their need for real-time insights has given rise to increased demand for transactional \u003cb\u003edatabases\u003c/b\u003e to support \u003cb\u003edata\u003c/b\u003e ...", "snippetStatus": "SUCCESS" } ] }, { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/e10a5a3c267dc61579e7c00fefe656eb", "uri": "https://cloud.google.com/blog/topics/developers-practitioners/replicating-cloud-spanner-bigquery-scale", "title": "Replicating from Cloud Spanner to BigQuery at scale | Google Cloud Blog", "snippetInfo": [ { "snippet": "... \u003cb\u003eSpanner data\u003c/b\u003e into \u003cb\u003eBigQuery\u003c/b\u003e for analytics. In this post, you will learn how to efficiently use this feature to replicate large tables with high throughput ...", "snippetStatus": "SUCCESS" } ] }, ... { "document": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/8100ad36e1cac149eb9fc180a41d8f25", "uri": "https://cloud.google.com/blog/products/gcp/from-nosql-to-new-sql-how-spanner-became-a-global-mission-critical-database", "title": "How Spanner became a global, mission-critical database | Google Cloud Blog", "snippetInfo": [ { "snippet": "... SQL \u003cb\u003evs\u003c/b\u003e. NoSQL dichotomy may no longer be relevant." The \u003cb\u003eSpanner\u003c/b\u003e SQL query processor, while recognizable as a standard implementation, has unique ...", "snippetStatus": "SUCCESS" } ] } ] } } ] } ] }, "session": { "name": "projects/123456/locations/global/collections/default_collection/engines/my-app/sessions/16002628354770206943", "state": "IN_PROGRESS", "userPseudoId": "test_user", "turns": [ { "query": { "queryId": "projects/123456/locations/global/questions/741830", "text": "Compare bigquery with spanner database?" }, "answer": "projects/123456/locations/global/collections/default_collection/engines/my-app/sessions/16002628354770206943/answers/4861507376861383072" } ], "startTime": "2024-09-13T18:47:10.465311Z", "endTime": "2024-09-13T18:47:10.465311Z" }, "answerQueryToken": "NMwKDAjFkpK3BhDU24uZAhIkNjZlNDIyZWYtMDAwMC0yMjVmLWIxMmQtZjQwMzA0M2FkYmNj" }
  4. חוזרים על שלב 3 לכל שאילתה חדשה בסשן.

Python

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Python.

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

from google.cloud import discoveryengine_v1 as discoveryengine


def create_session(
    project_id: str,
    location: str,
    engine_id: str,
    user_pseudo_id: str,
) -> discoveryengine.Session:
    """Creates a session.

    Args:
        project_id: The ID of your Google Cloud project.
        location: The location of the app.
        engine_id: The ID of the app.
        user_pseudo_id: A unique identifier for tracking visitors. For example, this
          could be implemented with an HTTP cookie, which should be able to
          uniquely identify a visitor on a single device.
    Returns:
        discoveryengine.Session: The newly created Session.
    """

    client = discoveryengine.SessionServiceClient()

    session = client.create_session(
        # The full resource name of the engine
        parent=f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}",
        session=discoveryengine.Session(user_pseudo_id=user_pseudo_id),
    )

    # Send Session name in `answer_query()`
    print(f"Session: {session.name}")
    return session

קבלת סשן ממאגר הנתונים

הפקודה הבאה מראה איך להפעיל את השיטה get ולקבל סשן ממאגר הנתונים.

REST

כדי לקבל סשן ממאגר נתונים:

  1. מריצים את פקודת ה-curl הבאה:

    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/sessions/SESSION_ID"
    

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

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים.
    • SESSION_ID: המזהה של הסשן שרוצים לקבל.

Python

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Python.

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

from google.cloud import discoveryengine_v1 as discoveryengine


def get_session(
    project_id: str,
    location: str,
    engine_id: str,
    session_id: str,
) -> discoveryengine.Session:
    """Retrieves a session.

    Args:
        project_id: The ID of your Google Cloud project.
        location: The location of the app.
        engine_id: The ID of the app.
        session_id: The ID of the session.
    """

    client = discoveryengine.SessionServiceClient()

    # The full resource name of the session
    name = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/sessions/{session_id}"

    session = client.get_session(name=name)

    print(f"Session details: {session}")
    return session

מחיקת סשן מהאפליקציה

הפקודה הבאה מראה איך להפעיל את השיטה delete ולמחוק סשן ממאגר הנתונים.

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

REST

כדי למחוק סשן מאפליקציה:

  1. מריצים את פקודת ה-curl הבאה:

    curl -X DELETE -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/sessions/SESSION_ID"
    

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

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים.
    • SESSION_ID: המזהה של הסשן שרוצים למחוק.

Python

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Python.

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

from google.cloud import discoveryengine_v1 as discoveryengine


def delete_session(
    project_id: str,
    location: str,
    engine_id: str,
    session_id: str,
) -> None:
    """Deletes a session.

    Args:
        project_id: The ID of your Google Cloud project.
        location: The location of the app.
        engine_id: The ID of the app.
        session_id: The ID of the session.
    """

    client = discoveryengine.SessionServiceClient()

    # The full resource name of the session
    name = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/sessions/{session_id}"

    client.delete_session(name=name)

    print(f"Session {name} deleted.")

עדכון סשן

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

  • סימון פעילות כהושלמה
  • מיזוג ההודעות מסשן אחד לסשן אחר
  • שינוי מזהה פסאודו של משתמש

הפקודה הבאה מראה איך להפעיל את השיטה patch ולעדכן סשן במאגר הנתונים.

REST

כדי לעדכן הפעלה מאפליקציה:

  1. מריצים את פקודת ה-curl הבאה:

    curl -X PATCH \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/sessions/SESSION_ID?updateMask=state" \
      -d '{
            "state": "NEW_STATE"
          }'
    

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

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים.
    • SESSION_ID: המזהה של הסשן שרוצים לעדכן.
    • NEW_STATE: הערך החדש של המצב, לדוגמה IN_PROGRESS.

Python

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Python.

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

from google.cloud import discoveryengine_v1 as discoveryengine
from google.protobuf import field_mask_pb2


def update_session(
    project_id: str,
    location: str,
    engine_id: str,
    session_id: str,
) -> discoveryengine.Session:
    """Updates a session.

    Args:
        project_id: The ID of your Google Cloud project.
        location: The location of the app.
        engine_id: The ID of the app.
        session_id: The ID of the session.
    Returns:
        discoveryengine.Session: The updated Session.
    """
    client = discoveryengine.SessionServiceClient()

    # The full resource name of the session
    name = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/sessions/{session_id}"

    session = discoveryengine.Session(
        name=name,
        state=discoveryengine.Session.State.IN_PROGRESS,  # Options: IN_PROGRESS, STATE_UNSPECIFIED
    )

    # Fields to Update
    update_mask = field_mask_pb2.FieldMask(paths=["state"])

    session = client.update_session(session=session, update_mask=update_mask)
    print(f"Updated session: {session.name}")
    return session

הצגת רשימה של כל הפעילויות

הפקודה הבאה מראה איך להפעיל את השיטה list ולרשום את הסשנים במאגר הנתונים.

REST

כדי להציג את רשימת הסשנים של אפליקציה:

  1. מריצים את פקודת ה-curl הבאה:

    curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/sessions"
    

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

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים.

Python

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Python.

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

from google.cloud import discoveryengine_v1 as discoveryengine


def list_sessions(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.ListSessionsResponse:
    """Lists all sessions associated with a data store.

    Args:
        project_id: The ID of your Google Cloud project.
        location: The location of the app.
        engine_id: The ID of the app.
    Returns:
        discoveryengine.ListSessionsResponse: The list of sessions.
    """

    client = discoveryengine.SessionServiceClient()

    # The full resource name of the engine
    parent = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}"

    response = client.list_sessions(
        request=discoveryengine.ListSessionsRequest(
            parent=parent,
            filter='state="IN_PROGRESS"',  # Optional: Filter requests by userPseudoId or state
            order_by="update_time",  # Optional: Sort results
        )
    )

    print("Sessions:")
    for session in response.sessions:
        print(session)

    return response

הצגת רשימת הסשנים של משתמש

הפקודה הבאה מראה איך להפעיל את השיטה list כדי להציג רשימה של סשנים שמשויכים למשתמש או למבקר.

REST

כדי להציג רשימה של סשנים שמשויכים למשתמש או למבקר, מבצעים את הפעולות הבאות:

  1. מריצים את פקודת ה-curl הבאה:

    curl -X GET \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/sessions?filter=userPseudoId=USER_PSEUDO_ID"
    

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

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים.
    • USER_PSEUDO_ID: המזהה הפסאודו אנונימי של המשתמש שהסשנים שלו רוצים להציג.

Python

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Python.

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

from google.cloud import discoveryengine_v1 as discoveryengine


def list_sessions(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.ListSessionsResponse:
    """Lists all sessions associated with a data store.

    Args:
        project_id: The ID of your Google Cloud project.
        location: The location of the app.
        engine_id: The ID of the app.
    Returns:
        discoveryengine.ListSessionsResponse: The list of sessions.
    """

    client = discoveryengine.SessionServiceClient()

    # The full resource name of the engine
    parent = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}"

    response = client.list_sessions(
        request=discoveryengine.ListSessionsRequest(
            parent=parent,
            filter='state="IN_PROGRESS"',  # Optional: Filter requests by userPseudoId or state
            order_by="update_time",  # Optional: Sort results
        )
    )

    print("Sessions:")
    for session in response.sessions:
        print(session)

    return response

הצגת רשימה של סשנים של משתמש ומצב

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

REST

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

  1. מריצים את פקודת ה-curl הבאה:

    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/sessions?filter=userPseudoId=USER_PSEUDO_ID%20AND%20state=STATE"
    

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

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים.
    • USER_PSEUDO_ID: המזהה הפסאודו אנונימי של המשתמש שהסשנים שלו רוצים להציג.
    • STATE: מצב הסשן: ‫STATE_UNSPECIFIED (סגור או לא ידוע) או ‫IN_PROGRESS (פתוח).

Python

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Python.

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

from google.cloud import discoveryengine_v1 as discoveryengine


def list_sessions(
    project_id: str,
    location: str,
    engine_id: str,
) -> discoveryengine.ListSessionsResponse:
    """Lists all sessions associated with a data store.

    Args:
        project_id: The ID of your Google Cloud project.
        location: The location of the app.
        engine_id: The ID of the app.
    Returns:
        discoveryengine.ListSessionsResponse: The list of sessions.
    """

    client = discoveryengine.SessionServiceClient()

    # The full resource name of the engine
    parent = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}"

    response = client.list_sessions(
        request=discoveryengine.ListSessionsRequest(
            parent=parent,
            filter='state="IN_PROGRESS"',  # Optional: Filter requests by userPseudoId or state
            order_by="update_time",  # Optional: Sort results
        )
    )

    print("Sessions:")
    for session in response.sessions:
        print(session)

    return response