Live API ช่วยให้คุณโต้ตอบด้วยเสียงและวิดีโอกับ Gemini แบบเรียลไทม์ที่มีเวลาในการตอบสนองต่ำ โดยจะประมวลผลสตรีมเสียง วิดีโอ หรือข้อความอย่างต่อเนื่องเพื่อส่งมอบ คำตอบที่พูดได้ทันทีและเหมือนมนุษย์ ซึ่งจะสร้างประสบการณ์การสนทนาที่เป็นธรรมชาติ สำหรับผู้ใช้
Live API มีชุดฟีเจอร์ที่ครอบคลุม เช่น การตรวจหากิจกรรมเสียง การใช้เครื่องมือและการเรียกฟังก์ชัน การจัดการเซสชัน (สําหรับการจัดการการสนทนาที่ใช้เวลานาน) และโทเค็นชั่วคราว (สําหรับการตรวจสอบสิทธิ์ฝั่งไคลเอ็นต์ที่ปลอดภัย)
หน้านี้จะช่วยให้คุณเริ่มต้นใช้งานได้ด้วยตัวอย่างและตัวอย่างโค้ดพื้นฐาน
ตัวอย่างการใช้งาน
ดูแอปพลิเคชันตัวอย่างต่อไปนี้ซึ่งแสดงวิธีใช้ Live API สำหรับกรณีการใช้งานแบบครบวงจร
- แอปเริ่มต้นสำหรับเสียงสดใน AI Studio โดยใช้ไลบรารี JavaScript เพื่อเชื่อมต่อกับ Live API และสตรีมเสียงแบบสองทิศทาง ผ่านไมโครโฟนและลำโพง
- ตำราอาหาร Python ของ Live API โดยใช้ Pyaudio ที่เชื่อมต่อกับ Live API
การผสานรวมพาร์ทเนอร์
หากต้องการกระบวนการพัฒนาที่ง่ายขึ้น คุณสามารถใช้ Daily, LiveKit หรือ Voximplant ได้ แพลตฟอร์มพาร์ทเนอร์บุคคลที่สามเหล่านี้ได้ผสานรวม Gemini Live API ผ่านโปรโตคอล WebRTC ไว้แล้วเพื่อเพิ่มประสิทธิภาพการพัฒนาแอปพลิเคชันเสียงและวิดีโอแบบเรียลไทม์
ก่อนเริ่มสร้าง
คุณต้องตัดสินใจ 2 เรื่องที่สำคัญก่อนที่จะเริ่มสร้างด้วย Live API ได้แก่ การเลือกโมเดลและการเลือกแนวทางการติดตั้งใช้งาน
เลือกสถาปัตยกรรมการสร้างเสียง
หากคุณกำลังสร้าง Use Case ที่อิงตามเสียง ตัวเลือกโมเดลของคุณจะเป็นตัวกำหนด สถาปัตยกรรมการสร้างเสียงที่ใช้สร้างการตอบกลับด้วยเสียง
- เสียงแบบเนทีฟ:
ตัวเลือกนี้ให้เสียงพูดที่เป็นธรรมชาติและสมจริงที่สุด รวมถึง
ประสิทธิภาพแบบหลายภาษาที่ดีกว่า
นอกจากนี้ยังเปิดใช้ฟีเจอร์ขั้นสูง เช่น การโต้ตอบที่รับรู้ถึงอารมณ์ เสียงเชิงรุก (ที่โมเดลสามารถเลือกที่จะ
ไม่สนใจหรือตอบสนองต่ออินพุตบางอย่าง) และ"การคิด"
โมเดลเสียงเนทีฟต่อไปนี้รองรับเสียงเนทีฟ
gemini-2.5-flash-preview-native-audio-dialog
gemini-2.5-flash-exp-native-audio-thinking-dialog
- เสียงแบบกึ่งแคสเคด:
ตัวเลือกนี้ใช้สถาปัตยกรรมโมเดลแบบแคสเคด (อินพุตเสียงดั้งเดิมและเอาต์พุตการอ่านออกเสียงข้อความ)
โดยจะมอบประสิทธิภาพและความน่าเชื่อถือที่ดีกว่าในสภาพแวดล้อมการผลิต
โดยเฉพาะเมื่อใช้เครื่องมือ รุ่นต่อไปนี้รองรับเสียงแบบกึ่งแคสเคด
gemini-live-2.5-flash-preview
gemini-2.0-flash-live-001
เลือกแนวทางการติดตั้งใช้งาน
เมื่อผสานรวมกับ Live API คุณจะต้องเลือกแนวทางการติดตั้งใช้งานอย่างใดอย่างหนึ่งต่อไปนี้
- เซิร์ฟเวอร์ต่อเซิร์ฟเวอร์: แบ็กเอนด์จะเชื่อมต่อกับ Live API โดยใช้ WebSockets โดยปกติแล้ว ไคลเอ็นต์จะส่งข้อมูลสตรีม (เสียง วิดีโอ ข้อความ) ไปยังเซิร์ฟเวอร์ของคุณ ซึ่งจะส่งต่อข้อมูลไปยัง Live API
- ไคลเอ็นต์ถึงเซิร์ฟเวอร์: โค้ดส่วนหน้าจะเชื่อมต่อกับ Live API โดยตรง โดยใช้ WebSockets เพื่อสตรีมข้อมูลโดยข้ามแบ็กเอนด์
เริ่มต้นใช้งาน
ตัวอย่างนี้อ่านไฟล์ WAV ส่งในรูปแบบที่ถูกต้อง และบันทึก ข้อมูลที่ได้รับเป็นไฟล์ WAV
คุณส่งเสียงได้โดยแปลงเป็นรูปแบบ PCM 16 บิต, 16kHz, โมโน และรับเสียงได้โดยตั้งค่า AUDIO
เป็นรูปแบบการตอบกลับ เอาต์พุตใช้
อัตราการสุ่มตัวอย่าง 24kHz
Python
# 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
import wave
from google import genai
from google.genai import types
import soundfile as sf
import librosa
client = genai.Client()
# Half cascade model:
# model = "gemini-live-2.5-flash-preview"
# Native audio output model:
model = "gemini-2.5-flash-preview-native-audio-dialog"
config = {
"response_modalities": ["AUDIO"],
"system_instruction": "You are a helpful assistant and answer in a friendly tone.",
}
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")
)
wf = wave.open("audio.wav", "wb")
wf.setnchannels(1)
wf.setsampwidth(2)
wf.setframerate(24000) # Output is 24kHz
async for response in 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())
JavaScript
// Test file: https://storage.googleapis.com/generativeai-downloads/data/16000.wav
import { GoogleGenAI, Modality } from '@google/genai';
import * as fs from "node:fs";
import pkg from 'wavefile'; // npm install wavefile
const { WaveFile } = pkg;
const ai = new GoogleGenAI({});
// WARNING: Do not use API keys in client-side (browser based) applications
// Consider using Ephemeral Tokens instead
// More information at: https://ai.google.dev/gemini-api/docs/ephemeral-tokens
// Half cascade model:
// const model = "gemini-live-2.5-flash-preview"
// Native audio output model:
const model = "gemini-2.5-flash-preview-native-audio-dialog"
const config = {
responseModalities: [Modality.AUDIO],
systemInstruction: "You are a helpful assistant and answer in a friendly tone."
};
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();
// 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); // output is 24kHz
fs.writeFileSync('audio.wav', wf.toBuffer());
session.close();
}
async function main() {
await live().catch((e) => console.error('got error', e));
}
main();
ขั้นตอนถัดไป
- อ่านคู่มือความสามารถของ Live API ฉบับเต็มเพื่อดูความสามารถและการกำหนดค่าที่สำคัญ รวมถึงการตรวจหากิจกรรมเสียงและฟีเจอร์เสียงดั้งเดิม
- อ่านคู่มือการใช้เครื่องมือเพื่อดูวิธีผสานรวม Live API กับเครื่องมือและการเรียกใช้ฟังก์ชัน
- อ่านคู่มือการจัดการเซสชันเพื่อจัดการการสนทนาที่ใช้เวลานาน
- อ่านคู่มือโทเค็นชั่วคราวเพื่อดูการตรวจสอบสิทธิ์ที่ปลอดภัยในแอปพลิเคชันไคลเอ็นต์ต่อเซิร์ฟเวอร์
- ดูข้อมูลเพิ่มเติมเกี่ยวกับ WebSockets API พื้นฐานได้ที่ข้อมูลอ้างอิง WebSockets API