Использование инструмента с Live API

Использование инструментов позволяет Live API выходить за рамки простого общения, давая возможность выполнять действия в реальном мире и получать внешний контекст, поддерживая при этом связь в реальном времени. С помощью Live API можно определять такие инструменты, как вызов функций и поиск Google .

Обзор поддерживаемых инструментов

Вот краткий обзор доступных инструментов для моделей Live API:

Инструмент Gemini 3.1 Flash Live Preview Gemini 2.5 Flash Live Preview
Поиск Поддерживается Поддерживается
Вызов функции Поддерживается (только в синхронном режиме) Поддерживаются (синхронные и асинхронные )
Google Карты Не поддерживается Не поддерживается
Выполнение кода Не поддерживается Не поддерживается
контекст 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