การใช้เครื่องมือกับ Live API

การใช้เครื่องมือช่วยให้ Live API ทำได้มากกว่าแค่การสนทนา โดยช่วยให้ API ดำเนินการในโลกแห่งความจริงและดึงบริบทภายนอกเข้ามาได้ในขณะที่ยังคง การเชื่อมต่อแบบเรียลไทม์ คุณกำหนดเครื่องมือต่างๆ เช่น การเรียกใช้ฟังก์ชัน และ Google Search ได้ด้วย Live API

ภาพรวมของเครื่องมือที่รองรับ

ต่อไปนี้เป็นภาพรวมโดยย่อของเครื่องมือที่ใช้ได้สำหรับโมเดล Live API

เครื่องมือ เวอร์ชันตัวอย่าง Gemini 3.1 Flash Live เวอร์ชันตัวอย่างของ Gemini 2.5 Flash
ค้นหา สิ่งที่ทำได้ สิ่งที่ทำได้
การเรียกใช้ฟังก์ชัน รองรับ (ซิงโครนัสเท่านั้น) รองรับ (แบบเรียลไทม์และไม่เรียลไทม์)
Google Maps สิ่งที่ทำไม่ได้ สิ่งที่ทำไม่ได้
การรันโค้ด สิ่งที่ทำไม่ได้ สิ่งที่ทำไม่ได้
บริบทของ URL สิ่งที่ทำไม่ได้ สิ่งที่ทำไม่ได้

การเรียกใช้ฟังก์ชัน

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

คุณกําหนดการประกาศฟังก์ชันเป็นส่วนหนึ่งของการกําหนดค่าเซสชันได้ หลังจากได้รับฟังก์ชันคอลแล้ว ไคลเอ็นต์ควรตอบกลับด้วยรายการออบเจ็กต์ FunctionResponseโดยใช้เมธอด session.send_tool_response

ดูข้อมูลเพิ่มเติมได้ที่บทแนะนำการเรียกใช้ฟังก์ชัน

Python

import asyncio
import wave
from google import genai
from google.genai import types

client = genai.Client()

model = "gemini-3.1-flash-live-preview"

# 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": ["AUDIO"], "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}]})

        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)
            elif response.tool_call:
                print("The tool was called")
                function_responses = []
                for fc in response.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)

        wf.close()

if __name__ == "__main__":
    asyncio.run(main())

JavaScript

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({});
const model = 'gemini-3.1-flash-live-preview';

// Simple function definitions
const turn_on_the_lights = { name: "turn_on_the_lights" } // , description: '...', parameters: { ... }
const turn_off_the_lights = { name: "turn_off_the_lights" }

const tools = [{ functionDeclarations: [turn_on_the_lights, turn_off_the_lights] }]

const config = {
  responseModalities: [Modality.AUDIO],
  tools: tools
}

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;
      } else if (message.toolCall) {
        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 inputTurns = 'Turn on the lights please';
  session.sendClientContent({ turns: inputTurns });

  let turns = await handleTurn();

  for (const turn of turns) {
    if (turn.toolCall) {
      console.debug('A tool was called');
      const functionResponses = [];
      for (const fc of turn.toolCall.functionCalls) {
        functionResponses.push({
          id: fc.id,
          name: fc.name,
          response: { result: "ok" } // simple, hard-coded function response
        });
      }

      console.debug('Sending tool response...\n');
      session.sendToolResponse({ functionResponses: functionResponses });
    }
  }

  // Check again for new messages
  turns = await handleTurn();

  // Combine audio data strings and save as wave file
  const combinedAudio = turns.reduce((acc, turn)