Praktik terbaik dengan Gemini Live API

Untuk mendapatkan hasil yang lebih baik dari Gemini Live API, fokuslah pada praktik terbaik berikut:

Mendesain petunjuk sistem yang jelas

Untuk mendapatkan performa terbaik dari Gemini Live API, sebaiknya miliki serangkaian petunjuk sistem (SI) yang jelas dan menentukan persona agen, aturan percakapan, dan batasan, dalam urutan ini.

Untuk hasil terbaik, pisahkan setiap agen ke dalam SI yang berbeda.

  1. Tentukan persona agen: Berikan detail tentang nama, peran, dan karakteristik pilihan agen. Jika Anda ingin menentukan aksen, pastikan untuk juga menentukan bahasa output pilihan (seperti aksen Inggris untuk penutur bahasa Inggris).

  2. Tentukan aturan percakapan: Tempatkan aturan ini dalam urutan yang Anda harapkan untuk diikuti model. Gariskan antara elemen percakapan satu kali dan loop percakapan. Contoh:

    • Elemen satu kali: Kumpulkan detail pelanggan satu kali (seperti nama, lokasi, nomor kartu loyalitas).
    • Loop percakapan: Pengguna dapat membahas rekomendasi, harga, pengembalian, dan pengiriman, serta mungkin ingin beralih dari satu topik ke topik lain. Beri tahu model bahwa tidak masalah untuk terlibat dalam loop percakapan ini selama pengguna menginginkannya.
  3. Tentukan panggilan alat dalam alur dalam kalimat yang berbeda: Misalnya, jika langkah satu kali untuk mengumpulkan detail pelanggan memerlukan pemanggilan fungsi get_user_info, Anda dapat mengatakan: Langkah pertama Anda adalah mengumpulkan informasi pengguna. Pertama, minta pengguna untuk memberikan nama, lokasi, dan nomor kartu loyalitas mereka. Kemudian, panggil get_user_info dengan detail ini.

  4. Tambahkan batasan yang diperlukan: Berikan batasan percakapan umum yang tidak ingin Anda lakukan oleh model. Jangan ragu untuk memberikan contoh spesifik jika x terjadi, Anda ingin model melakukan y. Jika Anda masih belum mendapatkan tingkat presisi yang diinginkan, gunakan kata tidak salah untuk memandu model agar presisi.

Menentukan alat secara akurat

Saat menggunakan alat dengan Gemini Live API, berikan detail dalam definisi alat Anda. Pastikan untuk memberi tahu Gemini dalam kondisi apa panggilan alat harus dipanggil. Untuk mengetahui detail selengkapnya, lihat Definisi alat.

Membuat perintah yang efektif

  • Gunakan perintah yang jelas: Berikan contoh hal yang harus dan tidak boleh dilakukan model dalam perintah, dan coba batasi perintah menjadi satu perintah per persona atau peran dalam satu waktu. Daripada perintah yang panjang dan multi-halaman, sebaiknya gunakan chaining perintah. Model ini berperforma terbaik pada tugas dengan panggilan fungsi tunggal.

    # 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. 
    
  • Berikan perintah dan informasi awal: Gemini Live API mengharapkan input pengguna sebelum merespons. Agar Gemini Live API memulai percakapan, sertakan perintah yang memintanya untuk menyapa pengguna atau memulai percakapan. Sertakan informasi tentang pengguna agar Gemini Live API mempersonalisasi sapaan tersebut.

Melanjutkan sesi

  1. Gunakan kelanjutan sesi yang transparan: Konfigurasi koneksi dengan SessionResumptionConfig(transparent=True) di genai.types.LiveConnectConfig. Hal ini menandakan bahwa klien bermaksud menangani kelanjutan sesi dengan lancar, sehingga memungkinkan fitur seperti memutar ulang pesan yang belum digunakan saat terhubung kembali.
from google.genai import types

session_handle: str | None = None

live_config = types.LiveConnectConfig(
  session_resumption=types.SessionResumptionConfig(
      handle=session_handle,
      transparent=True,
  ),
)
  1. Pertahankan dan perbarui handle sesi: Dengarkan pesan session_resumption_update dari server. Jika resumable benar dan new_handle diberikan, simpan handle ini. Handle ini penting untuk terhubung kembali ke status sesi yang sama jika terjadi pemutusan koneksi.

  2. Buat buffer pesan yang dikirim dan hapus pesan yang diakui: Untuk memastikan tidak ada pesan klien yang hilang selama pemutusan koneksi, pertahankan buffer pesan yang dikirim ke Gemini Live API. Pesan session_resumption_update akan berisi last_consumed_client_message_index saat kelanjutan sesi transparan diaktifkan, yang menunjukkan pesan terakhir yang diproses oleh server. Gunakan indeks ini untuk menghapus pesan yang diakui dari buffer. Untuk melacak pesan dengan benar, indeks yang dikelola pengguna harus dimulai dari 1, karena indeks 0 menunjukkan bahwa the session is not resumable. Setiap pesan berikutnya yang dikirim ke model harus menambah indeks ini sebesar 1. Pada setiap kelanjutan sesi, pastikan indeks direset ke 1 untuk pesan awal yang dikirim menggunakan koneksi baru.

  3. Tangani pemutusan koneksi dengan baik:

    • Sinyal GoAway: Server mengirimkan pesan go_away sebelum pemutusan koneksi yang diharapkan (seperti waktu tunggu). Pengelola harus mendengarkan hal ini, lalu terhubung kembali secara proaktif menggunakan handle terbaru.
    • Error API: Masalah jaringan dapat menyebabkan genai_errors.APIError (misalnya, kode 1000 atau 1006 untuk error WebSocket). Pengelola harus menangkap error ini dalam loop pengiriman dan penerimaan serta memicu proses pembaruan atau koneksi ulang sesi.
  4. Terapkan koneksi ulang dengan pemutaran ulang pesan: Jika terjadi pemutusan koneksi, buat sesi baru menggunakan client.aio.live.connect dengan handle sesi terbaru. Setelah membuat koneksi baru, kirim ulang pesan apa pun dalam buffer yang tidak diakui oleh server sebelum pemutusan koneksi. Pesan pertama yang dikirim dalam buffer harus ditandai sebagai indeks 1 untuk koneksi baru.

