התחלה מהירה עם חנות לדוגמה ב-Gemini

במדריך הזה מוסבר איך ליצור באופן איטרטיבי פרומפטים עם כמה דוגמאות (few-shot) ולאחזר אותם באופן דינמי מ-Example Store כדי לתקן את ההתנהגות של מודל שפה גדול (LLM). כדי לעשות את זה:

  • יוצרים מכונה של Example Store‏ (ExampleStore).

  • יוצרים דוגמאות על סמך התשובה מ-Gemini ומעלים את הדוגמאות האלה למכונה של Example Store.

  • אחזור דינמי של הדוגמאות מ-Example Store כדי להנחות את ה-LLM להתנהגות הרצויה.

  • מנקים.

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

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

הגדרת הפרויקט

  1. נכנסים לחשבון Google Cloud . אנחנו ממליצים למשתמשים חדשים ב- Google Cloud ליצור חשבון כדי שיוכלו להעריך את הביצועים של המוצרים שלנו בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300$ להרצה, לבדיקה ולפריסה של עומסי העבודה.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Gemini Enterprise Agent Platform API, if it is not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Gemini Enterprise Agent Platform API, if it is not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  8. אם בחרתם פרויקט, ודאו שיש לכם את התפקיד משתמש בפלטפורמת Agent‏ (roles/aiplatform.user) ב-IAM בפרויקט.

אימות ב-Agent Platform

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

  1. התקינו את ה-CLI של Google Cloud.

  2. אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

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

    gcloud auth application-default login

    אם אתם משתמשים ב-Cloud Shell, אתם לא צריכים לעשות את זה.

    אם מוחזרת שגיאת אימות ואתם משתמשים בספק זהויות חיצוני (IdP), ודאו ש נכנסתם ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

למידע נוסף, ראו הגדרת ADC לסביבת פיתוח מקומית במאמרי העזרה בנושא אימות Google Cloud .

ייבוא ספריות

  1. מריצים את הפקודה הבאה כדי להתקין את Agent Platform SDK לחנות לדוגמה.

    pip install --upgrade google-cloud-aiplatform>=1.87.0
  2. אפשר להשתמש בדוגמת הקוד הבאה כדי לייבא ולהפעיל את ה-SDK של Example Store.

    import vertexai
    from vertexai.preview import example_stores
    
    vertexai.init(
      project="PROJECT_ID",
      location="LOCATION"
    )
    

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

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

    • ‫LOCATION: האזור שלכם. יש תמיכה רק ב-us-central1.

יצירת מכונה של Example Store

כדי ליצור מכונה של Example Store שמשתמשת במודל ההטמעה text-embedding-005, משתמשים בדוגמת הקוד הבאה.

example_store = example_stores.ExampleStore.create(
    example_store_config=example_stores.ExampleStoreConfig(
        vertex_embedding_model="text-embedding-005"
    )
)

שימו לב: יצירת חנות לדוגמה נמשכת כמה דקות.

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

העלאת דוגמאות למכונה של Example Store

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

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

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

    from google.genai import types as genai_types
    
    get_current_weather_func = genai_types.FunctionDeclaration(
      name="get_current_weather",
      description="Get the current weather in a given location",
      parameters={
        "type": "object",
        "properties": {
          "location": {
            "type": "string",
            "description": "The city name of the location for which to get the weather."
          }
        },
      },
    )
    
  2. שולחים בקשה ל-Gemini ליצור תוכן באמצעות הפונקציה get_current_weather.

    איך יוצרים לקוח ב-Gen AI SDK

    from google import genai
    
    client = genai.Client(
        http_options=genai_types.HttpOptions(api_version="v1"),
        vertexai=True,
        project="PROJECT_ID",
        location="LOCATION")
    
    user_content = genai_types.Content(
      role="user",
      parts=[genai_types.Part(text="What is the weather like in Boston?")],
    )
    response = client.models.generate_content(
      model="gemini-3.5-flash",
      user_content,
      config=genai_types.GenerateContentConfig(
        tools=[
          genai_types.Tool(function_declarations=[get_current_weather_func])]
      )
    )
    
  3. כדי ליצור ולהעלות דוגמה, מבצעים אחת מהפעולות הבאות:

    • אם התשובה מה-LLM מציגה את ההתנהגות הצפויה, משתמשים בדוגמת הקוד הבאה כדי ליצור דוגמה על סמך התשובה ולהעלות אותה ל-Example Store.

      function_response = genai_types.Content(
        parts=[
          genai_types.Part(
            function_response={
              "name": "get_current_weather",
              "response": {
                "location": "New York, NY", "temperature": 38,
                "description": "Partly Cloudy",
                "icon": "partly-cloudy", "humidity": 65,
                "wind": { "speed": 10, "direction": "NW" }
              }
            }
          )
        ]
      )
      final_model_response = genai_types.Content(
        role="model",
        parts=[genai_types.Part(text="The weather in NYC is 38 degrees and partly cloudy.")],
      )
      example = {
        "contents_example": {
          "contents": [user_content.to_json_dict()],
          "expected_contents": [
            {"content": response.candidates[0].content.to_json_dict()},
            {"content": function_response.to_json_dict()},
            {"content": final_model_response.to_json_dict()},
          ],
        },
        "search_key": user_content.parts[0].text,
      }
      example_store.upsert_examples(examples=[example])
      
    • לחלופין, אם התשובה לא כוללת את כל הפונקציות או התוצאות שציפיתם להן, או אם אתם רואים שהמודל מתקשה להסיק מסקנות, אתם יכולים להשתמש בדוגמת הקוד הבאה כדי ליצור תשובה שתתקן את התנהגות המודל.

      expected_function_call = genai_types.Content(
        parts=[
          genai_types.Part(
            function_call={
              "name": "get_current_weather",
              "args": {"location": "New York, NY"}
            }
          )
        ]
      )
      function_response = genai_types.Content(
        parts=[
          genai_types.Part(
            function_response={
              "name": "get_current_weather",
              "response": {
                "location": "New York, NY", "temperature": 38,
                "description": "Partly Cloudy",
                "icon": "partly-cloudy", "humidity": 65,
                "wind": { "speed": 10, "direction": "NW" }
              }
            }
          )
        ]
      )
      final_model_response = genai_types.Content(
        role="model",
        parts=[genai_types.Part(text="The weather in NYC is 38 degrees and partly cloudy.")],
      )
      example = {
        "contents_example": {
          "contents": [user_content.to_json_dict()],
          "expected_contents": [
            {"content": expected_function_call.to_json_dict()},
            {"content": function_response.to_json_dict()},
            {"content": final_model_response.to_json_dict()},
          ],
        },
        "search_key": user_content.parts[0].text,
      }
      example_store.upsert_examples(examples=[example])
      
  4. חוזרים על שלבים 2 ו-3 כדי ליצור ולהעלות כמה דוגמאות, לפי הצורך. אם המודל מתנהג בצורה לא צפויה או שהדוגמאות שהעליתם לא מכסות את כל הפונקציות, התוצאות או הנימוקים שאתם מצפים להם, אתם יכולים להעלות דוגמאות נוספות. מידע נוסף על המקרים שבהם צריך להעלות דוגמאות נוספות זמין במאמר העלאת דוגמאות.

