קבלת תשובות ופריטים להמשך טיפול (גרסה קודמת)

בדף הזה מוסבר איך להטמיע את התכונה "חיפוש עם תשובה ושאלות המשך" ב-Gemini Enterprise באמצעות הפעלות של methods.

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

תכונות של שיטת המענה

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

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

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

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

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

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

ב-Gemini Enterprise יש שתי שיטות לשליחת שאילתות לאפליקציות. יש להם תכונות שונות, אבל הן חופפות.

משתמשים ב-method‏ answer במקרים הבאים:

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

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

משתמשים בשיטה search במקרים הבאים:

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

  • אתם רוצים לקבל יותר מ-10 תוצאות חיפוש ("קישורים כחולים").

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

    • הטמעות משלכם
    • פקדים למילים נרדפות או להפניות אוטומטיות
    • מאפיינים
    • קודי המדינות של המשתמשים

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

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

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

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

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

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

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

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

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

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

    קלט של משתמשים שאילתות משנה שנוצרו מהשאילתה המורכבת
    אילו עבודות ותחביבים משותפים לאנדי רם ולארנו קלמנט?
    • Andie Ram occupation
    • ארנו קלמנט מקצוע
    • Andie Ram hobby
    • התחביב של ארנו קלמנט
  • לסנתז שאילתות עם כמה שלבים, כדי ששאלות ההמשך יהיו מותאמות להקשר ובעלות מצב (stateful).

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

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

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

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

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

    לדוגמה:

    קלט של משתמשים שני שלבים ליצירת התשובה
    כמה שנים אחרי ש-Google נוסדה היא הגיעה להכנסות של מיליארד דולר? שלב 1:
    [Thought]: I need to know when Google was founded, then I can query it is revenue since then.
    [Act] Search: When was Google founded?[Observe תוצאת חיפוש]: "1998"

    שלב 2:
    [Thought]: Now I need to Google's yearly revenue since 1998, and find out when it exceeded 1 billion for the first time.
    [פעולה] חיפוש: ההכנסות של Google מאז 1998
    [צפייה בתוצאות החיפוש] ההכנסות של Google ב-1998, ההכנסות של Google ב-1999…
    [תשובה]: Google הגיעה להכנסות של יותר ממיליארד דולר ארה"ב בשנת 2003 [1], 5 שנים אחרי שהוקמה ב-1998 [2].

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

הפקודה הבאה מראה איך להפעיל את ה-method‏ 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: מזהה הפרויקט.
    • ‫APP_ID: המזהה של האפליקציה שרוצים לשלוח אליה שאילתה.
    • ‫QUERY: מחרוזת טקסט חופשי שמכילה את השאלה או את שאילתת החיפוש. לדוגמה, "Compare the BigQuery and Spanner databases?‎".

Python

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

כדי לבצע אימות ב-Gemini Enterprise, צריך להגדיר את 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.

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

הפקודה הבאה מראה איך להפעיל את ה-method‏ 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": {
               "queryRephraserSpec": {
                  "disable": true
            }
        }
          }'
    
    

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

    • ‫PROJECT_ID: מזהה הפרויקט.
    • ‫APP_ID: מזהה האפליקציה.
    • ‫QUERY: מחרוזת טקסט חופשי שמכילה את השאלה או את שאילתת החיפוש. לדוגמה, "Compare the BigQuery and Spanner databases?‎".

Python

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

כדי לבצע אימות ב-Gemini Enterprise, צריך להגדיר את 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 ולהחזיר תשובה שנוצרה ורשימה של תוצאות חיפוש. התשובה שונה מהתשובות הקודמות כי מספר שלבי הניסוח מחדש גדל.

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": {
                "queryRephraserSpec": {
                    "maxRephraseSteps": MAX_REPHRASE
                 }
             }
          }'
    

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

    • ‫PROJECT_ID: מזהה הפרויקט.
    • ‫APP_ID: המזהה של האפליקציה שרוצים לשלוח אליה שאילתה.
    • ‫QUERY: מחרוזת טקסט חופשי שמכילה את השאלה או את שאילתת החיפוש. לדוגמה, "Compare the BigQuery and Spanner databases?‎".
    • ‫MAX_REPHRASE: המספר המקסימלי של שלבי ניסוח מחדש. הערך המקסימלי המותר הוא 5. אם המדיניות לא מוגדרת או שהערך שלה נמוך מ-1, הערך הוא ברירת המחדל, 1.

