Përdorimi i veglave lejon Live API të shkojë përtej vetëm bisedës duke i mundësuar të kryejë veprime në botën reale dhe të tërheqë në kontekstin e jashtëm duke ruajtur një lidhje në kohë reale. Mund të përcaktoni mjete të tilla si Thirrja e funksionit , ekzekutimi i kodit dhe Kërkimi në Google me API-në e drejtpërdrejtë.
Pasqyrë e mjeteve të mbështetura
Këtu është një përmbledhje e shkurtër e mjeteve të disponueshme për secilin model:
Mjet | Modele me kaskadëgemini-live-2.5-flash-preview gemini-2.0-flash-live-001 | gemini-2.5-flash-preview-native-audio-dialog | gemini-2.5-flash-exp-native-audio-thinking-dialog |
---|---|---|---|
Kërko | po | po | po |
Thirrja e funksionit | po | po | Nr |
Ekzekutimi i kodit | po | Nr | Nr |
Konteksti i URL-së | po | Nr | Nr |
Thirrja e funksionit
Live API mbështet thirrjet funksionale, ashtu si kërkesat e rregullta të gjenerimit të përmbajtjes. Thirrja e funksionit lejon Live API të ndërveprojë me të dhënat dhe programet e jashtme, duke rritur në masë të madhe atë që aplikacionet tuaja mund të arrijnë.
Ju mund të përcaktoni deklaratat e funksioneve si pjesë e konfigurimit të sesionit. Pas marrjes së thirrjeve të veglave, klienti duhet të përgjigjet me një listë të objekteve FunctionResponse
duke përdorur metodën session.send_tool_response
.
Shikoni tutorialin e thirrjes së funksionit për të mësuar më shumë.
Python
import asyncio
from google import genai
from google.genai import types
client = genai.Client(api_key="GEMINI_API_KEY")
model = "gemini-live-2.5-flash-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": ["TEXT"], "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}]})
async for chunk in session.receive():
if chunk.server_content:
if chunk.text is not None:
print(chunk.text)
elif chunk.tool_call:
function_responses = []
for fc in chunk.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)
if __name__ == "__main__":
asyncio.run(main())
JavaScript
import { GoogleGenAI, Modality } from '@google/genai';
const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
const model = 'gemini-live-2.5-flash-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.TEXT],
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.serverContent && turn.serverContent.modelTurn && turn.serverContent.modelTurn.parts) {
for (const part of turn.serverContent.modelTurn.parts) {
if (part.text) {
console.debug('Received text: %s\n', part.text);
}
}
}
else if (turn.toolCall) {
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();
for (const turn of turns) {
if (turn.serverContent && turn.serverContent.modelTurn && turn.serverContent.modelTurn.parts) {
for (const part of turn.serverContent.modelTurn.parts) {
if (part.text) {
console.debug('Received text: %s\n', part.text);
}
}
}
}
session.close();
}
async function main() {
await live().catch((e) => console.error('got error', e));
}
main();
Nga një kërkesë e vetme, modeli mund të gjenerojë thirrje të shumëfishta funksionesh dhe kodin e nevojshëm për zinxhirin e daljeve të tyre. Ky kod ekzekutohet në një mjedis sandbox, duke gjeneruar mesazhe të mëvonshme BidiGenerateContentToolCall .
Thirrja e funksionit asinkron
Thirrja e funksionit ekzekutohet në mënyrë sekuenciale si parazgjedhje, që do të thotë se ekzekutimi ndalon derisa rezultatet e çdo thirrjeje funksioni të jenë të disponueshme. Kjo siguron përpunim sekuencial, që do të thotë se nuk do të mund të vazhdoni të ndërveproni me modelin gjatë ekzekutimit të funksioneve.
Nëse nuk doni të bllokoni bisedën, mund t'i thoni modelit të ekzekutojë funksionet në mënyrë asinkrone. Për ta bërë këtë, së pari duhet të shtoni një behavior
në përkufizimet e funksionit:
Python
# Non-blocking function definitions
turn_on_the_lights = {"name": "turn_on_the_lights", "behavior": "NON_BLOCKING"} # turn_on_the_lights will run asynchronously
turn_off_the_lights = {"name": "turn_off_the_lights"} # turn_off_the_lights will still pause all interactions with the model
JavaScript
import { GoogleGenAI, Modality, Behavior } from '@google/genai';
// Non-blocking function definitions
const turn_on_the_lights = {name: "turn_on_the_lights", behavior: Behavior.NON_BLOCKING}
// Blocking function definitions
const turn_off_the_lights = {name: "turn_off_the_lights"}
const tools = [{ functionDeclarations: [turn_on_the_lights, turn_off_the_lights] }]
NON-BLOCKING
siguron që funksioni të funksionojë në mënyrë asinkrone ndërkohë që ju mund të vazhdoni të ndërveproni me modelin.
Pastaj ju duhet t'i tregoni modelit se si të sillet kur merr FunctionResponse
duke përdorur parametrin scheduling
. Mund ose:
- Ndërprisni atë që po bën dhe ju tregoni për përgjigjen që mori menjëherë (
scheduling="INTERRUPT"
), - Prisni derisa të përfundojë me atë që po bën aktualisht (
scheduling="WHEN_IDLE"
), Ose mos bëni asgjë dhe përdorni atë njohuri më vonë në diskutim (
scheduling="SILENT"
)
Python
# for a non-blocking function definition, apply scheduling in the function response:
function_response = types.FunctionResponse(
id=fc.id,
name=fc.name,
response={
"result": "ok",
"scheduling": "INTERRUPT" # Can also be WHEN_IDLE or SILENT
}
)
JavaScript
import { GoogleGenAI, Modality, Behavior, FunctionResponseScheduling } from '@google/genai';
// for a non-blocking function definition, apply scheduling in the function response:
const functionResponse = {
id: fc.id,
name: fc.name,
response: {
result: "ok",
scheduling: FunctionResponseScheduling.INTERRUPT // Can also be WHEN_IDLE or SILENT
}
}
Ekzekutimi i kodit
Ju mund të përcaktoni ekzekutimin e kodit si pjesë e konfigurimit të sesionit. Kjo lejon që API Live të gjenerojë dhe ekzekutojë kodin Python dhe të kryejë në mënyrë dinamike llogaritjet për të përfituar nga rezultatet tuaja. Shihni tutorialin e ekzekutimit të kodit për të mësuar më shumë.
Python
import asyncio
from google import genai
from google.genai import types
client = genai.Client(api_key="GEMINI_API_KEY")
model = "gemini-live-2.5-flash-preview"
tools = [{'code_execution': {}}]
config = {"response_modalities": ["TEXT"], "tools": tools}
async def main():
async with client.aio.live.connect(model=model, config=config) as session:
prompt = "Compute the largest prime palindrome under 100000."
await session.send_client_content(turns={"parts": [{"text": prompt}]})
async for chunk in session.receive():
if chunk.server_content:
if chunk.text is not None:
print(chunk.text)
model_turn = chunk.server_content.model_turn
if model_turn:
for part in model_turn.parts:
if part.executable_code is not None:
print(part.executable_code.code)
if part.code_execution_result is not None:
print(part.code_execution_result.output)
if __name__ == "__main__":
asyncio.run(main())
JavaScript
import { GoogleGenAI, Modality } from '@google/genai';
const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
const model = 'gemini-live-2.5-flash-preview';
const tools = [{codeExecution: {}}]
const config = {
responseModalities: [Modality.TEXT],
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 = 'Compute the largest prime palindrome under 100000.';
session.sendClientContent({ turns: inputTurns });
const turns = await handleTurn();
for (const turn of turns) {
if (turn.serverContent && turn.serverContent.modelTurn && turn.serverContent.modelTurn.parts) {
for (const part of turn.serverContent.modelTurn.parts) {
if (part.text) {
console.debug('Received text: %s\n', part.text);
}
else if (part.executableCode) {
console.debug('executableCode: %s\n', part.executableCode.code);
}
else if (part.codeExecutionResult) {
console.debug('codeExecutionResult: %s\n', part.codeExecutionResult.output);
}
}
}
}
session.close();
}
async function main() {
await live().catch((e) => console.error('got error', e));
}
main();
Tokëzimi me Google Search
Mund të aktivizoni Grounding me Google Search si pjesë e konfigurimit të sesionit. Kjo rrit saktësinë e Live API dhe parandalon halucinacionet. Shihni tutorialin e tokëzimit për të mësuar më shumë.
Python
import asyncio
from google import genai
from google.genai import types
client = genai.Client(api_key="GEMINI_API_KEY")
model = "gemini-live-2.5-flash-preview"
tools = [{'google_search': {}}]
config = {"response_modalities": ["TEXT"], "tools": tools}
async def main():
async with client.aio.live.connect(model=model, config=config) as session:
prompt = "When did the last Brazil vs. Argentina soccer match happen?"
await session.send_client_content(turns={"parts": [{"text": prompt}]})
async for chunk in session.receive():
if chunk.server_content:
if chunk.text is not None:
print(chunk.text)
# The model might generate and execute Python code to use Search
model_turn = chunk.server_content.model_turn
if model_turn:
for part in model_turn.parts:
if part.executable_code is not None:
print(part.executable_code.code)
if part.code_execution_result is not None:
print(part.code_execution_result.output)
if __name__ == "__main__":
asyncio.run(main())
JavaScript
import { GoogleGenAI, Modality } from '@google/genai';
const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
const model = 'gemini-live-2.5-flash-preview';
const tools = [{googleSearch: {}}]
const config = {
responseModalities: [Modality.TEXT],
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 = 'When did the last Brazil vs. Argentina soccer match happen?';
session.sendClientContent({ turns: inputTurns });
const turns = await handleTurn();
for (const turn of turns) {
if (turn.serverContent && turn.serverContent.modelTurn && turn.serverContent.modelTurn.parts) {
for (const part of turn.serverContent.modelTurn.parts) {
if (part.text) {
console.debug('Received text: %s\n', part.text);
}
else if (part.executableCode) {
console.debug('executableCode: %s\n', part.executableCode.code);
}
else if (part.codeExecutionResult) {
console.debug('codeExecutionResult: %s\n', part.codeExecutionResult.output);
}
}
}
}
session.close();
}
async function main() {
await live().catch((e) => console.error('got error', e));
}
main();
Kombinimi i shumë mjeteve
Ju mund të kombinoni shumë mjete brenda API-së Live, duke rritur edhe më shumë aftësitë e aplikacionit tuaj:
Python
prompt = """
Hey, I need you to do three things for me.
1. Compute the largest prime palindrome under 100000.
2. Then use Google Search to look up information about the largest earthquake in California the week of Dec 5 2024?
3. Turn on the lights
Thanks!
"""
tools = [
{"google_search": {}},
{"code_execution": {}},
{"function_declarations": [turn_on_the_lights, turn_off_the_lights]},
]
config = {"response_modalities": ["TEXT"], "tools": tools}
# ... remaining model call
JavaScript
const prompt = `Hey, I need you to do three things for me.
1. Compute the largest prime palindrome under 100000.
2. Then use Google Search to look up information about the largest earthquake in California the week of Dec 5 2024?
3. Turn on the lights
Thanks!
`
const tools = [
{ googleSearch: {} },
{ codeExecution: {} },
{ functionDeclarations: [turn_on_the_lights, turn_off_the_lights] }
]
const config = {
responseModalities: [Modality.TEXT],
tools: tools
}
// ... remaining model call
Çfarë është më pas
- Shikoni më shumë shembuj të përdorimit të veglave me Live API në librin e gatimit të përdorimit të veglave .
- Merrni historinë e plotë mbi veçoritë dhe konfigurimet nga udhëzuesi Live API Capabilities .