টুল ব্যবহারের ফলে লাইভ এপিআই কেবল কথোপকথনের বাইরেও যেতে পারে, বাস্তব জগতে ক্রিয়া সম্পাদন করতে এবং রিয়েল টাইম সংযোগ বজায় রেখে বাহ্যিক প্রেক্ষাপটে টানতে সক্ষম হয়। আপনি লাইভ এপিআই ব্যবহার করে ফাংশন কলিং এবং গুগল সার্চের মতো টুলগুলি সংজ্ঞায়িত করতে পারেন।
সমর্থিত সরঞ্জামগুলির সংক্ষিপ্ত বিবরণ
লাইভ এপিআই মডেলের জন্য উপলব্ধ সরঞ্জামগুলির একটি সংক্ষিপ্ত বিবরণ এখানে দেওয়া হল:
| টুল | gemini-2.5-flash-native-audio-preview-09-2025 |
|---|---|
| অনুসন্ধান করুন | হাঁ |
| ফাংশন কলিং | হাঁ |
| গুগল ম্যাপস | না |
| কোড এক্সিকিউশন | না |
| URL প্রসঙ্গ | না |
ফাংশন কলিং
লাইভ এপিআই ফাংশন কলিং সমর্থন করে, ঠিক নিয়মিত কন্টেন্ট জেনারেশন অনুরোধের মতো। ফাংশন কলিং লাইভ এপিআইকে বহিরাগত ডেটা এবং প্রোগ্রামগুলির সাথে ইন্টারঅ্যাক্ট করতে দেয়, যা আপনার অ্যাপ্লিকেশনগুলির অর্জনকে ব্যাপকভাবে বৃদ্ধি করে।
আপনি সেশন কনফিগারেশনের অংশ হিসেবে ফাংশন ডিক্লেয়ারেশন সংজ্ঞায়িত করতে পারেন। টুল কল পাওয়ার পর, ক্লায়েন্টকে session.send_tool_response পদ্ধতি ব্যবহার করে FunctionResponse অবজেক্টের একটি তালিকা দিয়ে সাড়া দিতে হবে।
আরও জানতে ফাংশন কলিং টিউটোরিয়ালটি দেখুন।
পাইথন
import asyncio
import wave
from google import genai
from google.genai import types
client = genai.Client()
model = "gemini-2.5-flash-native-audio-preview-09-2025"
# 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())
জাভাস্ক্রিপ্ট
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-2.5-flash-native-audio-preview-09-2025';
// 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) => {
if (turn.data) {
const buffer = Buffer.from(turn.data, 'base64');
const intArray = new Int16Array(buffer.buffer, buffer.byteOffset, buffer.byteLength / Int16Array.BYTES_PER_ELEMENT);
return acc.concat(Array.from(intArray));
}
return acc;
}, []);
const audioBuffer = new Int16Array(combinedAudio);
const wf = new WaveFile();
wf.fromScratch(1, 24000, '16', audioBuffer); // output is 24kHz
fs.writeFileSync('audio.wav', wf.toBuffer());
session.close();
}
async function main() {
await live().catch((e) => console.error('got error', e));
}
main();
একটি একক প্রম্পট থেকে, মডেলটি একাধিক ফাংশন কল এবং তাদের আউটপুট চেইন করার জন্য প্রয়োজনীয় কোড তৈরি করতে পারে। এই কোডটি একটি স্যান্ডবক্স পরিবেশে কার্যকর হয়, পরবর্তী BidiGenerateContentToolCall বার্তা তৈরি করে।
অ্যাসিঙ্ক্রোনাস ফাংশন কলিং
ফাংশন কলিং ডিফল্টভাবে ক্রমানুসারে কার্যকর হয়, অর্থাৎ প্রতিটি ফাংশন কলের ফলাফল উপলব্ধ না হওয়া পর্যন্ত এক্সিকিউশন বিরতি দেয়। এটি ক্রমানুসারে প্রক্রিয়াকরণ নিশ্চিত করে, যার অর্থ ফাংশনগুলি চালানোর সময় আপনি মডেলের সাথে ইন্টারঅ্যাক্ট করতে পারবেন না।
যদি আপনি কথোপকথনটি ব্লক করতে না চান, তাহলে আপনি মডেলটিকে ফাংশনগুলি অ্যাসিঙ্ক্রোনাসভাবে চালাতে বলতে পারেন। এটি করার জন্য, আপনাকে প্রথমে ফাংশনের সংজ্ঞাগুলিতে একটি behavior যুক্ত করতে হবে:
পাইথন
# 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
জাভাস্ক্রিপ্ট
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 নিশ্চিত করে যে ফাংশনটি অ্যাসিঙ্ক্রোনাসভাবে চলে এবং আপনি মডেলের সাথে ইন্টারঅ্যাক্ট চালিয়ে যেতে পারেন।
তারপর আপনাকে মডেলটিকে বলতে হবে যে যখন এটি FunctionResponse গ্রহণ করবে তখন কীভাবে আচরণ করবে, scheduling প্যারামিটার ব্যবহার করে। এটি যে কোনও একটি করতে পারে:
- এটি যা করছে তা থামান এবং এটি যে প্রতিক্রিয়া পেয়েছে তা আপনাকে অবিলম্বে বলুন (
scheduling="INTERRUPT"), - এটি বর্তমানে যা করছে তা শেষ না হওয়া পর্যন্ত অপেক্ষা করুন (
scheduling="WHEN_IDLE"), অথবা কিছুই করবেন না এবং পরে আলোচনায় সেই জ্ঞান ব্যবহার করুন (
scheduling="SILENT")
পাইথন
# 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
}
)
জাভাস্ক্রিপ্ট
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
}
}
গুগল সার্চের মাধ্যমে গ্রাউন্ডিং
সেশন কনফিগারেশনের অংশ হিসেবে আপনি Google Search দিয়ে Grounding সক্ষম করতে পারেন। এটি Live API-এর নির্ভুলতা বৃদ্ধি করে এবং হ্যালুসিনেশন প্রতিরোধ করে। আরও জানতে Grounding টিউটোরিয়ালটি দেখুন।
পাইথন
import asyncio
import wave
from google import genai
from google.genai import types
client = genai.Client()
model = "gemini-2.5-flash-native-audio-preview-09-2025"
tools = [{'google_search': {}}]
config = {"response_modalities": ["AUDIO"], "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}]})
wf = wave.open("audio.wav", "wb")
wf.setnchannels(1)
wf.setsampwidth(2)
wf.setframerate(24000) # Output is 24kHz
async for chunk in session.receive():
if chunk.server_content:
if chunk.data is not None:
wf.writeframes(chunk.data)
# 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)
wf.close()
if __name__ == "__main__":
asyncio.run(main())
জাভাস্ক্রিপ্ট
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-2.5-flash-native-audio-preview-09-2025';
const tools = [{ googleSearch: {} }]
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 = 'When did the last Brazil vs. Argentina soccer match happen?';
session.sendClientContent({ turns: inputTurns });
let turns = await handleTurn();
let combinedData = '';
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.executableCode) {
console.debug('executableCode: %s\n', part.executableCode.code);
}
else if (part.codeExecutionResult) {
console.debug('codeExecutionResult: %s\n', part.codeExecutionResult.output);
}
else if (part.inlineData && typeof part.inlineData.data === 'string') {
combinedData += atob(part.inlineData.data);
}
}
}
}
// Convert the base64-encoded string of bytes into a Buffer.
const buffer = Buffer.from(combinedData, 'binary');
// The buffer contains raw bytes. For 16-bit audio, we need to interpret every 2 bytes as a single sample.
const intArray = new Int16Array(buffer.buffer, buffer.byteOffset, buffer.byteLength / Int16Array.BYTES_PER_ELEMENT);
const wf = new WaveFile();
// The API returns 16-bit PCM audio at a 24kHz sample rate.
wf.fromScratch(1, 24000, '16', intArray);
fs.writeFileSync('audio.wav', wf.toBuffer());
session.close();
}
async function main() {
await live().catch((e) => console.error('got error', e));
}
main();
একাধিক সরঞ্জাম একত্রিত করা
আপনি লাইভ API-এর মধ্যে একাধিক টুল একত্রিত করতে পারেন, যা আপনার অ্যাপ্লিকেশনের ক্ষমতা আরও বাড়িয়ে তোলে:
পাইথন
prompt = """
Hey, I need you to do two things for me.
1. Use Google Search to look up information about the largest earthquake in California the week of Dec 5 2024?
2. Then turn on the lights
Thanks!
"""
tools = [
{"google_search": {}},
{"function_declarations": [turn_on_the_lights, turn_off_the_lights]},
]
config = {"response_modalities": ["AUDIO"], "tools": tools}
# ... remaining model call
জাভাস্ক্রিপ্ট
const prompt = `Hey, I need you to do two things for me.
1. Use Google Search to look up information about the largest earthquake in California the week of Dec 5 2024?
2. Then turn on the lights
Thanks!
`
const tools = [
{ googleSearch: {} },
{ functionDeclarations: [turn_on_the_lights, turn_off_the_lights] }
]
const config = {
responseModalities: [Modality.AUDIO],
tools: tools
}
// ... remaining model call
এরপর কি?
- টুল ইউজ কুকবুক -এ লাইভ API ব্যবহার করে টুল ব্যবহারের আরও উদাহরণ দেখুন।
- লাইভ এপিআই ক্যাপাবিলিটিস গাইড থেকে বৈশিষ্ট্য এবং কনফিগারেশন সম্পর্কে সম্পূর্ণ বিবরণ পান।