Python

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

כדי לבצע אימות ב-Gemini Enterprise, צריך להגדיר את 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 כדי לבדוק אם שאילתה היא אדברסרית, לא מחפשת תשובה או אף אחת מהאפשרויות.

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

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: מזהה הפרויקט.
    • ‫APP_ID: המזהה של האפליקציה שרוצים לשלוח אליה שאילתה.
    • ‫QUERY: מחרוזת טקסט חופשי שמכילה את השאלה או את שאילתת החיפוש. לדוגמה, "שלום".
    • ‫QUERY_CLASSIFICATION_TYPE: סוגי השאילתות שרוצים לזהות: ADVERSARIAL_QUERY, NON_ANSWER_SEEKING_QUERY או שניהם.

Python

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

כדי לבצע אימות ב-Gemini Enterprise, צריך להגדיר את 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: מזהה הפרויקט.
    • ‫APP_ID: המזהה של האפליקציה שרוצים לשלוח אליה שאילתה.
    • ‫QUERY: מחרוזת טקסט חופשי שמכילה את השאלה או את שאילתת החיפוש. לדוגמה, "Compare the BigQuery and Spanner databases?‎"
    • ‫MAX_RETURN_RESULTS: מספר תוצאות החיפוש שיוחזרו. ערך ברירת המחדל הוא 10.
    • ‫FILTER: המסנן מציין אילו מסמכים נכללים בשאילתה. אם המטא-נתונים של מסמך עומדים במפרט המסנן, המסמך ייכלל בשאילתה. מידע נוסף, כולל תחביר של מסננים, זמין במאמר סינון חיפוש בהתאמה אישית של נתונים מובְנים או לא מובְנים.
    • ‫BOOST_SPEC: מפרט הקידום מאפשר לקדם מסמכים מסוימים בתוצאות החיפוש, מה שיכול להשפיע על התשובה. למידע נוסף, כולל התחביר של מפרט החיזוק, ראו חיזוק תוצאות החיפוש.
    • ‫ORDER_BY: הסדר שבו המסמכים מוחזרים. אפשר לסדר מסמכים לפי שדה באובייקט Document. הביטוי orderBy תלוי אותיות רישיות (case-sensitive). אם השדה הזה לא מזוהה, מוחזרת השגיאה INVALID_ARGUMENT.
    • ‫SEARCH_RESULT_MODE: מציין את מצב תוצאות החיפוש: DOCUMENTS או CHUNKS. מידע נוסף זמין במאמרים ניתוח מסמכים וחלוקה שלהם לחלקים ו-ContentSearchSpec. השדה הזה זמין רק בגרסת v1alpha של ה-API.

Python

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

כדי לבצע אימות ב-Gemini Enterprise, צריך להגדיר את 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. אפשר לשלב בין האפשרויות הבאות לפי הצורך.

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

הפקודה הבאה מדגימה איך להימנע ממענה על שאילתות אדברסריות ועל שאילתות שלא מחפשות תשובה, כשקוראים ל-method‏ 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: מזהה הפרויקט.
    • ‫APP_ID: המזהה של האפליקציה שרוצים לשלוח אליה שאילתה.
    • ‫QUERY: מחרוזת טקסט חופשי שמכילה את השאלה או את שאילתת החיפוש.

Python

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

כדי לבצע אימות ב-Gemini Enterprise, צריך להגדיר את 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

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

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

