Get started with Live API

Live API ช่วยให้สามารถโต้ตอบด้วยเสียงและวิดีโอแบบเรียลไทม์ที่มีเวลาในการตอบสนองต่ำกับ Gemini โดยระบบจะประมวลผลสตรีมเสียง วิดีโอ หรือข้อความอย่างต่อเนื่องเพื่อแสดงคำตอบที่เป็นเสียงพูดที่เหมือนมนุษย์ในทันที ซึ่งจะสร้างประสบการณ์การสนทนาที่เป็นธรรมชาติให้แก่ผู้ใช้

ภาพรวมของ Live API

Live API มีชุดฟีเจอร์ที่ครอบคลุม เช่น การตรวจจับกิจกรรมเสียง การใช้เครื่องมือและการเรียกใช้ฟังก์ชัน การจัดการเซสชัน (สำหรับจัดการการสนทนาที่ดำเนินอยู่นาน) และโทเค็นชั่วคราว (สำหรับการตรวจสอบสิทธิ์ฝั่งไคลเอ็นต์ที่ปลอดภัย)

หน้านี้จะช่วยให้คุณเริ่มต้นใช้งานด้วยตัวอย่างและโค้ดพื้นฐาน

ตัวอย่างแอปพลิเคชัน

ดูตัวอย่างแอปพลิเคชันต่อไปนี้ซึ่งแสดงวิธีใช้ Live API สำหรับกรณีการใช้งานตั้งแต่ต้นจนจบ

การผสานรวมพาร์ทเนอร์

หากต้องการใช้กระบวนการพัฒนาที่ง่ายขึ้น คุณสามารถใช้ Daily หรือ LiveKit แพลตฟอร์มเหล่านี้เป็นแพลตฟอร์มของพาร์ทเนอร์บุคคลที่สามที่ผสานรวม Gemini Live API ผ่านโปรโตคอล WebRTC แล้วเพื่อปรับปรุงการพัฒนาแอปพลิเคชันเสียงและวิดีโอแบบเรียลไทม์

ก่อนเริ่มสร้าง

คุณต้องตัดสินใจ 2 อย่างสําคัญก่อนเริ่มสร้างด้วย Live API ได้แก่ การเลือกรูปแบบและเลือกแนวทางการใช้งาน

เลือกรุ่น

หากคุณกำลังสร้าง Use Case ที่อิงตามเสียง การเลือกโมเดลจะเป็นตัวกำหนดสถาปัตยกรรมการสร้างเสียงที่ใช้ในการสร้างคำตอบที่เป็นเสียง

  • เสียงแบบดั้งเดิมด้วย Gemini 2.5 Flash: ตัวเลือกนี้จะให้เสียงพูดที่ฟังเป็นธรรมชาติและสมจริงที่สุด รวมถึงมีประสิทธิภาพมากขึ้นในหลายภาษา นอกจากนี้ ยังเปิดใช้ฟีเจอร์ขั้นสูง เช่น บทสนทนาที่แสดงอารมณ์ (รับรู้อารมณ์), เสียงแบบเชิงรุก (ซึ่งโมเดลจะตัดสินใจได้ว่าจะเพิกเฉยหรือตอบสนองต่ออินพุตบางอย่าง) และการ"คิด" รูปแบบเสียงแบบเนทีฟต่อไปนี้รองรับเสียงแบบเนทีฟ
    • gemini-2.5-flash-preview-native-audio-dialog
    • gemini-2.5-flash-exp-native-audio-thinking-dialog
  • เสียงแบบแคสเคดครึ่งหนึ่งด้วย Gemini 2.0 Flash:ตัวเลือกนี้พร้อมใช้งานในโมเดล 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(api_key="GEMINI_API_KEY")

# Half cascade model:
# model = "gemini-2.0-flash-live-001"

# 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({ apiKey: "GEMINI_API_KEY" });
// 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-2.0-flash-live-001"

// 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();

ขั้นตอนถัดไป