אחזור דוגמאות ושימוש בהן באמצעות Gemini

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

הגדרת פונקציות עזר לעיצוב דוגמאות

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

import abc
import jinja2
import json

from google.protobuf import json_format
# --BOILERPLATE CODE FOR FORMATTING--

EXAMPLES_PREAMBLE = """<EXAMPLES>
The following are examples of user queries and model responses using the available python libraries.

Begin few-shot
"""

EXAMPLES_POSTAMBLE = """
End few-shot

Now, try to follow these examples and complete the following conversation:
</EXAMPLES>
"""

EXAMPLE_PREAMBLE = "EXAMPLE"

TEMPLATE = """
"""

class ExampleStorePrompt:

    def __init__(
          self, template = TEMPLATE, example_preamble = EXAMPLE_PREAMBLE,
          examples_preamble = EXAMPLES_PREAMBLE,
          examples_postamble = EXAMPLES_POSTAMBLE):

        self.template = jinja2.Template(template)
        self.example_preamble = example_preamble
        self.examples_preamble = examples_preamble
        self.examples_postamble = examples_postamble

    @abc.abstractmethod
    def process_function_response(self, function_response):
        return json.dumps(function_response)

    @abc.abstractmethod
    def process_function_call(self, function_call):
        args_list = []
        for key, value in function_call.get("args", []).items():
            if isinstance(value, str):
                # Wrap strings in quotes.
                value = f'"{value}"'
            if isinstance(value, list):
                value = ', '.join(
                    f'"{item}"' if isinstance(item, str)
                    else str(item) for item in value)
                value = f"[{value}]"
            if isinstance(value, dict):
                value = json.dumps(value)
            args_list.append(f'{key}={value}')
        args = ", ".join(args_list)
        return f"```\n{function_call.get('name')}({args})\n```"

    @abc.abstractmethod
    def process_part(self, part):
        if "function_call" in part:
            return self.process_function_call(part["function_call"])
        if "text" in part:
            return part.get("text")
        if "function_response" in part:
            return self.process_function_response(part["function_response"])

    @abc.abstractmethod
    def process_content(self, content):
        response = []
        for part in content.get("parts", []):
            response.append(self.process_part(part))
        return [content.get("role"), response]

    @abc.abstractmethod
    def example_formatter(self, example: dict):
        response = []
        for content in example.get("contents", []):
            response.append(self.process_content(content))
        for content in example.get("expected_contents", []):
            content = content.get("content", {})
            response.append(self.process_content(content))
        return response

    def get_prompt(self, examples: list):
        if not examples:
          return ""
        examples = [self.example_formatter(example) for example in examples]
        return self.template.render(
            examples=examples,
            example_preamble=self.example_preamble,
            examples_preamble=self.examples_preamble,
            examples_postamble=self.examples_postamble
        )

חיפוש דוגמאות רלוונטיות

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

query = "what's the fastest way to get to disney from lax"

# Search for relevant examples.
examples = example_store.search_examples(
  {"stored_contents_example_key": query}, top_k=3)

prompt = ExampleStorePrompt().get_prompt(examples.get("results", []))

model_response = client.models.generate_content(
    model="gemini-3.5-flash",
    contents="How do I get to LAX?",
    config=genai_types.GenerateContentConfig(
      system_instruction=prompt,
      tools=[
        genai_types.Tool(function_declarations=[get_current_weather_func])]
  )
)

שיפור איכות התשובות באופן הדרגתי

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

  1. יוצרים דוגמאות ומעלים אותן למופע של Example Store.

  2. איך לאחזר דוגמאות ולהשתמש בהן בעזרת Gemini

הסרת המשאבים

כדי להסיר את כל המשאבים שבהם השתמשתם בפרויקט, אתם יכולים למחוק את הפרויקט ב- Google Cloud שבו השתמשתם במדריך למתחילים.

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

  1. כדי למחוק את המכונה Example Store, משתמשים בדוגמת הקוד הבאה.

    example_store.delete()
    
  2. מוחקים את כל הקבצים שנוצרו באופן מקומי.

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