הפקודה הבאה מראה איך להחזיר את תשובת ברירת המחדל במקרה של תוצאות לא רלוונטיות כשקוראים ל-method‏ 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: מזהה הפרויקט.
    • ‫APP_ID: המזהה של האפליקציה שרוצים לשלוח אליה שאילתה.
    • ‫QUERY: מחרוזת טקסט חופשי שמכילה את השאלה או את שאילתת החיפוש.

Python

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

כדי לבצע אימות ב-Gemini Enterprise, צריך להגדיר את 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"},
            "groundingSpec": {
               "includeGroundingSupports": true,
            }
          }'
    

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

    • ‫PROJECT_ID: מזהה הפרויקט.
    • ‫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"},
            "groundingSpec": {
               "filteringLevel": "FILTER_LEVEL"
            }
          }'
    

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

    • ‫PROJECT_ID: מזהה הפרויקט.
    • ‫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: מזהה הפרויקט.
    • ‫APP_ID: המזהה של האפליקציה שרוצים לשלוח אליה שאילתה.
    • ‫QUERY: מחרוזת טקסט חופשי שמכילה את השאלה או את שאילתת החיפוש.
    • ‫MODEL_VERSION: גרסת המודל שבה רוצים להשתמש כדי ליצור את התשובה. מידע נוסף זמין במאמר גרסאות ומחזור חיים של מודלים ליצירת תשובות.

Python

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

כדי לבצע אימות ב-Gemini Enterprise, צריך להגדיר את 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: מזהה הפרויקט.
    • ‫APP_ID: המזהה של האפליקציה שרוצים לשלוח אליה שאילתה.
    • ‫QUERY: מחרוזת טקסט חופשי שמכילה את השאלה או את שאילתת החיפוש.
    • ‫PREAMBLE: הוראה בשפה טבעית להתאמה אישית של התשובה. לדוגמה, נסו את show the answer format in an ordered list או את give a very detailed answer.

Python

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

כדי לבצע אימות ב-Gemini Enterprise, צריך להגדיר את 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": {
               "includeCitations": INCLUDE_CITATIONS
            }
          }'
    

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

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

Python

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

כדי לבצע אימות ב-Gemini Enterprise, צריך להגדיר את 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: מזהה הפרויקט.
    • ‫APP_ID: המזהה של האפליקציה שרוצים לשלוח אליה שאילתה.
    • ‫QUERY: מחרוזת טקסט חופשי שמכילה את השאלה או את שאילתת החיפוש.
    • ‫ANSWER_LANGUAGE_CODE: קוד השפה של התשובה. צריך להשתמש בתגי שפה שמוגדרים לפי BCP47: Tags for Identifying Languages.

Python

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

כדי לבצע אימות ב-Gemini Enterprise, צריך להגדיר את 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: מזהה הפרויקט.
    • ‫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 יכולה ליצור תרשימים ולהחזיר אותם כחלק מהתשובה לשאילתה.

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

בנוסף, אם יש מספיק נתונים כדי ליצור תרשים, שיטת התשובה יכולה להחזיר תרשים גם אם השאילתה לא ביקשה תרשים באופן מפורש. לדוגמה, "מה היה השיפור בציוני ה-HDI שקשורים לגישה רחבה יותר למים נקיים לשתייה בעשור שבין 2010 ל-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: מזהה הפרויקט.
    • ‫APP_ID: המזהה של האפליקציה שרוצים לשלוח אליה שאילתה.
    • ‫QUERY: מחרוזת טקסט חופשי באנגלית שמכילה את השאלה או את שאילתת החיפוש.
    • ‫MODEL_VERSION: גרסת המודל stable או מודל נתמך אחר, ראו גרסאות ומחזור חיים של מודלים ליצירת תשובות.
    • ‫IMAGE_SOURCE: ערך מספרי שמציין אם התשובה צריכה לכלול תרשים שנוצר, FIGURE_GENERATION_ONLY, או שהתשובה יכולה לכלול תרשים שנוצר או תמונה קיימת ממאגרי הנתונים, ALL_AVAILABLE_SOURCES.

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

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

