Live API ช่วยให้สามารถโต้ตอบด้วยเสียงและวิดีโอแบบ 2 ทิศทางที่มีเวลาในการตอบสนองต่ำกับ Gemini ซึ่งช่วยให้คุณพูดคุยกับ Gemini แบบเรียลไทม์ขณะสตรีมอินพุตวิดีโอหรือแชร์หน้าจอได้ด้วย การใช้ Live API ช่วยให้คุณมอบประสบการณ์การสนทนาด้วยเสียงที่เหมือนมนุษย์และเป็นธรรมชาติให้แก่ผู้ใช้ปลายทางได้
คุณลองใช้ API แบบเรียลไทม์ได้ใน Google AI Studio หากต้องการใช้ Live API ใน Google AI Studio ให้เลือกสตรีม
วิธีการทํางานของ Live API
สตรีมมิง
Live API ใช้รูปแบบสตรีมมิงผ่านการเชื่อมต่อ WebSocket เมื่อคุณโต้ตอบกับ API ระบบจะสร้างการเชื่อมต่อแบบถาวร ระบบจะสตรีมอินพุต (เสียง วิดีโอ หรือข้อความ) ไปยังโมเดลอย่างต่อเนื่อง และระบบจะสตรีมคำตอบของโมเดล (ข้อความหรือเสียง) กลับแบบเรียลไทม์ผ่านการเชื่อมต่อเดียวกัน
สตรีมมิงแบบ 2 ทิศทางนี้ช่วยให้มั่นใจได้ว่าเวลาในการตอบสนองต่ำและรองรับฟีเจอร์ต่างๆ เช่น การตรวจจับกิจกรรมเสียง การใช้เครื่องมือ และการสร้างคำพูด
ดูข้อมูลเพิ่มเติมเกี่ยวกับ WebSockets API พื้นฐานได้ที่ข้อมูลอ้างอิง WebSockets API
การสร้างเอาต์พุต
Live API จะประมวลผลอินพุตหลายรูปแบบ (ข้อความ เสียง วิดีโอ) เพื่อสร้างข้อความหรือเสียงแบบเรียลไทม์ โดยมาพร้อมกับกลไกในการสร้างเสียงในตัว และจะสร้างเสียงด้วยวิธีใดวิธีหนึ่งต่อไปนี้ ทั้งนี้ขึ้นอยู่กับรุ่นที่คุณใช้
- แคสเคดครึ่ง: โมเดลรับอินพุตเสียงแบบเนทีฟ และใช้แคสเคดโมเดลเฉพาะของโมเดลที่แตกต่างกันเพื่อประมวลผลอินพุตและสร้างเอาต์พุตเสียง
- แบบเนทีฟ: Gemini 2.5 เปิดตัวการสร้างเสียงแบบเนทีฟ ซึ่งจะสร้างเอาต์พุตเสียงโดยตรงเพื่อให้เสียงที่ฟังดูเป็นธรรมชาติมากขึ้น น้ำเสียงที่สื่ออารมณ์ได้มากขึ้น รับรู้บริบทเพิ่มเติมได้มากขึ้น เช่น ระดับเสียง และตอบสนองได้เชิงรุกมากขึ้น
การสร้างด้วย Live API
ก่อนเริ่มสร้างด้วย Live API ให้เลือกแนวทางการสร้างเสียงที่เหมาะกับความต้องการของคุณมากที่สุด
การสร้างการเชื่อมต่อ
ตัวอย่างต่อไปนี้แสดงวิธีสร้างการเชื่อมต่อด้วยคีย์ API
import asyncio
from google import genai
client = genai.Client(api_key="GEMINI_API_KEY")
model = "gemini-2.0-flash-live-001"
config = {"response_modalities": ["TEXT"]}
async def main():
async with client.aio.live.connect(model=model, config=config) as session:
print("Session started")
if __name__ == "__main__":
asyncio.run(main())
import { GoogleGenAI } from '@google/genai';
const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
const model = 'gemini-2.0-flash-live-001';
const config = { responseModalities: [Modality.TEXT] };
async function main() {
const session = await ai.live.connect({
model: model,
callbacks: {
onopen: function () {
console.debug('Opened');
},
onmessage: function (message) {
console.debug(message);
},
onerror: function (e) {
console.debug('Error:', e.message);
},
onclose: function (e) {
console.debug('Close:', e.reason);
},
},
config: config,
});
// Send content...
session.close();
}
main();
การส่งและการรับข้อความ
วิธีรับส่งข้อความมีดังนี้
import asyncio
from google import genai
client = genai.Client(api_key="GEMINI_API_KEY")
model = "gemini-2.0-flash-live-001"
config = {"response_modalities": ["TEXT"]}
async def main():
async with client.aio.live.connect(model=model, config=config) as session:
message = "Hello, how are you?"
await session.send_client_content(
turns={"role": "user", "parts": [{"text": message}]}, turn_complete=True
)
async for response in session.receive():
if response.text is not None:
print(response.text, end="")
if __name__ == "__main__":
asyncio.run(main())
import { GoogleGenAI, Modality } from '@google/genai';
const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
const model = 'gemini-2.0-flash-live-001';
const config = { responseModalities: [Modality.TEXT] };
async function live() {
const responseQueue = [];
async function waitMessage() {
let done = false;
let message = undefined;
while (!done) {
message = responseQueue.shift();
if (message) {
done = true;
} else {
await new Promise((resolve) => setTimeout(resolve, 100));
}
}
return message;
}
async function handleTurn() {
const turns = [];
let done = false;
while (!done) {
const message = await waitMessage();
turns.push(message);
if (message.serverContent && message.serverContent.turnComplete) {
done = true;
}
}
return turns;
}
const session = await ai.live.connect({
model: model,
callbacks: {
onopen: function () {
console.debug('Opened');
},
onmessage: function (message) {
responseQueue.push(message);
},
onerror: function (e) {
console.debug('Error:', e.message);
},
onclose: function (e) {
console.debug('Close:', e.reason);
},
},
config: config,
});
const simple = 'Hello how are you?';
session.sendClientContent({ turns: simple });
const turns = await handleTurn();
for (const turn of turns) {
if (turn.text) {
console.debug('Received text: %s\n', turn.text);
}
else if (turn.data) {
console.debug('Received inline data: %s\n', turn.data);
}
}
session.close();
}
async function main() {
await live().catch((e) => console.error('got error', e));
}
main();
การส่งและการรับเสียง
คุณสามารถส่งเสียงได้โดยแปลงเป็นรูปแบบ PCM 16 บิต, 16 kHz, โมโน ตัวอย่างนี้จะอ่านไฟล์ WAV และส่งในรูปแบบที่ถูกต้อง
# Test file: https://storage.googleapis.com/generativeai-downloads/data/16000.wav
# Install helpers for converting files: pip install librosa soundfile
import asyncio
import io
from pathlib import Path
from google import genai
from google.genai import types
import soundfile as sf
import librosa
client = genai.Client(api_key="GEMINI_API_KEY")
model = "gemini-2.0-flash-live-001"
config = {"response_modalities": ["TEXT"]}
async def main():
async with client.aio.live.connect(model=model, config=config) as session:
buffer = io.BytesIO()
y, sr = librosa.load("sample.wav", sr=16000)
sf.write(buffer, y, sr, format='RAW', subtype='PCM_16')
buffer.seek(0)
audio_bytes = buffer.read()
# If already in correct format, you can use this:
# audio_bytes = Path("sample.pcm").read_bytes()
await session.send_realtime_input(
audio=types.Blob(data=audio_bytes, mime_type="audio/pcm;rate=16000")
)
async for response in session.receive():
if response.text is not None:
print(response.text)
if __name__ == "__main__":
asyncio.run(main())
// Test file: https://storage.googleapis.com/generativeai-downloads/data/16000.wav
// Install helpers for converting files: npm install wavefile
import { GoogleGenAI, Modality } from '@google/genai';
import * as fs from "node:fs";
import pkg from 'wavefile';
const { WaveFile } = pkg;
const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
const model = 'gemini-2.0-flash-live-001';
const config = { responseModalities: [Modality.TEXT] };
async function live() {
const responseQueue = [];
async function waitMessage() {
let done = false;
let message = undefined;
while (!done) {
message = responseQueue.shift();
if (message) {
done = true;
} else {
await new Promise((resolve) => setTimeout(resolve, 100));
}
}
return message;
}
async function handleTurn() {
const turns = [];
let done = false;
while (!done) {
const message = await waitMessage();
turns.push(message);
if (message.serverContent && message.serverContent.turnComplete) {
done = true;
}
}
return turns;
}
const session = await ai.live.connect({
model: model,
callbacks: {
onopen: function () {
console.debug('Opened');
},
onmessage: function (message) {
responseQueue.push(message);
},
onerror: function (e) {
console.debug('Error:', e.message);
},
onclose: function (e) {
console.debug('Close:', e.reason);
},
},
config: config,
});
// Send Audio Chunk
const fileBuffer = fs.readFileSync("sample.wav");
// Ensure audio conforms to API requirements (16-bit PCM, 16kHz, mono)
const wav = new WaveFile();
wav.fromBuffer(fileBuffer);
wav.toSampleRate(16000);
wav.toBitDepth("16");
const base64Audio = wav.toBase64();
// If already in correct format, you can use this:
// const fileBuffer = fs.readFileSync("sample.pcm");
// const base64Audio = Buffer.from(fileBuffer).toString('base64');
session.sendRealtimeInput(
{
audio: {
data: base64Audio,
mimeType: "audio/pcm;rate=16000"
}
}
);
const turns = await handleTurn();
for (const turn of turns) {
if (turn.text) {
console.debug('Received text: %s\n', turn.text);
}
else if (turn.data) {
console.debug('Received inline data: %s\n', turn.data);
}
}
session.close();
}
async function main() {
await live().catch((e) => console.error('got error', e));
}
main();
คุณสามารถรับเสียงได้โดยตั้งค่า AUDIO
เป็นรูปแบบการตอบกลับ ตัวอย่างนี้จะบันทึกข้อมูลที่รับเป็นไฟล์ WAV
import asyncio
import wave
from google import genai
client = genai.Client(api_key="GEMINI_API_KEY")
model = "gemini-2.0-flash-live-001"
config = {"response_modalities": ["AUDIO"]}
async def main():
async with client.aio.live.connect(model=model, config=config) as session:
wf = wave.open("audio.wav", "wb")
wf.setnchannels(1)
wf.setsampwidth(2)
wf.setframerate(24000)
message = "Hello how are you?"
await session.send_client_content(
turns={"role": "user", "parts": [{"text": message}]}, turn_complete=True
)
async for idx,response in async_enumerate(session.receive()):
if response.data is not None:
wf.writeframes(response.data)
# Un-comment this code to print audio data info
# if response.server_content.model_turn is not None:
# print(response.server_content.model_turn.parts[0].inline_data.mime_type)
wf.close()
if __name__ == "__main__":
asyncio.run(main())
import { GoogleGenAI, Modality } from '@google/genai';
const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
const model = 'gemini-2.0-flash-live-001';
const config = { responseModalities: [Modality.AUDIO] };
async function live() {
const responseQueue = [];
async function waitMessage() {
let done = false;
let message = undefined;
while (!done) {
message = responseQueue.shift();
if (message) {
done = true;
} else {
await new Promise((resolve) => setTimeout(resolve, 100));
}
}
return message;
}
async function handleTurn() {
const turns = [];
let done = false;
while (!done) {
const message = await waitMessage();
turns.push(message);
if (message.serverContent && message.serverContent.turnComplete) {
done = true;
}
}
return turns;
}
const session = await ai.live.connect({
model: model,
callbacks: {
onopen: function () {
console.debug('Opened');
},
onmessage: function (message) {
responseQueue.push(message);
},
onerror: function (e) {
console.debug('Error:', e.message);
},
onclose: function (e) {
console.debug('Close:', e.reason);
},
},
config: config,
});
const simple = 'Hello how are you?';
session.sendClientContent({ turns: simple });
const turns = await handleTurn();
// Combine audio data strings and save as wave file
const combinedAudio = turns.reduce((acc, turn) => {
if (turn.data) {
const buffer = Buffer.from(turn.data, 'base64');
const intArray = new Int16Array(buffer.buffer, buffer.byteOffset, buffer.byteLength / Int16Array.BYTES_PER_ELEMENT);
return acc.concat(Array.from(intArray));
}
return acc;
}, []);
const audioBuffer = new Int16Array(combinedAudio);
const wf = new WaveFile();
wf.fromScratch(1, 24000, '16', audioBuffer);
fs.writeFileSync('output.wav', wf.toBuffer());
session.close();
}
async function main() {
await live().catch((e) => console.error('got error', e));
}
main();
รูปแบบเสียง
ข้อมูลเสียงใน Live API จะเป็น PCM 16 บิตแบบ Little Endian แบบดิบเสมอ เอาต์พุตเสียงจะใช้อัตราการสุ่มตัวอย่าง 24kHz เสมอ เสียงอินพุตจะอยู่ที่ 16kHz โดยค่าเริ่มต้น แต่ Live API จะสุ่มตัวอย่างใหม่หากจำเป็นเพื่อให้ส่งอัตราตัวอย่างใดก็ได้ หากต้องการระบุอัตราตัวอย่างของเสียงอินพุต ให้ตั้งค่าประเภท MIME ของ Blob ที่มีเสียงแต่ละรายการเป็นค่าอย่างเช่น audio/pcm;rate=16000
การรับการถอดเสียงเป็นคำ
คุณเปิดใช้การถอดเสียงเป็นคำของเอาต์พุตเสียงของโมเดลได้โดยส่ง output_audio_transcription
ในการกำหนดค่าการตั้งค่า ระบบจะอนุมานภาษาในการถอดเสียงจากคำตอบของโมเดล
import asyncio
from google import genai
from google.genai import types
client = genai.Client(api_key="GEMINI_API_KEY")
model = "gemini-2.0-flash-live-001"
config = {"response_modalities": ["AUDIO"],
"output_audio_transcription": {}
}
async def main():
async with client.aio.live.connect(model=model, config=config) as session:
message = "Hello? Gemini are you there?"
await session.send_client_content(
turns={"role": "user", "parts": [{"text": message}]}, turn_complete=True
)
async for response in session.receive():
if response.server_content.model_turn:
print("Model turn:", response.server_content.model_turn)
if response.server_content.output_transcription:
print("Transcript:", response.server_content.output_transcription.text)
if __name__ == "__main__":
asyncio.run(main())
คุณเปิดใช้การถอดเสียงเป็นคำของอินพุตเสียงได้โดยส่ง input_audio_transcription
ในการกำหนดค่าการตั้งค่า
import asyncio
from google import genai
from google.genai import types
client = genai.Client(api_key="GEMINI_API_KEY")
model = "gemini-2.0-flash-live-001"
config = {"response_modalities": ["TEXT"],
"realtime_input_config": {
"automatic_activity_detection": {"disabled": True},
"activity_handling": "NO_INTERRUPTION",
},
"input_audio_transcription": {},
}
async def main():
async with client.aio.live.connect(model=model, config=config) as session:
audio_data = Path("sample.pcm").read_bytes()
await session.send_realtime_input(activity_start=types.ActivityStart())
await session.send_realtime_input(
audio=types.Blob(data=audio_data, mime_type='audio/pcm;rate=16000')
)
await session.send_realtime_input(activity_end=types.ActivityEnd())
async for msg in session.receive():
if msg.server_content.input_transcription:
print('Transcript:', msg.server_content.input_transcription.text)
if __name__ == "__main__":
asyncio.run(main())
การสตรีมเสียงและวิดีโอ
วิธีการของระบบ
คำสั่งของระบบช่วยให้คุณควบคุมลักษณะการทํางานของโมเดลตามความต้องการและกรณีการใช้งานที่เฉพาะเจาะจง คุณสามารถตั้งค่าวิธีการของระบบในการกําหนดค่าการตั้งค่าได้ และจะมีผลตลอดทั้งเซสชัน
from google.genai import types
config = {
"system_instruction": types.Content(
parts=[
types.Part(
text="You are a helpful assistant and answer in a friendly tone."
)
]
),
"response_modalities": ["TEXT"],
}
การอัปเดตเนื้อหาเพิ่มเติม
ใช้การอัปเดตแบบเพิ่มเพื่อส่งอินพุตข้อความ สร้างบริบทของเซสชัน หรือกู้คืนบริบทของเซสชัน สำหรับบริบทสั้นๆ คุณสามารถส่งการโต้ตอบแบบทีละขั้นเพื่อแสดงลำดับเหตุการณ์ที่แน่นอนได้ ดังนี้
turns = [
{"role": "user", "parts": [{"text": "What is the capital of France?"}]},
{"role": "model", "parts": [{"text": "Paris"}]},
]
await session.send_client_content(turns=turns, turn_complete=False)
turns = [{"role": "user", "parts": [{"text": "What is the capital of Germany?"}]}]
await session.send_client_content(turns=turns, turn_complete=True)
{
"clientContent": {
"turns": [
{
"parts":[
{
"text": ""
}
],
"role":"user"
},
{
"parts":[
{
"text": ""
}
],
"role":"model"
}
],
"turnComplete": true
}
}
สำหรับบริบทที่ยาวขึ้น เราขอแนะนำให้ระบุสรุปข้อความเดียวเพื่อเพิ่มพื้นที่ว่างในกรอบเวลาบริบทสำหรับการโต้ตอบครั้งต่อๆ ไป
การเปลี่ยนเสียงและภาษา
Live API รองรับเสียง Puck, Charon, Kore, Fenrir, Aoede, Leda, Orus และ Zephyr
หากต้องการระบุเสียง ให้ตั้งค่าชื่อเสียงภายในออบเจ็กต์ speechConfig
โดยเป็นส่วนหนึ่งของการกำหนดค่าเซสชัน
from google.genai import types
config = types.LiveConnectConfig(
response_modalities=["AUDIO"],
speech_config=types.SpeechConfig(
voice_config=types.VoiceConfig(
prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name="Kore")
)
)
)
{
"voiceConfig": {
"prebuiltVoiceConfig": {
"voiceName": "Kore"
}
}
}
Live API รองรับหลายภาษา
หากต้องการเปลี่ยนภาษา ให้ตั้งค่ารหัสภาษาภายในออบเจ็กต์ speechConfig
เป็นส่วนหนึ่งของการกำหนดค่าเซสชัน ดังนี้
from google.genai import types
config = types.LiveConnectConfig(
response_modalities=["AUDIO"],
speech_config=types.SpeechConfig(
language_code="de-DE",
)
)
เอาต์พุตเสียงแบบดั้งเดิม
นอกจากนี้ คุณยังเข้าถึงโมเดลที่อนุญาตให้ใช้เอาต์พุตเสียงแบบดั้งเดิมได้นอกเหนือจากอินพุตเสียงแบบดั้งเดิมผ่าน Live API วิธีนี้ช่วยให้ได้เสียงที่มีคุณภาพสูงขึ้นด้วยจังหวะที่ดีขึ้น เสียงที่เป็นธรรมชาติ ความยาวของคำพูด และอารมณ์
รูปแบบเสียงแบบเนทีฟต่อไปนี้รองรับเอาต์พุตเสียงแบบเนทีฟ
gemini-2.5-flash-preview-native-audio-dialog
gemini-2.5-flash-exp-native-audio-thinking-dialog
วิธีใช้เอาต์พุตเสียงแบบดั้งเดิม
หากต้องการใช้เอาต์พุตเสียงแบบเนทีฟ ให้กําหนดค่ารูปแบบเสียงแบบเนทีฟรายการใดรายการหนึ่ง และตั้งค่า response_modalities
เป็น AUDIO
model = "gemini-2.5-flash-preview-native-audio-dialog"
config = types.LiveConnectConfig(response_modalities=["AUDIO"])
async with client.aio.live.connect(model=model, config=config) as session:
# Send audio input and receive audio
กล่องโต้ตอบที่แสดงอารมณ์
ฟีเจอร์นี้ช่วยให้ Gemini ปรับสไตล์คำตอบให้เข้ากับรูปแบบและโทนคำสั่ง
หากต้องการใช้กล่องโต้ตอบที่แสดงอารมณ์ ให้ตั้งค่า enable_affective_dialog
เป็น true
ในข้อความการตั้งค่า
config = types.LiveConnectConfig(
response_modalities=["AUDIO"],
enable_affective_dialog=True
)
โปรดทราบว่าปัจจุบันมีเพียงโมเดลเอาต์พุตเสียงแบบเนทีฟเท่านั้นที่รองรับการสนทนาที่แสดงอารมณ์
เสียงแบบเชิงรุก
เมื่อเปิดใช้ฟีเจอร์นี้ Gemini จะตัดสินใจไม่ตอบกลับได้หากเนื้อหาไม่เกี่ยวข้อง
หากต้องการใช้ ให้กําหนดค่าช่อง proactivity
ในข้อความการตั้งค่าและตั้งค่า proactive_audio
เป็น true
config = types.LiveConnectConfig(
response_modalities=["AUDIO"],
proactivity={'proactive_audio': True}
)
โปรดทราบว่าปัจจุบันมีเพียงรูปแบบเอาต์พุตเสียงแบบดั้งเดิมเท่านั้นที่รองรับเสียงเชิงรุก
เอาต์พุตเสียงแบบดั้งเดิมที่มีการคิด
เอาต์พุตเสียงแบบเนทีฟรองรับความสามารถในการคิด ซึ่งพร้อมใช้งานผ่านโมเดล gemini-2.5-flash-exp-native-audio-thinking-dialog
ที่แยกต่างหาก
model = "gemini-2.5-flash-exp-native-audio-thinking-dialog"
config = types.LiveConnectConfig(response_modalities=["AUDIO"])
async with client.aio.live.connect(model=model, config=config) as session:
# Send audio input and receive audio
การใช้เครื่องมือกับ Live API
คุณสามารถกําหนดเครื่องมือต่างๆ เช่น การเรียกฟังก์ชัน การเรียกใช้โค้ด และ Google Search ด้วย Live API
ภาพรวมของเครื่องมือที่รองรับ
ภาพรวมคร่าวๆ ของเครื่องมือที่ใช้ได้สำหรับแต่ละรุ่นมีดังนี้
เครื่องมือ | โมเดลที่ซ้อนกันgemini-2.0-flash-live-001 |
gemini-2.5-flash-preview-native-audio-dialog |
gemini-2.5-flash-exp-native-audio-thinking-dialog |
---|---|---|---|
ค้นหา | ได้ | ได้ | ได้ |
การเรียกใช้ฟังก์ชัน | ได้ | ได้ | ไม่ได้ |
การเรียกใช้โค้ด | ได้ | ไม่ได้ | ไม่ได้ |
บริบท URL | ได้ | ไม่ได้ | ไม่ได้ |
การเรียกใช้ฟังก์ชัน
คุณสามารถกําหนดการประกาศฟังก์ชันเป็นส่วนหนึ่งของการกําหนดค่าเซสชันได้ ดูข้อมูลเพิ่มเติมได้ในบทแนะนำการเรียกใช้ฟังก์ชัน
หลังจากได้รับการเรียกใช้เครื่องมือแล้ว ไคลเอ็นต์ควรตอบกลับด้วยรายการออบเจ็กต์ FunctionResponse
โดยใช้เมธอด session.send_tool_response
import asyncio
from google import genai
from google.genai import types
client = genai.Client(api_key="GEMINI_API_KEY")
model = "gemini-2.0-flash-live-001"
# Simple function definitions
turn_on_the_lights = {"name": "turn_on_the_lights"}
turn_off_the_lights = {"name": "turn_off_the_lights"}
tools = [{"function_declarations": [turn_on_the_lights, turn_off_the_lights]}]
config = {"response_modalities": ["TEXT"], "tools": tools}
async def main():
async with client.aio.live.connect(model=model, config=config) as session:
prompt = "Turn on the lights please"
await session.send_client_content(turns={"parts": [{"text": prompt}]})
async for chunk in session.receive():
if chunk.server_content:
if chunk.text is not None:
print(chunk.text)
elif chunk.tool_call:
function_responses = []
for fc in tool_call.function_calls:
function_response = types.FunctionResponse(
id=fc.id,
name=fc.name,
response={ "result": "ok" } # simple, hard-coded function response
)
function_responses.append(function_response)
await session.send_tool_response(function_responses=function_responses)
if __name__ == "__main__":
asyncio.run(main())
จากพรอมต์เดียว โมเดลสามารถสร้างการเรียกฟังก์ชันหลายรายการและโค้ดที่จําเป็นต่อเชื่อมเอาต์พุต โค้ดนี้จะทํางานในสภาพแวดล้อมแซนด์บ็อกซ์ ซึ่งจะสร้างข้อความ BidiGenerateContentToolCall ตามมา
การเรียกใช้ฟังก์ชันแบบอะซิงโครนัส
โดยค่าเริ่มต้น การดำเนินการจะหยุดชั่วคราวจนกว่าผลลัพธ์ของการเรียกใช้ฟังก์ชันแต่ละรายการจะพร้อมใช้งาน ซึ่งช่วยให้การประมวลผลเป็นไปตามลำดับ ซึ่งหมายความว่าคุณจะโต้ตอบกับโมเดลต่อไปไม่ได้ขณะที่ฟังก์ชันกำลังทำงาน
หากไม่ต้องการบล็อกการสนทนา คุณสามารถบอกให้โมเดลเรียกใช้ฟังก์ชันแบบไม่พร้อมกันได้
โดยก่อนอื่นคุณต้องเพิ่ม behavior
ลงในคําจํากัดความของฟังก์ชัน ดังนี้
# Non-blocking function definitions
turn_on_the_lights = {"name": "turn_on_the_lights", "behavior": "NON_BLOCKING"} # turn_on_the_lights will run asynchronously
turn_off_the_lights = {"name": "turn_off_the_lights"} # turn_off_the_lights will still pause all interactions with the model
NON-BLOCKING
จะช่วยให้มั่นใจว่าฟังก์ชันจะทํางานแบบไม่พร้อมกันขณะที่คุณโต้ตอบกับโมเดลต่อไปได้
จากนั้นคุณต้องบอกให้โมเดลทราบว่าจะทําอย่างไรเมื่อได้รับ FunctionResponse
โดยใช้พารามิเตอร์ scheduling
ซึ่งอาจเป็นอย่างใดอย่างหนึ่งต่อไปนี้
- ขัดจังหวะสิ่งที่กำลังทำอยู่และบอกคุณเกี่ยวกับคำตอบที่ได้รับทันที
(
scheduling="INTERRUPT"
), - โปรดรอจนกว่าระบบจะดำเนินการเสร็จสิ้น
(
scheduling="WHEN_IDLE"
) - หรือจะไม่ต้องดำเนินการใดๆ และใช้ความรู้นั้นในภายหลังในการสนทนาก็ได้
(
scheduling="SILENT"
)
# Non-blocking function definitions
function_response = types.FunctionResponse(
id=fc.id,
name=fc.name,
response={
"result": "ok",
"scheduling": "INTERRUPT" # Can also be WHEN_IDLE or SILENT
}
)
การดำเนินการกับโค้ด
คุณสามารถกําหนดการเรียกใช้โค้ดเป็นส่วนหนึ่งของการกําหนดค่าเซสชันได้ ดูข้อมูลเพิ่มเติมได้ในบทแนะนําการเรียกใช้โค้ด
import asyncio
from google import genai
from google.genai import types
client = genai.Client(api_key="GEMINI_API_KEY")
model = "gemini-2.0-flash-live-001"
tools = [{'code_execution': {}}]
config = {"response_modalities": ["TEXT"], "tools": tools}
async def main():
async with client.aio.live.connect(model=model, config=config) as session:
prompt = "Compute the largest prime palindrome under 100000."
await session.send_client_content(turns={"parts": [{"text": prompt}]})
async for chunk in session.receive():
if chunk.server_content:
if chunk.text is not None:
print(chunk.text)
model_turn = chunk.server_content.model_turn
if model_turn:
for part in model_turn.parts:
if part.executable_code is not None:
print(part.executable_code.code)
if part.code_execution_result is not None:
print(part.code_execution_result.output)
if __name__ == "__main__":
asyncio.run(main())
การยึดเหนี่ยวกับ Google Search
คุณสามารถเปิดใช้การกําหนดค่าพื้นฐานด้วย Google Search เป็นส่วนหนึ่งของการกำหนดค่าเซสชันได้ ดูข้อมูลเพิ่มเติมได้ในบทแนะนำการต่อกราวด์
import asyncio
from google import genai
from google.genai import types
client = genai.Client(api_key="GEMINI_API_KEY")
model = "gemini-2.0-flash-live-001"
tools = [{'google_search': {}}]
config = {"response_modalities": ["TEXT"], "tools": tools}
async def main():
async with client.aio.live.connect(model=model, config=config) as session:
prompt = "When did the last Brazil vs. Argentina soccer match happen?"
await session.send_client_content(turns={"parts": [{"text": prompt}]})
async for chunk in session.receive():
if chunk.server_content:
if chunk.text is not None:
print(chunk.text)
# The model might generate and execute Python code to use Search
model_turn = chunk.server_content.model_turn
if model_turn:
for part in model_turn.parts:
if part.executable_code is not None:
print(part.executable_code.code)
if part.code_execution_result is not None:
print(part.code_execution_result.output)
if __name__ == "__main__":
asyncio.run(main())
การรวมเครื่องมือหลายอย่างเข้าด้วยกัน
คุณรวมเครื่องมือหลายอย่างภายใน Live API ได้ดังนี้
prompt = """
Hey, I need you to do three things for me.
1. Compute the largest prime palindrome under 100000.
2. Then use Google Search to look up information about the largest earthquake in California the week of Dec 5 2024?
3. Turn on the lights
Thanks!
"""
tools = [
{"google_search": {}},
{"code_execution": {}},
{"function_declarations": [turn_on_the_lights, turn_off_the_lights]},
]
config = {"response_modalities": ["TEXT"], "tools": tools}
การจัดการกับการหยุดชะงัก
ผู้ใช้สามารถขัดจังหวะเอาต์พุตของโมเดลได้ทุกเมื่อ เมื่อการตรวจจับกิจกรรมเสียงพูด (VAD) ตรวจพบการหยุดชะงัก ระบบจะยกเลิกและทิ้งการสร้างที่กำลังดำเนินอยู่ เฉพาะข้อมูลที่ส่งไปยังไคลเอ็นต์แล้วเท่านั้นที่จะยังคงอยู่ในประวัติเซสชัน จากนั้นเซิร์ฟเวอร์จะส่งข้อความ BidiGenerateContentServerContent เพื่อรายงานการหยุดชะงัก
นอกจากนี้ เซิร์ฟเวอร์ Gemini จะทิ้งการเรียกฟังก์ชันที่รอดำเนินการและส่งข้อความ BidiGenerateContentServerContent
พร้อมรหัสของการเรียกที่ถูกยกเลิก
async for response in session.receive():
if response.server_content.interrupted is True:
# The generation was interrupted
การตรวจจับกิจกรรมเสียงพูด (VAD)
คุณสามารถกำหนดค่าหรือปิดใช้การตรวจจับกิจกรรมเสียง (VAD) ได้
การใช้ VAD อัตโนมัติ
โดยค่าเริ่มต้น โมเดลจะดำเนินการ VAD กับสตรีมอินพุตเสียงแบบต่อเนื่องโดยอัตโนมัติ คุณสามารถกําหนดค่า VAD ได้ด้วยช่อง realtimeInputConfig.automaticActivityDetection
ของการกําหนดค่าการตั้งค่า
เมื่อสตรีมเสียงหยุดชั่วคราวนานกว่า 1 วินาที (เช่น เนื่องจากผู้ใช้ปิดไมโครโฟน) คุณควรส่งเหตุการณ์ audioStreamEnd
เพื่อล้างเสียงที่แคชไว้ โดยลูกค้าสามารถส่งข้อมูลเสียงต่อได้ทุกเมื่อ
# example audio file to try:
# URL = "https://storage.googleapis.com/generativeai-downloads/data/hello_are_you_there.pcm"
# !wget -q $URL -O sample.pcm
import asyncio
from pathlib import Path
from google import genai
from google.genai import types
client = genai.Client(api_key="GEMINI_API_KEY")
model = "gemini-2.0-flash-live-001"
config = {"response_modalities": ["TEXT"]}
async def main():
async with client.aio.live.connect(model=model, config=config) as session:
audio_bytes = Path("sample.pcm").read_bytes()
await session.send_realtime_input(
audio=types.Blob(data=audio_bytes, mime_type="audio/pcm;rate=16000")
)
# if stream gets paused, send:
# await session.send_realtime_input(audio_stream_end=True)
async for response in session.receive():
if response.text is not None:
print(response.text)
if __name__ == "__main__":
asyncio.run(main())
เมื่อใช้ send_realtime_input
ทาง API จะตอบสนองต่อเสียงโดยอัตโนมัติตาม VAD ขณะที่ send_client_content
จะเพิ่มข้อความลงในบริบทของโมเดลตามลําดับ แต่ send_realtime_input
จะเพิ่มประสิทธิภาพเพื่อตอบสนองโดยเสียค่าใช้จ่ายในการเรียงลําดับแบบกำหนด
การกำหนดค่า VAD อัตโนมัติ
หากต้องการควบคุมกิจกรรม VAD ได้มากขึ้น คุณสามารถกําหนดค่าพารามิเตอร์ต่อไปนี้ ดูข้อมูลเพิ่มเติมได้ที่ข้อมูลอ้างอิง API
from google.genai import types
config = {
"response_modalities": ["TEXT"],
"realtime_input_config": {
"automatic_activity_detection": {
"disabled": False, # default
"start_of_speech_sensitivity": types.StartSensitivity.START_SENSITIVITY_LOW,
"end_of_speech_sensitivity": types.EndSensitivity.END_SENSITIVITY_LOW,
"prefix_padding_ms": 20,
"silence_duration_ms": 100,
}
}
}
การปิดใช้ VAD อัตโนมัติ
หรือจะปิดใช้ VAD อัตโนมัติโดยการตั้งค่า realtimeInputConfig.automaticActivityDetection.disabled
เป็น true
ในข้อความการตั้งค่าก็ได้ ในการกำหนดค่านี้ ไคลเอ็นต์มีหน้าที่รับผิดชอบในการตรวจจับเสียงพูดของผู้ใช้และส่งข้อความ activityStart
และ activityEnd
ในเวลาที่เหมาะสม ระบบจะไม่ส่ง audioStreamEnd
ในการกำหนดค่านี้ แต่ระบบจะแสดงข้อความ activityEnd
แทนเพื่อระบุว่าสตรีมหยุดชะงัก
config = {
"response_modalities": ["TEXT"],
"realtime_input_config": {"automatic_activity_detection": {"disabled": True}},
}
async with client.aio.live.connect(model=model, config=config) as session:
# ...
await session.send_realtime_input(activity_start=types.ActivityStart())
await session.send_realtime_input(
audio=types.Blob(data=audio_bytes, mime_type="audio/pcm;rate=16000")
)
await session.send_realtime_input(activity_end=types.ActivityEnd())
# ...
จํานวนโทเค็น
คุณดูจํานวนโทเค็นทั้งหมดที่ใช้ได้ในช่อง usageMetadata ของข้อความเซิร์ฟเวอร์ที่แสดงผล
async for message in session.receive():
# The server will periodically send messages that include UsageMetadata.
if message.usage_metadata:
usage = message.usage_metadata
print(
f"Used {usage.total_token_count} tokens in total. Response token breakdown:"
)
for detail in usage.response_tokens_details:
match detail:
case types.ModalityTokenCount(modality=modality, token_count=count):
print(f"{modality}: {count}")
การขยายระยะเวลาเซสชัน
ระยะเวลาเซสชันสูงสุดสามารถขยายได้ไม่จำกัดด้วยกลไก 2 อย่างดังนี้
นอกจากนี้ คุณจะได้รับข้อความ GoAway ก่อนเซสชันสิ้นสุดลง ซึ่งจะช่วยให้คุณดำเนินการต่อได้
การบีบอัดกรอบเวลาบริบท
หากต้องการให้เซสชันทำงานได้นานขึ้นและหลีกเลี่ยงการสิ้นสุดการเชื่อมต่ออย่างกะทันหัน คุณสามารถเปิดใช้การบีบอัดกรอบบริบทได้โดยตั้งค่าช่อง contextWindowCompression เป็นส่วนหนึ่งของการกำหนดค่าเซสชัน
ใน ContextWindowCompressionConfig คุณสามารถกําหนดค่ากลไกกรอบเวลาแบบเลื่อนและจํานวนโทเค็นที่จะทริกเกอร์การบีบอัด
from google.genai import types
config = types.LiveConnectConfig(
response_modalities=["AUDIO"],
context_window_compression=(
# Configures compression with default parameters.
types.ContextWindowCompressionConfig(
sliding_window=types.SlidingWindow(),
)
),
)
การกลับมาดำเนินเซสชันต่อ
หากต้องการป้องกันไม่ให้เซสชันสิ้นสุดลงเมื่อเซิร์ฟเวอร์รีเซ็ตการเชื่อมต่อ WebSocket เป็นระยะ ให้กําหนดค่าช่อง sessionResumption ภายในการกําหนดค่าการตั้งค่า
การส่งการกำหนดค่านี้จะทำให้เซิร์ฟเวอร์ส่งข้อความ SessionResumptionUpdate ซึ่งสามารถใช้เพื่อกลับมาดำเนินการในเซสชันต่อได้โดยส่งโทเค็นการกลับมาทำงานอีกครั้งล่าสุดเป็น SessionResumptionConfig.handle
ของการเชื่อมต่อครั้งถัดไป
import asyncio
from google import genai
from google.genai import types
client = genai.Client(api_key="GEMINI_API_KEY")
model = "gemini-2.0-flash-live-001"
async def main():
print(f"Connecting to the service with handle {previous_session_handle}...")
async with client.aio.live.connect(
model=model,
config=types.LiveConnectConfig(
response_modalities=["AUDIO"],
session_resumption=types.SessionResumptionConfig(
# The handle of the session to resume is passed here,
# or else None to start a new session.
handle=previous_session_handle
),
),
) as session:
while True:
await session.send_client_content(
turns=types.Content(
role="user", parts=[types.Part(text="Hello world!")]
)
)
async for message in session.receive():
# Periodically, the server will send update messages that may
# contain a handle for the current state of the session.
if message.session_resumption_update:
update = message.session_resumption_update
if update.resumable and update.new_handle:
# The handle should be retained and linked to the session.
return update.new_handle
# For the purposes of this example, placeholder input is continually fed
# to the model. In non-sample code, the model inputs would come from
# the user.
if message.server_content and message.server_content.turn_complete:
break
if __name__ == "__main__":
asyncio.run(main())
การรับข้อความก่อนที่เซสชันจะตัดการเชื่อมต่อ
เซิร์ฟเวอร์ส่งข้อความ GoAway ซึ่งบ่งบอกว่าการเชื่อมต่อปัจจุบันจะสิ้นสุดลงในไม่ช้า ข้อความนี้มี timeLeft ซึ่งแสดงเวลาที่เหลืออยู่และให้คุณดำเนินการเพิ่มเติมได้ก่อนที่การเชื่อมต่อจะสิ้นสุดลงโดยระบุว่า "ยกเลิก"
async for response in session.receive():
if response.go_away is not None:
# The connection will soon be terminated
print(response.go_away.time_left)
การรับข้อความเมื่อการสร้างเสร็จสมบูรณ์
เซิร์ฟเวอร์จะส่งข้อความ generationComplete ที่บ่งบอกว่าโมเดลสร้างคำตอบเสร็จแล้ว
async for response in session.receive():
if response.server_content.generation_complete is True:
# The generation is complete
ความละเอียดของสื่อ
คุณสามารถระบุความละเอียดของสื่อสำหรับสื่ออินพุตได้โดยตั้งค่าช่อง mediaResolution
เป็นส่วนหนึ่งของการกำหนดค่าเซสชัน ดังนี้
from google.genai import types
config = types.LiveConnectConfig(
response_modalities=["AUDIO"],
media_resolution=types.MediaResolution.MEDIA_RESOLUTION_LOW,
)
ข้อจำกัด
โปรดคำนึงถึงข้อจำกัดต่อไปนี้ของ Live API เมื่อวางแผนโปรเจ็กต์
รูปแบบการตอบกลับ
คุณตั้งค่ารูปแบบคำตอบได้เพียงรูปแบบเดียว (TEXT
หรือ AUDIO
) ต่อเซสชันในการกําหนดค่าเซสชัน การตั้งค่าทั้ง 2 รายการจะส่งผลให้เกิดข้อความแสดงข้อผิดพลาดในการกําหนดค่า ซึ่งหมายความว่าคุณสามารถกําหนดค่าโมเดลให้ตอบกลับด้วยข้อความหรือเสียงได้ แต่จะตอบกลับทั้ง 2 อย่างในเซสชันเดียวกันไม่ได้
การตรวจสอบสิทธิ์ไคลเอ็นต์
Live API มีการตรวจสอบสิทธิ์แบบเซิร์ฟเวอร์ต่อเซิร์ฟเวอร์เท่านั้น และเราไม่แนะนำให้ใช้กับไคลเอ็นต์โดยตรง อินพุตของไคลเอ็นต์ควรกำหนดเส้นทางผ่านเซิร์ฟเวอร์แอปพลิเคชันระดับกลางเพื่อการตรวจสอบสิทธิ์ที่ปลอดภัยกับ Live API
ระยะเวลาเซสชัน
คุณสามารถขยายระยะเวลาเซสชันได้ไม่จํากัดโดยเปิดใช้การบีบอัดเซสชัน หากไม่มีการบีบอัด เซสชันที่มีเฉพาะเสียงจะจำกัดไว้ที่ 15 นาที และเซสชันที่มีทั้งเสียงและวิดีโอจะจำกัดไว้ที่ 2 นาที การเกินขีดจำกัดเหล่านี้โดยไม่ใช้การบีบอัดจะสิ้นสุดการเชื่อมต่อ
นอกจากนี้ คุณยังกําหนดค่าการกลับมาทํางานต่อของเซสชันเพื่ออนุญาตให้ไคลเอ็นต์กลับมาทํางานต่อในเซสชันที่สิ้นสุดไปแล้วได้
หน้าต่างบริบท
เซสชันมีขีดจํากัดของกรอบเวลาบริบทดังนี้
- โทเค็น 128,000 รายการสำหรับโมเดลเอาต์พุตเสียงแบบดั้งเดิม
- โทเค็น 32,000 รายการสำหรับ Live API รุ่นอื่นๆ
ภาษาที่รองรับ
Live API รองรับภาษาต่อไปนี้
ภาษา | รหัส BCP-47 |
---|---|
เยอรมัน (เยอรมนี) | de-DE |
อังกฤษ (ออสเตรเลีย) | en-AU |
อังกฤษ (สหราชอาณาจักร) | en-GB |
อังกฤษ (อินเดีย) | en-IN |
อังกฤษ (อเมริกัน) | en-US |
สเปน (สหรัฐอเมริกา) | es-US |
ฝรั่งเศส (ฝรั่งเศส) | fr-FR |
ฮินดู (อินเดีย) | hi-IN |
โปรตุเกส (บราซิล) | pt-BR |
อาหรับ (ทั่วไป) | ar-XA |
สเปน (สเปน) | es-ES |
ฝรั่งเศส (แคนาดา) | fr-CA |
อินโดนีเซีย (อินโดนีเซีย) | id-ID |
อิตาลี (อิตาลี) | it-IT |
ญี่ปุ่น (ญี่ปุ่น) | ja-JP |
ตุรกี (ตุรกี) | tr-TR |
เวียดนาม (เวียดนาม) | vi-VN |
เบงกาลี (อินเดีย) | bn-IN |
คุชราต (อินเดีย) | gu-IN |
กันนาดา (อินเดีย) | kn-IN |
มลยาฬัม (อินเดีย) | ml-IN |
มราฐี (อินเดีย) | mr-IN |
ทมิฬ (อินเดีย) | ta-IN |
เตลูกู (อินเดีย) | te-IN |
ดัตช์ (เนเธอร์แลนด์) | nl-NL |
เกาหลี (เกาหลีใต้) | ko-KR |
จีนกลาง (จีน) | cmn-CN |
โปแลนด์ (โปแลนด์) | pl-PL |
รัสเซีย (รัสเซีย) | ru-RU |
ไทย (ประเทศไทย) | th-TH |
การผสานรวมกับบุคคลที่สาม
สําหรับการติดตั้งใช้งานเว็บและแอปบนอุปกรณ์เคลื่อนที่ คุณสามารถดูตัวเลือกต่อไปนี้
ขั้นตอนถัดไป
- ใช้ไคลเอ็นต์ต่อเซิร์ฟเวอร์ด้วยโทเค็นชั่วคราว
- ลองใช้ Live API ใน Google AI Studio
- ดูข้อมูลเพิ่มเติมเกี่ยวกับ Gemini 2.0 Flash Live ได้ที่หน้าโมเดล
- ลองดูตัวอย่างเพิ่มเติมในตำรา Live API, ตำราเครื่องมือ Live API และสคริปต์เริ่มต้นใช้งาน Live API