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

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

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

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

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

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

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

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

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

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

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

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

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

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

משתמשים ב-search כשרוצים:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    לדוגמה:

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

    שלב 2:
    [מחשבה]: עכשיו אני צריך לחפש ב-Google את ההכנסה השנתית מאז 1998, ולגלות מתי היא עברה את המיליארד בפעם הראשונה.
    [פעולה] חיפוש: ההכנסות של Google מאז 1998
    [התבוננות בתוצאות החיפוש] ההכנסות של Google בשנת 1998, ההכנסות של Google בשנת 1999…
    [תשובה]: ההכנסות של Google הגיעו ליותר ממיליארד דולר ארה"ב בשנת 2003 [1], 5 שנים אחרי שהיא נוסדה ב-1998 [2].

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

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

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

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

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

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

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

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

  • קבלת ציון תמיכה לכל טענה (משפט בתשובה שנוצרה). ציון התמיכה הוא ערך נקודה צפה בטווח [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: מחרוזת טקסט חופשי שמכילה את השאלה או את שאילתת החיפוש. לדוגמה, "השוואה בין מסדי הנתונים של BigQuery ו-Spanner".

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

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

הפקודה הבאה מראה איך להפעיל את המתודה 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

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

הפקודה הבאה מראה איך להפעיל את המתודה 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."

הפקודה הבאה מראה איך להחזיר את תשובת ברירת המחדל במקרה של תוצאות לא רלוונטיות כשמפעילים את המתודה 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, השיטה 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 מעלות צלזיוס. הטמפרטורה הממוצעת בקנקון היא ‎~ 77°F.

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

כששואלים "What is the best time of the year to vacation in Mexico?‎" (מה הזמן הכי טוב בשנה לצאת לחופשה במקסיקו?), בנוסף לתשובה לשאלה, התשובה וההמשך יכולים להציע שאלות נוספות שאפשר לשאול, כמו "What is the cheapest month to vacation in Mexico?‎" (מה החודש הכי זול לצאת לחופשה במקסיקו?) ו-"What are the tourist months in Mexico?‎" (מהם חודשי התיירות במקסיקו?).

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

מידע על סשנים

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

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

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

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

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

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

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

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

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

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

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

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

REST

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

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

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

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

    • ‫PROJECT_ID: מזהה הפרויקט.

    • ‫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

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

הפקודה הבאה מראה איך להפעיל את המתודה 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