כשהערך של imageSource הוא CORPUS_IMAGE_ONLY או ALL_AVAILABLE_SOURCES, ה-method‏ 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: מזהה הפרויקט.
    • ‫APP_ID: המזהה של האפליקציה שרוצים לשלוח אליה שאילתה.
    • ‫QUERY: מחרוזת טקסט חופשי באנגלית שמכילה את השאלה או את שאילתת החיפוש.
    • ‫MODEL_VERSION: גרסת המודל stable או מודל נתמך אחר, כמו שמוסבר במאמר גרסאות ומחזור החיים של מודלים ליצירת תשובות.
    • ‫IMAGE_SOURCE: ערך שמציין אם התשובה צריכה לכלול תמונה ממאגר הנתונים (CORPUS_IMAGE_ONLY) או שהיא יכולה לכלול תמונה ממאגר הנתונים או תרשים שנוצר (ALL_AVAILABLE_SOURCES).

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

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

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

דוגמה לסשן עוקב

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

  • תור 1:

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

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

  • תור 2:

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

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

  • תור 3:

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

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

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

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

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

מידע על סשנים

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

סשן מורכב משאילתות טקסט שהמשתמש שולח ומתשובות ש-Gemini Enterprise מחזיר.

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

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

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

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

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

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

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

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

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

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

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: מזהה הפרויקט.

    • ‫APP_ID: מזהה האפליקציה.

    • ‫USER_PSEUDO_ID: זהו מזהה ייחודי למעקב אחרי מבקרים בחיפוש. לדוגמה, אפשר להטמיע את זה באמצעות קובץ Cookie מסוג HTTP, שמזהה באופן ייחודי מבקר במכשיר אחד.

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

    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: מזהה הפרויקט.
    • ‫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

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

כדי לבצע אימות ב-Gemini Enterprise, צריך להגדיר את 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: מזהה הפרויקט.
    • ‫APP_ID: מזהה האפליקציה.
    • ‫SESSION_ID: המזהה של הסשן שרוצים לקבל.

Python

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

כדי לבצע אימות ב-Gemini Enterprise, צריך להגדיר את 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: מזהה הפרויקט.
    • ‫APP_ID: מזהה האפליקציה.
    • ‫SESSION_ID: המזהה של הסשן שרוצים למחוק.

Python

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

כדי לבצע אימות ב-Gemini Enterprise, צריך להגדיר את 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: מזהה הפרויקט.
    • ‫APP_ID: מזהה האפליקציה.
    • ‫SESSION_ID: המזהה של הסשן שרוצים לעדכן.
    • ‫NEW_STATE: הערך החדש של המצב, לדוגמה IN_PROGRESS.

Python

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

כדי לבצע אימות ב-Gemini Enterprise, צריך להגדיר את 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: מזהה הפרויקט.
    • ‫APP_ID: מזהה האפליקציה.

Python

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

כדי לבצע אימות ב-Gemini Enterprise, צריך להגדיר את 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: מזהה הפרויקט.
    • ‫APP_ID: מזהה האפליקציה.
    • ‫USER_PSEUDO_ID: המזהה המדומה של המשתמש שאת הסשנים שלו רוצים להציג ברשימה.

Python

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

כדי לבצע אימות ב-Gemini Enterprise, צריך להגדיר את 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

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

הפקודה הבאה מראה איך להפעיל את ה-method‏ 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: מזהה הפרויקט.
    • ‫APP_ID: מזהה האפליקציה.
    • ‫USER_PSEUDO_ID: המזהה המדומה של המשתמש שאת הסשנים שלו רוצים להציג ברשימה.
    • ‫STATE: מצב הסשן: STATE_UNSPECIFIED (סגור או לא ידוע) או IN_PROGRESS (פתוח).

Python

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

כדי לבצע אימות ב-Gemini Enterprise, צריך להגדיר את 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