Mengaktifkan kompresi jendela konteks

Gunakan ContextWindowCompressionConfig untuk mengonfigurasi jendela konteks sesi untuk sesi panjang, karena token audio native terakumulasi dengan cepat (sekitar 25 token per detik audio).

Peringatan: Kompresi konteks akan menyebabkan histori percakapan hilang.

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),
  ),
)

Penghitungan penggunaan token

Struktur penagihan Gemini Live API dijelaskan di halaman harga. Selama setiap giliran, API akan menagih semua token konteks, yang mencakup histori percakapan dan petunjuk sistem yang diberikan oleh pengguna. Developer dapat memantau dan menghitung biaya ini dengan mengekstrak kolom usage_metadata yang disediakan dalam respons model.

# 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)

Deteksi aktivitas suara (VAD)

Secara default, Gemini Live API menggunakan VAD yang disediakan oleh Gemini.

Saat menggunakan VAD Gemini Live API, Anda dapat mengonfigurasi model untuk menampilkan peristiwa VAD secara eksplisit. Dengan mengaktifkan explicit_vad_signal dalam konfigurasi, Anda dapat memantau dan menangkap peristiwa ini langsung dari respons model.

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)

Jika Anda lebih suka menggunakan sistem deteksi aktivitas kustom, Anda harus menonaktifkan default Deteksi Aktivitas Suara (VAD) dan memberi sinyal giliran pengguna secara manual ke model Gemini. Hal ini dilakukan dengan mengirimkan peristiwa ActivityStart atau ActivityEnd untuk menentukan batas interaksi.

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

Menetapkan kode bahasa audio

Menetapkan kode bahasa dan suara secara eksplisit dalam konfigurasi Anda direkomendasikan untuk menjaga konsistensi; tanpa definisi ini, Gemini dapat mengubah bahasa percakapan bergantung pada konteks yang diberikan.

from google.genai import types

config = types.LiveConnectConfig(
  speech_config=types.SpeechConfig(
    language_code="en-US",
  ),
)

Sebutkan juga hal berikut dalam petunjuk sistem:

RESPOND IN {OUTPUT_LANGUAGE}. YOU MUST RESPOND UNMISTAKABLY IN {OUTPUT_LANGUAGE}.

Untuk model audio native seperti gemini-live-2.5-flash-native-audio, Anda dapat meningkatkan kualitas transkripsi untuk pengenalan ucapan otomatis (ASR) multibahasa dengan memberikan petunjuk bahasa dalam konfigurasi sesi. Untuk mengetahui informasi selengkapnya, lihat Mengaktifkan transkripsi audio untuk sesi.

Menetapkan kode bahasa transkripsi

Tentukan kode bahasa transkripsi untuk meningkatkan akurasi transkripsi menggunakan format kode bahasa BCP-47.

Catatan: Mengaktifkan transkripsi akan menambahkan lebih banyak token.

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']
  ),
)

Buffering klien

Jangan buffer audio input secara signifikan (misalnya, 1 detik) sebelum mengirim. Kirim potongan kecil (antara 20 md dan 40 md) untuk meminimalkan latensi.

Pengambilan ulang sampel

Pastikan aplikasi klien Anda mengambil ulang sampel input mikrofon (sering kali 44,1 kHz atau 48 kHz) ke 16 kHz sebelum transmisi.

Contoh

Contoh ini menggabungkan praktik terbaik dan panduan untuk desain petunjuk sistem guna memandu performa model sebagai pelatih karier.

**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.

Definisi alat

JSON ini menentukan fungsi yang relevan yang dipanggil dalam contoh pelatih karier. Untuk hasil terbaik saat menentukan fungsi, sertakan nama, deskripsi, parameter, dan kondisi pemanggilan.

[
 {
   "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"]
   }
 }
]

Informasi selengkapnya

Untuk mengetahui informasi selengkapnya tentang penggunaan Gemini Live API, lihat: