استخدام الأداة مع Live API

تتيح ميزة "استخدام الأدوات" لواجهة Live API تجاوز مجرد المحادثة من خلال تمكينها من تنفيذ إجراءات في العالم الحقيقي واستخلاص السياق الخارجي مع الحفاظ على اتصال في الوقت الفعلي. يمكنك تحديد أدوات، مثل استدعاء الدوال وبحث Google، باستخدام Live API.

نظرة عامة على الأدوات المتوافقة

في ما يلي نظرة عامة موجزة على الأدوات المتاحة لنماذج Live API:

الأداة معاينة Gemini 3.1 Flash Live النسخة الحصرية من Gemini 2.5 Flash
البحث متاح متاح
استدعاء الدوال متاح (متزامن فقط) متوافق (متزامن وغير متزامن)
خرائط 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'