השימוש בכלי מאפשר ל-Live API לעשות יותר מסתם שיחה. הוא יכול לבצע פעולות בעולם האמיתי ולשלוף הקשר חיצוני תוך שמירה על חיבור בזמן אמת. אפשר להגדיר כלים כמו בקשות להפעלת פונקציות וחיפוש Google באמצעות Live API.
סקירה כללית של הכלים הנתמכים
הנה סקירה כללית קצרה של הכלים הזמינים למודלים של Live API:
| כלי | Gemini 3.1 Flash Live Preview | גרסת טרום-השקה של Gemini 2.5 Flash Live |
|---|---|---|
| חיפוש | נתמך | נתמך |
| בקשה להפעלת פונקציה | נתמך (סינכרוני בלבד) | נתמך (סינכרוני ואסינכרוני) |
| מפות 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 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