במדריך הזה נסביר איך ליצור דוגמאות של למידה עם מעט דוגמאות באופן איטרטיבי, ולאחזר אותן באופן דינמי ממאגר הדוגמאות כדי לתקן את ההתנהגות של מודל שפה גדול (LLM). במדריך הזה משתמשים במודל gemini-2.0-flash. תבצעו את הפעולות הבאות:
יוצרים מופע של חנות לדוגמה (
ExampleStore).יוצרים דוגמאות על סמך התשובה מ-Gemini ומעלים את הדוגמאות האלה למופע של מאגר הדוגמאות.
אפשר לאחזר באופן דינמי את הדוגמאות מ-Example Store כדי להנחות את ה-LLM להתנהגות הצפויה.
לפנות.
לפני שמתחילים
כדי להשלים את השלבים שמוצגים במדריך הזה, קודם צריך להגדיר את הפרויקט והסביבה.
הגדרת הפרויקט
- נכנסים לחשבון Google Cloud . אם אתם משתמשים חדשים ב- Google Cloud, צרו חשבון כדי שתוכלו להעריך את הביצועים של המוצרים שלנו בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300$ להרצה, לבדיקה ולפריסה של עומסי העבודה.
-
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 theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Gemini Enterprise Agent Platform API.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission. Learn how to grant roles.-
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 theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Gemini Enterprise Agent Platform API.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission. Learn how to grant roles.- אם בחרתם פרויקט, ודאו שיש לכם את תפקיד ה-IAM Agent Platform user (
roles/aiplatform.user) בפרויקט.
אימות ב-Agent Platform
כדי להשתמש בסביבת פיתוח מקומית בדוגמאות של Python שבדף הזה, מתקינים ומפעילים את ה-CLI של gcloud, ואז מגדירים את Application Default Credentials באמצעות פרטי הכניסה של המשתמש.
-
התקינו את ה-CLI של Google Cloud.
-
אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.
-
אם אתם משתמשים במעטפת מקומית, אתם צריכים ליצור פרטי כניסה לאימות מקומי עבור חשבון המשתמש:
gcloud auth application-default login
אם אתם משתמשים ב-Cloud Shell, אין צורך לבצע את הפעולה הזו.
אם מוחזרת שגיאת אימות ואתם משתמשים בספק זהויות חיצוני (IdP), ודאו ש נכנסתם ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.
למידע נוסף, ראו הגדרת ADC לסביבת פיתוח מקומית במאמרי העזרה בנושא אימות Google Cloud .
ייבוא ספריות
מריצים את הפקודה הבאה כדי להתקין את Agent Platform SDK עבור Example Store.
pip install --upgrade google-cloud-aiplatform>=1.87.0בדוגמת הקוד הבאה אפשר לראות איך מייבאים ומפעילים את ה-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 שמשתמש במודל ההטמעה text-embedding-005.
example_store = example_stores.ExampleStore.create(
example_store_config=example_stores.ExampleStoreConfig(
vertex_embedding_model="text-embedding-005"
)
)
שימו לב: יצירת חנות לדוגמה נמשכת כמה דקות.
מידע נוסף על יצירה או שימוש חוזר במופעים של חנות לדוגמה זמין במאמר יצירת מופע של חנות לדוגמה.
העלאת דוגמאות למופע של חנות הדוגמאות
כדי ליצור דוגמאות ולהעלות אותן למופע של מאגר הדוגמאות, מבצעים את השלבים הבאים. אפשר להעלות עד חמש דוגמאות בכל בקשה.
מגדירים את כלי הפונקציה
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." } }, }, )שולחים בקשה ל-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-2.0-flash", user_content, config=genai_types.GenerateContentConfig( tools=[ genai_types.Tool(function_declarations=[get_current_weather_func])] ) )כדי ליצור דוגמה ולהעלות אותה, מבצעים אחת מהפעולות הבאות.
אם התשובה של ה-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])
חוזרים על שלבים 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-2.0-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 באמצעות דוגמאות של למידה עם מעט דוגמאות, חוזרים על השלבים שבקטעים הבאים:
הסרת המשאבים
כדי להסיר את כל המשאבים שבהם השתמשתם בפרויקט הזה, אתם יכולים למחוק את Google Cloud הפרויקט שבו השתמשתם במדריך למתחילים.
אחרת, תוכלו למחוק את המשאבים הספציפיים שיצרתם במדריך הזה, באופן הבא:
כדי למחוק את המופע Example Store, משתמשים בקוד לדוגמה הבא.
example_store.delete()מוחקים את כל הקבצים שנוצרו באופן מקומי.