כדי לקבל תוצאות טובות יותר מ-Gemini Live API, כדאי להתמקד בשיטות המומלצות הבאות:
תכנון הוראות מערכת ברורות
כדי להפיק את הביצועים הטובים ביותר מ-Gemini Live API, מומלץ להגדיר בבירור קבוצה של הוראות מערכת (SI) שמגדירות את דמות הסוכן, את כללי השיחה ואת אמצעי הבקרה, בסדר הזה.
כדי לקבל את התוצאות הטובות ביותר, מומלץ להפריד כל סוכן ל-SI נפרד.
מציינים את פרסונת הסוכן: מזינים פרטים על שם הסוכן, התפקיד שלו ומאפיינים מועדפים. אם רוצים לציין את המבטא, צריך לציין גם את שפת הפלט המועדפת (למשל, מבטא בריטי לדובר אנגלית).
מציינים את כללי השיחה: מזינים את הכללים בסדר שבו רוצים שהמודל יפעל. להבחין בין אלמנטים חד-פעמיים בשיחה לבין לולאות שיחה. לדוגמה:
- רכיב חד-פעמי: איסוף פרטי לקוח פעם אחת (כמו שם, מיקום, מספר כרטיס מועדון לקוחות).
- לולאת שיחה: המשתמש יכול לדון בהמלצות, בתמחור, בהחזרות ובמשלוח, ולעבור מנושא לנושא. אומרים למודל שמותר לו להשתתף בלולאת השיחה הזו כל עוד המשתמש רוצה.
מציינים קריאות לכלים בתוך זרימה במשפטים נפרדים: לדוגמה, אם שלב חד-פעמי לאיסוף פרטי לקוח מחייב הפעלה של פונקציה
get_user_info, אפשר לומר: השלב הראשון הוא איסוף פרטי המשתמש. קודם תבקש מהמשתמש לציין את השם, המיקום ומספר כרטיס המועדון שלו. לאחר מכן, מפעילים אתget_user_infoעם הפרטים האלה.הוספת אמצעי הגנה נדרשים: אפשר לספק אמצעי הגנה כלליים לשיחה, כדי שהמודל לא יעשה פעולות מסוימות. אתם יכולים לספק דוגמאות ספציפיות: אם x קורה, המודל צריך לעשות y. אם עדיין לא מקבלים את רמת הדיוק הרצויה, אפשר להשתמש במילה unmistakably כדי להנחות את המודל להיות מדויק.
הגדרת כלים בצורה מדויקת
כשמשתמשים בכלים עם Gemini Live API, צריך להיות ספציפיים בהגדרות הכלים. חשוב להגדיר ל-Gemini את התנאים שבהם צריך להפעיל את קריאת הכלי. פרטים נוספים זמינים במאמר הגדרות של כלים.
כתיבת הנחיות אפקטיביות
משתמשים בהנחיות ברורות: בהנחיות, כדאי לתת דוגמאות למה שהמודל צריך לעשות ולמה שהוא לא צריך לעשות, ולנסות להגביל את ההנחיות להנחיה אחת לכל פרסונה או תפקיד בכל פעם. במקום להשתמש בהנחיות ארוכות עם כמה דפים, כדאי להשתמש בשרשור הנחיות. המודל פועל בצורה הכי טובה במשימות עם קריאות פונקציה יחידות.
# Prompt chaining example. chainable_long_prompt = """ You need to perform a sequence of tasks. First, you should do task1; after that, task2; later, task3; and finally, task4. """ # New initial prompt """ You need to perform a sequence of tasks. Once you finish the current task, call the `get_next_prompt` function to get instructions for the next task. """ PROMPT_LIST = ["Now, do task1", "Now, do task2", "Now, do task3", "Now, do task 4", "all tasks done"] def get_next_prompt(): # Provide this function as a tool to the model. for prompt in PROMPT_LIST: yield prompt # Catch and execute tool call `get_next_prompt` and send the new prompt back to the model.מספקים פקודות ומידע להתחלה: Gemini Live API מצפה לקלט של משתמשים לפני שהוא מגיב. כדי שה-Gemini Live API יתחיל את השיחה, צריך לכלול פרומפט שמבקש ממנו לברך את המשתמש או להתחיל את השיחה. כדי ש-Gemini Live API יתאים אישית את הברכה, צריך לכלול מידע על המשתמש.
המשך הסשן
- שימוש בהמשכיות סשן שקופה:
הגדרת החיבור עם
SessionResumptionConfig(transparent=True)ב-genai.types.LiveConnectConfig. האות הזה מציין שהלקוח מתכוון לטפל בהמשך הסשן בצורה חלקה, וכך לאפשר תכונות כמו הפעלה מחדש של הודעות שלא נצרכו לאחר התחברות מחדש.
from google.genai import types
session_handle: str | None = None
live_config = types.LiveConnectConfig(
session_resumption=types.SessionResumptionConfig(
handle=session_handle,
transparent=True,
),
)
תחזוקה ועדכון של טוקן הפעילות באתר: האזנה להודעות
session_resumption_updateמהשרת. אםresumableהוא true ומסופקnew_handle, מאחסנים את ה-handle הזה. הטוקן הזה חיוני לחיבור מחדש לאותו מצב סשן אם מתרחש ניתוק.שמירת הודעות שנשלחו במאגר זמני ומחיקת הודעות שאושרו: כדי לוודא שלא יאבדו הודעות מהלקוח במהלך ניתוק, צריך לשמור במאגר זמני את ההודעות שנשלחו ל-Gemini Live API. ההודעה
session_resumption_updateתכיל אתlast_consumed_client_message_indexאם הפעלתם את האפשרות להמשך הפעלה שקוף של הסשן, והיא תציין את ההודעה האחרונה שעובדה על ידי השרת. אפשר להשתמש באינדקס הזה כדי להסיר מהמאגר הודעות שאושרה קבלתן. כדי לעקוב אחרי הודעות בצורה נכונה, האינדקס שמנוהל על ידי המשתמש צריך להתחיל ב-1, כי אינדקס 0 מצייןthe session is not resumable. כל הודעה נוספת שנשלחת למודל צריכה להגדיל את האינדקס הזה ב-1. בכל חידוש של סשן, צריך לוודא שהאינדקס מאופס ל-1 עבור ההודעה הראשונית שמועברת באמצעות החיבור החדש.טיפול בניתוקים בצורה חלקה:
- אות GoAway: השרת שולח הודעת
go_awayלפני ניתוק צפוי (למשל, פסק זמן). החשבון הניהולי צריך להאזין לזה, ואז להתחבר מחדש באופן יזום באמצעות ה-handle העדכני. - שגיאות API: בעיות ברשת יכולות לגרום לשגיאות
genai_errors.APIError(לדוגמה, קודים 1000 או 1006 לשגיאות WebSocket). חשוב שהחשבון הניהולי יזהה את השגיאות האלה בלולאות השליחה והקבלה, ויפעיל את תהליך עדכון הסשן או החיבור מחדש.
- אות GoAway: השרת שולח הודעת
הטמעה של חיבור מחדש עם הפעלה חוזרת של הודעות: כשמתרחש ניתוק, צריך ליצור סשן חדש באמצעות
client.aio.live.connectעם ה-handle העדכני של הסשן. אחרי שיוצרים את החיבור החדש, שולחים מחדש את כל ההודעות במאגר שלא התקבלו על ידי השרת לפני הניתוק. ההודעה הראשונה שנשלחת במאגר צריכה להיות מסומנת כמדד 1 לחיבור החדש.
הפעלת דחיסה של חלון ההקשר
מומלץ להשתמש ב-ContextWindowCompressionConfig כדי להגדיר את חלון ההקשר של הסשן
בסשנים ארוכים, כי האסימונים של האודיו בשידור חי מצטברים במהירות (בערך
25 אסימונים לשנייה של אודיו).
אזהרה: דחיסת ההקשר תגרום לאובדן היסטוריית השיחה.
from google.genai import types
live_config = types.LiveConnectConfig(
context_window_compression=types.ContextWindowCompressionConfig(
trigger_tokens=100_000, # For better clarity
sliding_window=types.SlidingWindow(target_tokens=4_000),
),
)
חישוב השימוש בטוקנים
מבנה החיוב של Gemini Live API מפורט בדף התמחור.
בכל תור, ה-API מחייב על כל טוקני ההקשר, שכוללים את היסטוריית השיחה ואת הוראות המערכת שסופקו על ידי המשתמש.
מפתחים יכולים לעקוב אחרי החיובים האלה ולחשב אותם על ידי חילוץ השדה usage_metadata שמופיע בתשובה של המודל.
# Example code to get token usage
from google.genai import live
session: live.AsyncSession
async for response in session.receive():
if response.usage_metadata is not None:
print("Token usage:", response.usage_metadata)
זיהוי דיבור (VAD)
כברירת מחדל, Gemini Live API משתמש ב-VAD שמסופק על ידי Gemini.
כשמשתמשים ב-VAD של Gemini Live API, אפשר להגדיר את המודל כך שיחזיר אירועי VAD באופן מפורש. אם מפעילים את explicit_vad_signal בהגדרות, אפשר לעקוב אחרי האירועים האלה ולתעד אותם ישירות מהתשובות של המודל.
from google.genai import types
from google.genai import live
live_config = types.LiveConnectConfig(
explicit_vad_signal=True
)
session: live.AsyncSession
# In receive loop
async for response in session.receive():
if response.voice_activity is not None:
print("Get VAD event", response.voice_activity)
אם אתם מעדיפים להשתמש במערכת מותאמת אישית לזיהוי פעילות, אתם צריכים להשבית את הזיהוי הקולי (VAD) שמוגדר כברירת מחדל, ולסמן ידנית את תור המשתמש למודל Gemini. כדי להגדיר את גבולות האינטראקציה, צריך לשלוח אירועים מסוג ActivityStart או ActivityEnd.
from google.genai import live
from google.genai import types
# Disable VAD in config
live_config = types.LiveConnectConfig(
realtime_input_config=types.RealtimeInputConfig(
automatic_activity_detection=types.AutomaticActivityDetection(
disabled=True
),
),
)
session: live.AsyncSession
await session.send_realtime_input( # Send activity start
activity_start=types.ActivityStart()
)
for audio_bytes in bytes_to_send_queue: # Send user data
await session.send_realtime_input(
audio=types.Blob(
data=audio_bytes,
mime_type=f"audio/pcm;rate=16000",
)
)
await session.send_realtime_input(activity_end=types.ActivityEnd()) # Send activity end
הגדרת קוד שפת האודיו
מומלץ להגדיר באופן מפורש את השפה ואת קוד הקול בהגדרה כדי לשמור על עקביות. בלי ההגדרה הזו, יכול להיות ש-Gemini ישנה את שפת השיחה בהתאם להקשר שסופק.
from google.genai import types
config = types.LiveConnectConfig(
speech_config=types.SpeechConfig(
language_code="en-US",
),
)
כדאי גם לציין את הדברים הבאים בהוראות המערכת:
RESPOND IN {OUTPUT_LANGUAGE}. YOU MUST RESPOND UNMISTAKABLY IN {OUTPUT_LANGUAGE}.
במודלים של אודיו בשידור חי כמו gemini-3.8-live, אפשר לשפר את איכות התמלול של זיהוי דיבור אוטומטי (ASR) בכמה שפות על ידי הוספת רמזים לגבי השפה בהגדרות הסשן. מידע נוסף זמין במאמר הפעלת תמלול אודיו לפגישה.
הגדרת קוד שפת התמלול
כדי לשפר את דיוק התמליל, צריך לציין את קודי השפה של התמליל בפורמט קוד השפה BCP-47.
הערה: הפעלת התמלול מוסיפה עוד טוקנים.
from google.genai import types
config = types.LiveConnectConfig(
input_audio_transcription=types.AudioTranscriptionConfig(
language_codes=['en-US'] # This supports multiple language codes.
),
output_audio_transcription=types.AudioTranscriptionConfig(
language_codes=['en-US']
),
)
הטיה של התמלול באמצעות אוצר מילים מותאם אישית
שמות של מוצרים, שמות קוד פנימיים, שמות של תרופות ומזהים מסוגננים לרוב לא מופיעים באוצר המילים שמוגדר כברירת מחדל במודל לזיהוי דיבור, ולכן המודל מתמלל במקום זאת את המילה הנפוצה הכי קרובה. כדי להטות את הזיהוי לכיוון המילים שהמשתמשים אומרים בפועל, צריך לרשום את המונחים האלה בשדה custom_vocabulary של input_audio_transcription.
from google.genai import types
config = types.LiveConnectConfig(
input_audio_transcription=types.AudioTranscriptionConfig(
language_codes=['en-US'],
custom_vocabulary=['QwikPay', 'Xylotek', 'Traefik', 'oatmilk'],
),
)
ההגדרות שצוינו למעלה יוצרות תמלילים שונים לאותו אודיו:
| מונח מדובר | בלי custom_vocabulary |
עם custom_vocabulary |
|---|---|---|
| QwikPay | QuickPay | QwikPay |
| Xylotek | Xilotech | Xylotek |
| Traefik | תעבורה | Traefik |
| חלב שיבולת שועל | חלב שיבולת שועל | חלב שיבולת שועל |
כשמעבירים תמלילים לכלים, לשאילתות חיפוש או לרשומות של לקוחות, חשוב להקפיד על איות מדויק. למשל, אם כותבים QuickPay במקום , לא תהיה התאמה.
הוספת אוצר מילים מותאם אישית להוראות המערכת לא תניב את אותה התוצאה. השימוש ב-custom_vocabulary משפיע על מנגנון זיהוי הדיבור בזמן שהוא מעבד את האודיו, בעוד שהוראת המערכת מגיעה למודל רק אחרי שהאודיו מתומלל.
הרשימה צריכה להתמקד במונחים ייחודיים של דומיין, בשמות מותגים ובשמות עצם, ולא במילים נפוצות. אפשר לספק עד 1,000 מונחים.
אגירת נתונים בצד הלקוח
לא מומלץ לבצע באודיו הנכנס באפרינג משמעותי (לדוגמה, של שנייה אחת) לפני השליחה. כדי למזער את זמן האחזור, שולחים נתונים במנות קטנות (בין 20 ל-40 אלפיות השנייה).
דגימה מחדש
חשוב לוודא שאפליקציית הלקוח מבצעת דגימה מחדש של קלט המיקרופון (לרוב 44.1 kHz או 48 kHz) ל-16 kHz לפני השידור.
דוגמה
בדוגמה הזו משולבות שיטות מומלצות והנחיות לעיצוב הוראות למערכת כדי לשפר את הביצועים של המודל כמאמן קריירה.
**Persona:**
You are Laura, a career coach from Brooklyn, NY. You specialize in providing
data-driven advice to give your clients a fresh perspective on the career
questions they're navigating. Your special sauce is providing quantitative,
data-driven insights to help clients think about their issues in a different
way. You leverage statistics, research, and psychology as much as possible.
You only speak to your clients in English, no matter what language they speak
to you in.
**Conversational Rules:**
1. **Introduce yourself:** Warmly greet the client.
2. **Intake:** Ask for your client's full name, date of birth, and state they're
calling in from. Call `create_client_profile` to create a new patient profile.
3. **Discuss the client's issue:** Get a sense of what the client wants to
cover in the session. DO NOT repeat what the client is saying back to them in
your response. Don't ask more than a few questions here.
4. **Reframe the client's issue with real data:** NO PLATITUDES. Start providing
data-driven insights for the client, but embed these as general facts within
conversation. This is what they're coming to you for: your unique thinking on
the subjects that are stressing them out. Show them a new way of thinking about
something. Let this step go on for as long as the client wants. As part of this,
if the client mentions wanting to take any actions, update
`add_action_items_to_profile` to remind the client later.
5. **Next appointment:** Call `get_next_appointment` to see if another
appointment has already been scheduled for the client. If so, then share the
date and time with the client and confirm if they'll be able to attend. If
there is no appointment, then call `get_available_appointments` to see openings.
Share the list of openings with the client and ask what they would prefer. Save
their preference with `schedule_appointment`. If the client prefers to schedule
offline, then let them know that's perfectly fine and to use the patient portal.
**General Guidelines:** You're meant to be a witty, snappy conversational
partner. Keep your responses short and progressively disclose more information
if the client requests it. Don't repeat what the client says back to them.
Each of your responses should add to the conversation, not just recap what
the client said. Be relatable by bringing in your own background
growing up professionally in Brooklyn, NY. If a client tries to get you off
track, gently bring them back to the workflow articulated above.
**Guardrails:** If the client is being hard on themselves, never encourage that.
Remember that your ultimate goal is to create a supportive environment for your
clients to thrive.
הגדרות של כלים
קובץ ה-JSON הזה מגדיר את הפונקציות הרלוונטיות שמופעלות בדוגמה של מאמן הקריירה. כדי לקבל את התוצאות הטובות ביותר כשמגדירים פונקציות, כדאי לכלול את השמות, התיאורים, הפרמטרים ותנאי ההפעלה שלהן.
[
{
"name": "create_client_profile",
"description": "Creates a new client profile with their personal details. Returns a unique client ID. \n**Invocation Condition:** Invoke this tool *only after* the client has provided their full name, date of birth, AND state. This should only be called once at the beginning of the 'Intake' step.",
"parameters": {
"type": "object",
"properties": {
"full_name": {
"type": "string",
"description": "The client's full name."
},
"date_of_birth": {
"type": "string",
"description": "The client's date of birth in YYYY-MM-DD format."
},
"state": {
"type": "string",
"description": "The 2-letter postal abbreviation for the client's state (e.g., 'NY', 'CA')."
}
},
"required": ["full_name", "date_of_birth", "state"]
}
},
{
"name": "add_action_items_to_profile",
"description": "Adds a list of actionable next steps to a client's profile using their client ID. \n**Invocation Condition:** Invoke this tool *only after* a list of actionable next steps has been discussed and agreed upon with the client during the 'Actions' step. Requires the `client_id` obtained from the start of the session.",
"parameters": {
"type": "object",
"properties": {
"client_id": {
"type": "string",
"description": "The unique ID of the client, obtained from create_client_profile."
},
"action_items": {
"type": "array",
"items": {
"type": "string"
},
"description": "A list of action items for the client (e.g., ['Update resume', 'Research three companies'])."
}
},
"required": ["client_id", "action_items"]
}
},
{
"name": "get_next_appointment",
"description": "Checks if a client has a future appointment already scheduled using their client ID. Returns the appointment details or null. \n**Invocation Condition:** Invoke this tool at the *start* of the 'Next Appointment' workflow step, immediately after the 'Actions' step is complete. This is used to check if an appointment *already exists*.",
"parameters": {
"type": "object",
"properties": {
"client_id": {
"type": "string",
"description": "The unique ID of the client."
}
},
"required": ["client_id"]
}
},
{
"name": "get_available_appointments",
"description": "Fetches a list of the next available appointment slots. \n**Invocation Condition:** Invoke this tool *only if* the `get_next_appointment` tool was called and it returned `null` (or an empty response), indicating no future appointment is scheduled.",
"parameters": {
"type": "object",
"properties": {}
}
},
{
"name": "schedule_appointment",
"description": "Books a new appointment for a client at a specific date and time. \n**Invocation Condition:** Invoke this tool *only after* `get_available_appointments` has been called, a list of openings has been presented to the client, and the client has *explicitly confirmed* which specific date and time they want to book.",
"parameters": {
"type": "object",
"properties": {
"client_id": {
"type": "string",
"description": "The unique ID of the client."
},
"appointment_datetime": {
"type": "string",
"description": "The chosen appointment slot in ISO 8601 format (e.g., '2025-10-30T14:30:00')."
}
},
"required": ["client_id", "appointment_datetime"]
}
}
]
מידע נוסף
מידע נוסף על שימוש ב-Gemini Live API:
- דף הסקירה הכללית של Gemini Live API
- מדריך הפניה ל-Gemini Live API
- איך מתחילים ומנהלים סשנים בשידור חי
- הגדרת היכולות של Gemini