Ten przewodnik zawiera sprawdzone metody, które pomogą Ci zoptymalizować korzystanie z interfejsu Live API. Na stronie Pierwsze kroki z interfejsem Live API znajdziesz omówienie i przykładowy kod dla typowych przypadków użycia.
Twórz jasne instrukcje systemowe
Aby w pełni wykorzystać możliwości interfejsu Live API, zalecamy zdefiniowanie zestawu instrukcji systemowych (SI), które określają kolejno profil agenta, reguły konwersacji i ograniczenia.
Aby uzyskać najlepsze wyniki, rozdziel każdego agenta na osobne SI.
Określ personę agenta: podaj szczegółowe informacje o imieniu, roli i preferowanych cechach agenta. Jeśli chcesz określić akcent, podaj też preferowany język wyjściowy (np. akcent brytyjski dla osoby mówiącej po angielsku).
Określ reguły konwersacji: umieść te reguły w kolejności, w jakiej model ma ich przestrzegać. Określ elementy jednorazowe rozmowy i pętle konwersacyjne. Na przykład:
- Element jednorazowy: zbieraj dane klienta tylko raz (np. imię i nazwisko, lokalizacja, numer karty lojalnościowej).
- Pętla konwersacyjna: użytkownik może omawiać rekomendacje, ceny, zwroty i dostawę oraz przechodzić od jednego tematu do drugiego. Poinformuj model, że może prowadzić tę rozmowę tak długo, jak zechce użytkownik.
Określ wywołania narzędzi w ramach przepływu w oddzielnych zdaniach: jeśli np. jednorazowy krok polegający na zebraniu szczegółów klienta wymaga wywołania
get_user_infofunkcji, możesz napisać: Pierwszym krokiem jest zebranie informacji o użytkowniku. Najpierw poproś użytkownika o podanie imienia i nazwiska, lokalizacji i numeru karty lojalnościowej. Następnie wywołaj funkcjęget_user_info, podając te szczegóły.Dodaj niezbędne zabezpieczenia: podaj ogólne zabezpieczenia konwersacyjne, których model nie powinien stosować. Możesz podać konkretne przykłady: jeśli x, model ma wykonać y. Jeśli nadal nie uzyskujesz preferowanego poziomu precyzji, użyj słowa nieomylnie, aby nakierować model na precyzyjność.
Precyzyjne określanie narzędzi
Podczas korzystania z narzędzi z interfejsem Live API podawaj w definicjach narzędzi konkretne informacje. Pamiętaj, aby poinformować Gemini, w jakich warunkach należy wywołać wywołanie narzędzia. Więcej informacji znajdziesz w sekcji z przykładami w artykule Definicje narzędzi.
Tworzenie skutecznych promptów
- Używaj jasnych promptów: w promptach podawaj przykłady tego, co modele powinny, a czego nie powinny robić, i staraj się ograniczać prompty do jednego prompta na osobę lub rolę. Zamiast długich promptów wielostronicowych rozważ użycie łańcuchów promptów. Model najlepiej sprawdza się w przypadku zadań z pojedynczymi wywołaniami funkcji.
- Podaj polecenia i informacje początkowe: interfejs Live API oczekuje danych wejściowych od użytkownika, zanim odpowie. Aby interfejs Live API rozpoczął rozmowę, dodaj prompt z prośbą o przywitanie użytkownika lub rozpoczęcie rozmowy. Dołącz informacje o użytkowniku, aby interfejs Live API mógł spersonalizować powitanie.
Określanie języka
Aby uzyskać optymalną skuteczność kaskadowego interfejsu Live API gemini-live-2.5-flash, upewnij się, że language_code interfejsu API jest zgodny z językiem, w którym mówi użytkownik.
Jeśli oczekujesz, że model odpowie w języku innym niż angielski, w instrukcjach systemowych uwzględnij te informacje:
RESPOND IN {OUTPUT_LANGUAGE}. YOU MUST RESPOND UNMISTAKABLY IN {OUTPUT_LANGUAGE}.
Streaming
Podczas wdrażania dźwięku w czasie rzeczywistym stosuj te sprawdzone metody:
- Rozmiar fragmentu i czas oczekiwania: wysyłaj dźwięk w fragmentach o długości od 20 ms do 40 ms.
- Obsługa przerw: gdy użytkownik mówi, gdy model odpowiada, serwer wysyła wiadomość
server_contentz parametrem"interrupted": true. Musisz natychmiast odrzucić bufor audio po stronie klienta, aby zapobiec dalszemu mówieniu agenta przez użytkownika.
Zarządzanie kontekstem
W przypadku długich sesji używaj tagu ContextWindowCompressionConfig, ponieważ tokeny audio natywne gromadzą się szybko (ok. 25 tokenów na sekundę dźwięku).
Buforowanie po stronie klienta
Nie buforuj znacząco (np. przez 1 sekundę) dźwięku wejściowego przed wysłaniem. Wysyłaj małe fragmenty (20–100 ms), aby zminimalizować opóźnienie.
Ponowne próbkowanie
Przed przesłaniem upewnij się, że aplikacja kliencka ponownie próbkuje dane wejściowe z mikrofonu (często 44,1 kHz lub 48 kHz) do 16 kHz.
Zarządzanie sesją
Aby zarządzać cyklem życia sesji i zapewnić użytkownikom niezawodne działanie usługi, postępuj zgodnie z tymi wytycznymi:
- Włącz kompresję okna kontekstu: tokeny audio gromadzą się w tempie około 25 tokenów na sekundę. Bez kompresji sesje tylko audio są ograniczone do 15 minut, a sesje audio-wideo do 2 minut. Włącz kompresję okna kontekstu, aby wydłużyć sesje do nieograniczonego czasu trwania.
- Wdróż wznawianie sesji: serwer może okresowo resetować połączenie WebSocket. Użyj wznawiania sesji, aby bezproblemowo ponownie połączyć się bez utraty kontekstu. Zachowaj najnowszy token wznowienia z
SessionResumptionUpdatewiadomości i przekaż go jako uchwyt podczas ponownego łączenia. Tokeny wznowienia są ważne przez 2 godziny od zakończenia ostatniej sesji. - Obsługa wiadomości GoAway: serwer wysyła wiadomość GoAway przed zakończeniem połączenia. Posłuchaj tego komunikatu i użyj pola
timeLeft, aby zakończyć połączenie lub ponownie się połączyć, zanim zostanie ono zamknięte. - Obsługa sygnałów generationComplete: użyj komunikatu
generationComplete, aby dowiedzieć się, kiedy model zakończył generowanie odpowiedzi. Dzięki temu aplikacja może zaktualizować interfejs lub przejść do następnego działania.
Szczegóły wdrażania znajdziesz w artykule Zarządzanie sesjami.
Przykłady
Ten przykład łączy sprawdzone metody i wskazówki dotyczące projektowania instrukcji systemowych, aby kierować działaniem modelu jako doradcy zawodowego.
**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 back what the client says back to them.
Each response you give should be a net new addition to the conversation, not a
recap of 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.
Definicje narzędzi
Ten kod JSON definiuje odpowiednie funkcje wywoływane w przykładzie dotyczącym doradcy zawodowego. Aby uzyskać najlepsze wyniki podczas definiowania funkcji, podaj ich nazwy, opisy, parametry i warunki wywołania.
[
{
"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"]
}
}
]