Thirrja e funksioneve ju lejon të lidhni modelet me mjete dhe API të jashtme. Në vend që të gjenerojë përgjigje me tekst, modeli përcakton se kur duhet të thirren funksione specifike dhe ofron parametrat e nevojshëm për të ekzekutuar veprime të botës reale. Kjo i lejon modelit të veprojë si një urë lidhëse midis gjuhës natyrore dhe veprimeve dhe të dhënave të botës reale. Thirrja e funksioneve ka 3 raste përdorimi kryesore:
- Rrit njohuritë: Qasje informacioni nga burime të jashtme si bazat e të dhënave, API-të dhe bazat e njohurive.
- Zgjerimi i Aftësive: Përdorni mjete të jashtme për të kryer llogaritjet dhe për të zgjeruar kufizimet e modelit, siç është përdorimi i një kalkulatori ose krijimi i grafikëve.
- Ndërmerrni Veprime: Ndërveproni me sisteme të jashtme duke përdorur API-të, të tilla si caktimi i takimeve, krijimi i faturave, dërgimi i email-eve ose kontrollimi i pajisjeve inteligjente të shtëpisë.
Python
from google import genai
from google.genai import types
# Define the function declaration for the model
schedule_meeting_function = {
"name": "schedule_meeting",
"description": "Schedules a meeting with specified attendees at a given time and date.",
"parameters": {
"type": "object",
"properties": {
"attendees": {
"type": "array",
"items": {"type": "string"},
"description": "List of people attending the meeting.",
},
"date": {
"type": "string",
"description": "Date of the meeting (e.g., '2024-07-29')",
},
"time": {
"type": "string",
"description": "Time of the meeting (e.g., '15:00')",
},
"topic": {
"type": "string",
"description": "The subject or topic of the meeting.",
},
},
"required": ["attendees", "date", "time", "topic"],
},
}
# Configure the client and tools
client = genai.Client()
tools = types.Tool(function_declarations=[schedule_meeting_function])
config = types.GenerateContentConfig(tools=[tools])
# Send request with function declarations
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="Schedule a meeting with Bob and Alice for 03/14/2025 at 10:00 AM about the Q3 planning.",
config=config,
)
# Check for a function call
if response.candidates[0].content.parts[0].function_call:
function_call = response.candidates[0].content.parts[0].function_call
print(f"Function to call: {function_call.name}")
print(f"Arguments: {function_call.args}")
# In a real app, you would call your function here:
# result = schedule_meeting(**function_call.args)
else:
print("No function call found in the response.")
print(response.text)
JavaScript
import { GoogleGenAI, Type } from '@google/genai';
// Configure the client
const ai = new GoogleGenAI({});
// Define the function declaration for the model
const scheduleMeetingFunctionDeclaration = {
name: 'schedule_meeting',
description: 'Schedules a meeting with specified attendees at a given time and date.',
parameters: {
type: Type.OBJECT,
properties: {
attendees: {
type: Type.ARRAY,
items: { type: Type.STRING },
description: 'List of people attending the meeting.',
},
date: {
type: Type.STRING,
description: 'Date of the meeting (e.g., "2024-07-29")',
},
time: {
type: Type.STRING,
description: 'Time of the meeting (e.g., "15:00")',
},
topic: {
type: Type.STRING,
description: 'The subject or topic of the meeting.',
},
},
required: ['attendees', 'date', 'time', 'topic'],
},
};
// Send request with function declarations
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: 'Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about the Q3 planning.',
config: {
tools: [{
functionDeclarations: [scheduleMeetingFunctionDeclaration]
}],
},
});
// Check for function calls in the response
if (response.functionCalls && response.functionCalls.length > 0) {
const functionCall = response.functionCalls[0]; // Assuming one function call
console.log(`Function to call: ${functionCall.name}`);
console.log(`Arguments: ${JSON.stringify(functionCall.args)}`);
// In a real app, you would call your actual function here:
// const result = await scheduleMeeting(functionCall.args);
} else {
console.log("No function call found in the response.");
console.log(response.text);
}
PUSHTIM
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [
{
"role": "user",
"parts": [
{
"text": "Schedule a meeting with Bob and Alice for 03/27/2025 at 10:00 AM about the Q3 planning."
}
]
}
],
"tools": [
{
"functionDeclarations": [
{
"name": "schedule_meeting",
"description": "Schedules a meeting with specified attendees at a given time and date.",
"parameters": {
"type": "object",
"properties": {
"attendees": {
"type": "array",
"items": {"type": "string"},
"description": "List of people attending the meeting."
},
"date": {
"type": "string",
"description": "Date of the meeting (e.g., '2024-07-29')"
},
"time": {
"type": "string",
"description": "Time of the meeting (e.g., '15:00')"
},
"topic": {
"type": "string",
"description": "The subject or topic of the meeting."
}
},
"required": ["attendees", "date", "time", "topic"]
}
}
]
}
]
}'
Si funksionon thirrja e funksionit
Thirrja e funksionit përfshin një bashkëveprim të strukturuar midis aplikacionit tuaj, modelit dhe funksioneve të jashtme. Ja një përshkrim i hollësishëm i procesit:
- Përcaktoni Deklaratën e Funksionit: Përcaktoni deklaratën e funksionit në kodin e aplikacionit tuaj. Deklaratat e Funksionit përshkruajnë emrin, parametrat dhe qëllimin e funksionit për modelin.
- Thirrja e LLM me deklarata funksioni: Dërgon kërkesën e përdoruesit së bashku me deklaratën(at) e funksionit te modeli. Ai analizon kërkesën dhe përcakton nëse një thirrje funksioni do të ishte e dobishme. Nëse po, përgjigjet me një objekt të strukturuar JSON.
- Ekzekutimi i Kodit të Funksionit (Përgjegjësia Juaj): Modeli nuk e ekzekuton vetë funksionin. Është përgjegjësi e aplikacionit tuaj të përpunojë përgjigjen dhe të kontrollojë për Thirrjen e Funksionit, nëse
- Po : Nxjerr emrin dhe argumentet e funksionit dhe ekzekuto funksionin përkatës në aplikacionin tënd.
- Jo: Modeli ka ofruar një përgjigje të drejtpërdrejtë me tekst ndaj kërkesës (kjo rrjedhë është më pak e theksuar në shembull, por është një rezultat i mundshëm).
- Krijo një përgjigje miqësore për përdoruesin: Nëse një funksion është ekzekutuar, kap rezultatin dhe dërgoje përsëri te modeli në një kthesë pasuese të bisedës. Ai do ta përdorë rezultatin për të gjeneruar një përgjigje përfundimtare, miqësore për përdoruesin, e cila përfshin informacionin nga thirrja e funksionit.
Ky proces mund të përsëritet në disa raunde, duke lejuar ndërveprime dhe rrjedha pune komplekse. Modeli gjithashtu mbështet thirrjen e funksioneve të shumëfishta në një raund të vetëm ( thirrje paralele e funksioneve ) dhe në sekuencë ( thirrje kompozicionale e funksioneve ).
Hapi 1: Përcaktoni një deklaratë funksioni
Përcaktoni një funksion dhe deklarimin e tij brenda kodit të aplikacionit tuaj që u lejon përdoruesve të vendosin vlera të lehta dhe të bëjnë një kërkesë API. Ky funksion mund të thërrasë shërbime ose API të jashtme.
Python
# Define a function that the model can call to control smart lights
set_light_values_declaration = {
"name": "set_light_values",
"description": "Sets the brightness and color temperature of a light.",
"parameters": {
"type": "object",
"properties": {
"brightness": {
"type": "integer",
"description": "Light level from 0 to 100. Zero is off and 100 is full brightness",
},
"color_temp": {
"type": "string",
"enum": ["daylight", "cool", "warm"],
"description": "Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.",
},
},
"required": ["brightness", "color_temp"],
},
}
# This is the actual function that would be called based on the model's suggestion
def set_light_values(brightness: int, color_temp: str) -> dict[str, int | str]:
"""Set the brightness and color temperature of a room light. (mock API).
Args:
brightness: Light level from 0 to 100. Zero is off and 100 is full brightness
color_temp: Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.
Returns:
A dictionary containing the set brightness and color temperature.
"""
return {"brightness": brightness, "colorTemperature": color_temp}
JavaScript
import { Type } from '@google/genai';
// Define a function that the model can call to control smart lights
const setLightValuesFunctionDeclaration = {
name: 'set_light_values',
description: 'Sets the brightness and color temperature of a light.',
parameters: {
type: Type.OBJECT,
properties: {
brightness: {
type: Type.NUMBER,
description: 'Light level from 0 to 100. Zero is off and 100 is full brightness',
},
color_temp: {
type: Type.STRING,
enum: ['daylight', 'cool', 'warm'],
description: 'Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.',
},
},
required: ['brightness', 'color_temp'],
},
};
/**
* Set the brightness and color temperature of a room light. (mock API)
* @param {number} brightness - Light level from 0 to 100. Zero is off and 100 is full brightness
* @param {string} color_temp - Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.
* @return {Object} A dictionary containing the set brightness and color temperature.
*/
function setLightValues(brightness, color_temp) {
return {
brightness: brightness,
colorTemperature: color_temp
};
}
Hapi 2: Thirrni modelin me deklaratat e funksionit
Pasi të keni përcaktuar deklaratat e funksioneve tuaja, mund ta nxisni modelin që t'i përdorë ato. Ai analizon njoftimin dhe deklaratat e funksioneve dhe vendos nëse do të përgjigjet drejtpërdrejt apo do të thërrasë një funksion. Nëse thirret një funksion, objekti i përgjigjes do të përmbajë një sugjerim për thirrjen e funksionit.
Python
from google.genai import types
# Configure the client and tools
client = genai.Client()
tools = types.Tool(function_declarations=[set_light_values_declaration])
config = types.GenerateContentConfig(tools=[tools])
# Define user prompt
contents = [
types.Content(
role="user", parts=[types.Part(text="Turn the lights down to a romantic level")]
)
]
# Send request with function declarations
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=contents
config=config,
)
print(response.candidates[0].content.parts[0].function_call)
JavaScript
import { GoogleGenAI } from '@google/genai';
// Generation config with function declaration
const config = {
tools: [{
functionDeclarations: [setLightValuesFunctionDeclaration]
}]
};
// Configure the client
const ai = new GoogleGenAI({});
// Define user prompt
const contents = [
{
role: 'user',
parts: [{ text: 'Turn the lights down to a romantic level' }]
}
];
// Send request with function declarations
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: contents,
config: config
});
console.log(response.functionCalls[0]);
Modeli pastaj kthen një objekt functionCall
në një skemë të pajtueshme me OpenAPI duke specifikuar se si të thirren një ose më shumë nga funksionet e deklaruara në mënyrë që t'i përgjigjen pyetjes së përdoruesit.
Python
id=None args={'color_temp': 'warm', 'brightness': 25} name='set_light_values'
JavaScript
{
name: 'set_light_values',
args: { brightness: 25, color_temp: 'warm' }
}
Hapi 3: Ekzekutoni kodin e funksionit set_light_values
Nxirrni detajet e thirrjes së funksionit nga përgjigja e modelit, analizoni argumentet dhe ekzekutoni funksionin set_light_values
.
Python
# Extract tool call details, it may not be in the first part.
tool_call = response.candidates[0].content.parts[0].function_call
if tool_call.name == "set_light_values":
result = set_light_values(**tool_call.args)
print(f"Function execution result: {result}")
JavaScript
// Extract tool call details
const tool_call = response.functionCalls[0]
let result;
if (tool_call.name === 'set_light_values') {
result = setLightValues(tool_call.args.brightness, tool_call.args.color_temp);
console.log(`Function execution result: ${JSON.stringify(result)}`);
}
Hapi 4: Krijoni një përgjigje miqësore për përdoruesin me rezultatin e funksionit dhe thirreni modelin përsëri.
Së fundmi, dërgoni rezultatin e ekzekutimit të funksionit përsëri te modeli në mënyrë që të mund ta përfshijë këtë informacion në përgjigjen e tij përfundimtare ndaj përdoruesit.
Python
from google import genai
from google.genai import types
# Create a function response part
function_response_part = types.Part.from_function_response(
name=tool_call.name,
response={"result": result},
)
# Append function call and result of the function execution to contents
contents.append(response.candidates[0].content) # Append the content from the model's response.
contents.append(types.Content(role="user", parts=[function_response_part])) # Append the function response
client = genai.Client()
final_response = client.models.generate_content(
model="gemini-2.5-flash",
config=config,
contents=contents,
)
print(final_response.text)
JavaScript
// Create a function response part
const function_response_part = {
name: tool_call.name,
response: { result }
}
// Append function call and result of the function execution to contents
contents.push(response.candidates[0].content);
contents.push({ role: 'user', parts: [{ functionResponse: function_response_part }] });
// Get the final response from the model
const final_response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: contents,
config: config
});
console.log(final_response.text);
Kjo përfundon rrjedhën e thirrjes së funksionit. Modeli përdori me sukses funksionin set_light_values
për të kryer veprimin e kërkesës së përdoruesit.
Deklaratat e funksioneve
Kur implementoni thirrjen e funksionit në një prompt, ju krijoni një objekt tools
, i cili përmban një ose më shumë function declarations
. Ju përcaktoni funksionet duke përdorur JSON, konkretisht me një nëngrup të zgjedhur të formatit të skemës OpenAPI . Një deklaratë e vetme funksioni mund të përfshijë parametrat e mëposhtëm:
-
name
(string): Një emër unik për funksionin (get_weather_forecast
,send_email
). Përdorni emra përshkrues pa hapësira ose karaktere speciale (përdorni nënvizime ose camelCase). -
description
(varg): Një shpjegim i qartë dhe i detajuar i qëllimit dhe aftësive të funksionit. Kjo është thelbësore që modeli të kuptojë se kur duhet ta përdorë funksionin. Jini specifik dhe jepni shembuj nëse është e dobishme ("Gjen kinema bazuar në vendndodhje dhe opsionalisht titullin e filmit që aktualisht po shfaqet në kinema."). -
parameters
(objekti): Përcakton parametrat e hyrjes që pret funksioni.-
type
(string): Specifikon llojin e përgjithshëm të të dhënave, siç ështëobject
. -
properties
(objekti): Liston parametrat individualë, secili me:-
type
(string): Lloji i të dhënave të parametrit, si p.sh.string
,integer
,boolean, array
. -
description
(string): Një përshkrim i qëllimit dhe formatit të parametrit. Jepni shembuj dhe kufizime ("Qyteti dhe shteti, p.sh., 'San Francisco, CA' ose një kod postar p.sh., '95616'."). -
enum
(matricë, opsionale): Nëse vlerat e parametrave janë nga një grup i caktuar, përdorni "enum" për të listuar vlerat e lejuara në vend që t'i përshkruani ato vetëm në përshkrim. Kjo përmirëson saktësinë ("enum": ["dritë dite", "cool", "warm"]).
-
-
required
(array): Një varg vargjesh që rendisin emrat e parametrave që janë të detyrueshëm që funksioni të funksionojë.
-
Gjithashtu mund të ndërtoni Deklarata Funksionesh nga funksionet Python direkt duke përdorur types.FunctionDeclaration.from_callable(client=client, callable=your_function)
.
Thirrja e funksionit me të menduarit
Aktivizimi i " të menduarit " mund të përmirësojë performancën e thirrjes së funksionit duke i lejuar modelit të arsyetojë përmes një kërkese përpara se të sugjerojë thirrje funksioni. API-ja Gemini është pa gjendje, konteksti i arsyetimit të modelit do të humbasë midis kthesave në një bisedë me shumë kthesa. Për të ruajtur këtë kontekst, mund të përdorni nënshkrime mendimi. Një nënshkrim mendimi është një përfaqësim i koduar i procesit të brendshëm të të menduarit të modelit që ju ia kaloni modelit në kthesat pasuese.
Modeli standard për përdorimin e mjetit me shumë kthesa është shtimi i përgjigjes së plotë të mëparshme të modelit në historikun e bisedës. Objekti content
përfshin automatikisht thought_signatures
. Nëse ndiqni këtë model , nuk kërkohen ndryshime në kod .
Menaxhimi manual i nënshkrimeve të mendimit
Nëse e modifikoni historikun e bisedës manualisht - në vend që të dërgoni përgjigjen e plotë të mëparshme dhe dëshironi të përfitoni nga të menduarit, duhet ta trajtoni saktë thought_signature
të përfshirë në radhën e modelit.
Ndiqni këto rregulla për t'u siguruar që konteksti i modelit të ruhet:
- Gjithmonë dërgoje
thought_signature
përsëri te modeli brendaPart
së tij origjinale. - Mos e bashkoni një
Part
që përmban një nënshkrim me një tjetër që nuk e përmban. Kjo prish kontekstin pozicional të mendimit. - Mos kombinoni dy
Parts
që të dyja përmbajnë nënshkrime, pasi vargjet e nënshkrimeve nuk mund të bashkohen.
Inspektimi i nënshkrimeve të mendimit
Edhe pse nuk është e nevojshme për zbatim, mund ta inspektoni përgjigjen për të parë thought_signature
për qëllime debugging ose edukative.
Python
import base64
# After receiving a response from a model with thinking enabled
# response = client.models.generate_content(...)
# The signature is attached to the response part containing the function call
part = response.candidates[0].content.parts[0]
if part.thought_signature:
print(base64.b64encode(part.thought_signature).decode("utf-8"))
JavaScript
// After receiving a response from a model with thinking enabled
// const response = await ai.models.generateContent(...)
// The signature is attached to the response part containing the function call
const part = response.candidates[0].content.parts[0];
if (part.thoughtSignature) {
console.log(part.thoughtSignature);
}
Mësoni më shumë rreth kufizimeve dhe përdorimit të nënshkrimeve të mendimit, si dhe rreth modeleve të të menduarit në përgjithësi, në faqen e të menduarit .
Thirrja paralele e funksionit
Përveç thirrjes së funksionit me një kthesë të vetme, mund të thirrni edhe shumë funksione njëkohësisht. Thirrja paralele e funksioneve ju lejon të ekzekutoni shumë funksione njëkohësisht dhe përdoret kur funksionet nuk varen nga njëra-tjetra. Kjo është e dobishme në skenarë si mbledhja e të dhënave nga burime të shumta të pavarura, siç është marrja e të dhënave të klientëve nga baza të dhënash të ndryshme ose kontrollimi i niveleve të inventarit nëpër depo të ndryshme ose kryerja e veprimeve të shumta siç është shndërrimi i apartamentit tuaj në një diskotekë.
Python
power_disco_ball = {
"name": "power_disco_ball",
"description": "Powers the spinning disco ball.",
"parameters": {
"type": "object",
"properties": {
"power": {
"type": "boolean",
"description": "Whether to turn the disco ball on or off.",
}
},
"required": ["power"],
},
}
start_music = {
"name": "start_music",
"description": "Play some music matching the specified parameters.",
"parameters": {
"type": "object",
"properties": {
"energetic": {
"type": "boolean",
"description": "Whether the music is energetic or not.",
},
"loud": {
"type": "boolean",
"description": "Whether the music is loud or not.",
},
},
"required": ["energetic", "loud"],
},
}
dim_lights = {
"name": "dim_lights",
"description": "Dim the lights.",
"parameters": {
"type": "object",
"properties": {
"brightness": {
"type": "number",
"description": "The brightness of the lights, 0.0 is off, 1.0 is full.",
}
},
"required": ["brightness"],
},
}
JavaScript
import { Type } from '@google/genai';
const powerDiscoBall = {
name: 'power_disco_ball',
description: 'Powers the spinning disco ball.',
parameters: {
type: Type.OBJECT,
properties: {
power: {
type: Type.BOOLEAN,
description: 'Whether to turn the disco ball on or off.'
}
},
required: ['power']
}
};
const startMusic = {
name: 'start_music',
description: 'Play some music matching the specified parameters.',
parameters: {
type: Type.OBJECT,
properties: {
energetic: {
type: Type.BOOLEAN,
description: 'Whether the music is energetic or not.'
},
loud: {
type: Type.BOOLEAN,
description: 'Whether the music is loud or not.'
}
},
required: ['energetic', 'loud']
}
};
const dimLights = {
name: 'dim_lights',
description: 'Dim the lights.',
parameters: {
type: Type.OBJECT,
properties: {
brightness: {
type: Type.NUMBER,
description: 'The brightness of the lights, 0.0 is off, 1.0 is full.'
}
},
required: ['brightness']
}
};
Konfiguroni modalitetin e thirrjes së funksionit për të lejuar përdorimin e të gjitha mjeteve të specifikuara. Për të mësuar më shumë, mund të lexoni rreth konfigurimit të thirrjes së funksionit .
Python
from google import genai
from google.genai import types
# Configure the client and tools
client = genai.Client()
house_tools = [
types.Tool(function_declarations=[power_disco_ball, start_music, dim_lights])
]
config = types.GenerateContentConfig(
tools=house_tools,
automatic_function_calling=types.AutomaticFunctionCallingConfig(
disable=True
),
# Force the model to call 'any' function, instead of chatting.
tool_config=types.ToolConfig(
function_calling_config=types.FunctionCallingConfig(mode='ANY')
),
)
chat = client.chats.create(model="gemini-2.5-flash", config=config)
response = chat.send_message("Turn this place into a party!")
# Print out each of the function calls requested from this single call
print("Example 1: Forced function calling")
for fn in response.function_calls:
args = ", ".join(f"{key}={val}" for key, val in fn.args.items())
print(f"{fn.name}({args})")
JavaScript
import { GoogleGenAI } from '@google/genai';
// Set up function declarations
const houseFns = [powerDiscoBall, startMusic, dimLights];
const config = {
tools: [{
functionDeclarations: houseFns
}],
// Force the model to call 'any' function, instead of chatting.
toolConfig: {
functionCallingConfig: {
mode: 'any'
}
}
};
// Configure the client
const ai = new GoogleGenAI({});
// Create a chat session
const chat = ai.chats.create({
model: 'gemini-2.5-flash',
config: config
});
const response = await chat.sendMessage({message: 'Turn this place into a party!'});
// Print out each of the function calls requested from this single call
console.log("Example 1: Forced function calling");
for (const fn of response.functionCalls) {
const args = Object.entries(fn.args)
.map(([key, val]) => `${key}=${val}`)
.join(', ');
console.log(`${fn.name}(${args})`);
}
Secili prej rezultateve të printuara pasqyron një thirrje të vetme funksioni që modeli ka kërkuar. Për të dërguar rezultatet mbrapsht, përfshini përgjigjet në të njëjtën renditje siç u kërkuan.
Python SDK mbështet thirrjen automatike të funksioneve , e cila konverton automatikisht funksionet Python në deklarata, trajton ekzekutimin e thirrjes së funksioneve dhe ciklin e përgjigjes për ju. Më poshtë është një shembull për rastin e përdorimit të disco-s.
Python
from google import genai
from google.genai import types
# Actual function implementations
def power_disco_ball_impl(power: bool) -> dict:
"""Powers the spinning disco ball.
Args:
power: Whether to turn the disco ball on or off.
Returns:
A status dictionary indicating the current state.
"""
return {"status": f"Disco ball powered {'on' if power else 'off'}"}
def start_music_impl(energetic: bool, loud: bool) -> dict:
"""Play some music matching the specified parameters.
Args:
energetic: Whether the music is energetic or not.
loud: Whether the music is loud or not.
Returns:
A dictionary containing the music settings.
"""
music_type = "energetic" if energetic else "chill"
volume = "loud" if loud else "quiet"
return {"music_type": music_type, "volume": volume}
def dim_lights_impl(brightness: float) -> dict:
"""Dim the lights.
Args:
brightness: The brightness of the lights, 0.0 is off, 1.0 is full.
Returns:
A dictionary containing the new brightness setting.
"""
return {"brightness": brightness}
# Configure the client
client = genai.Client()
config = types.GenerateContentConfig(
tools=[power_disco_ball_impl, start_music_impl, dim_lights_impl]
)
# Make the request
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="Do everything you need to this place into party!",
config=config,
)
print("\nExample 2: Automatic function calling")
print(response.text)
# I've turned on the disco ball, started playing loud and energetic music, and dimmed the lights to 50% brightness. Let's get this party started!
Thirrja e funksionit kompozitiv
Thirrja e funksioneve kompozicionale ose sekuenciale i lejon Gemini-t të bashkojë thirrje të shumëfishta funksionesh për të përmbushur një kërkesë komplekse. Për shembull, për t'iu përgjigjur "Merr temperaturën në vendndodhjen time aktuale", API-ja Gemini mund të thërrasë së pari një funksion get_current_location()
të ndjekur nga një funksion get_weather()
që merr vendndodhjen si parametër.
Shembulli i mëposhtëm tregon se si të zbatohet thirrja e funksionit kompozitiv duke përdorur SDK Python dhe thirrjen automatike të funksionit.
Python
Ky shembull përdor veçorinë e thirrjes automatike të funksioneve të SDK-së Python të google-genai
. SDK-ja i konverton automatikisht funksionet Python në skemën e kërkuar, ekzekuton thirrjet e funksioneve kur kërkohen nga modeli dhe i dërgon rezultatet përsëri te modeli për të përfunduar detyrën.
import os
from google import genai
from google.genai import types
# Example Functions
def get_weather_forecast(location: str) -> dict:
"""Gets the current weather temperature for a given location."""
print(f"Tool Call: get_weather_forecast(location={location})")
# TODO: Make API call
print("Tool Response: {'temperature': 25, 'unit': 'celsius'}")
return {"temperature": 25, "unit": "celsius"} # Dummy response
def set_thermostat_temperature(temperature: int) -> dict:
"""Sets the thermostat to a desired temperature."""
print(f"Tool Call: set_thermostat_temperature(temperature={temperature})")
# TODO: Interact with a thermostat API
print("Tool Response: {'status': 'success'}")
return {"status": "success"}
# Configure the client and model
client = genai.Client()
config = types.GenerateContentConfig(
tools=[get_weather_forecast, set_thermostat_temperature]
)
# Make the request
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise set it to 18°C.",
config=config,
)
# Print the final, user-facing response
print(response.text)
Prodhimi i pritur
Kur të ekzekutoni kodin, do të shihni SDK-në duke orkestruar thirrjet e funksioneve. Modeli së pari thërret get_weather_forecast
, merr temperaturën dhe më pas thërret set_thermostat_temperature
me vlerën e saktë bazuar në logjikën në njoftim.
Tool Call: get_weather_forecast(location=London)
Tool Response: {'temperature': 25, 'unit': 'celsius'}
Tool Call: set_thermostat_temperature(temperature=20)
Tool Response: {'status': 'success'}
OK. I've set the thermostat to 20°C.
JavaScript
Ky shembull tregon se si të përdoret SDK JavaScript/TypeScript për të bërë thirrje të funksionit kompozitiv duke përdorur një cikël ekzekutimi manual.
import { GoogleGenAI, Type } from "@google/genai";
// Configure the client
const ai = new GoogleGenAI({});
// Example Functions
function get_weather_forecast({ location }) {
console.log(`Tool Call: get_weather_forecast(location=${location})`);
// TODO: Make API call
console.log("Tool Response: {'temperature': 25, 'unit': 'celsius'}");
return { temperature: 25, unit: "celsius" };
}
function set_thermostat_temperature({ temperature }) {
console.log(
`Tool Call: set_thermostat_temperature(temperature=${temperature})`,
);
// TODO: Make API call
console.log("Tool Response: {'status': 'success'}");
return { status: "success" };
}
const toolFunctions = {
get_weather_forecast,
set_thermostat_temperature,
};
const tools = [
{
functionDeclarations: [
{
name: "get_weather_forecast",
description:
"Gets the current weather temperature for a given location.",
parameters: {
type: Type.OBJECT,
properties: {
location: {
type: Type.STRING,
},
},
required: ["location"],
},
},
{
name: "set_thermostat_temperature",
description: "Sets the thermostat to a desired temperature.",
parameters: {
type: Type.OBJECT,
properties: {
temperature: {
type: Type.NUMBER,
},
},
required: ["temperature"],
},
},
],
},
];
// Prompt for the model
let contents = [
{
role: "user",
parts: [
{
text: "If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise set it to 18°C.",
},
],
},
];
// Loop until the model has no more function calls to make
while (true) {
const result = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents,
config: { tools },
});
if (result.functionCalls && result.functionCalls.length > 0) {
const functionCall = result.functionCalls[0];
const { name, args } = functionCall;
if (!toolFunctions[name]) {
throw new Error(`Unknown function call: ${name}`);
}
// Call the function and get the response.
const toolResponse = toolFunctions[name](args);
const functionResponsePart = {
name: functionCall.name,
response: {
result: toolResponse,
},
};
// Send the function response back to the model.
contents.push({
role: "model",
parts: [
{
functionCall: functionCall,
},
],
});
contents.push({
role: "user",
parts: [
{
functionResponse: functionResponsePart,
},
],
});
} else {
// No more function calls, break the loop.
console.log(result.text);
break;
}
}
Prodhimi i pritur
Kur të ekzekutoni kodin, do të shihni SDK-në duke orkestruar thirrjet e funksioneve. Modeli së pari thërret get_weather_forecast
, merr temperaturën dhe më pas thërret set_thermostat_temperature
me vlerën e saktë bazuar në logjikën në njoftim.
Tool Call: get_weather_forecast(location=London)
Tool Response: {'temperature': 25, 'unit': 'celsius'}
Tool Call: set_thermostat_temperature(temperature=20)
Tool Response: {'status': 'success'}
OK. It's 25°C in London, so I've set the thermostat to 20°C.
Thirrja e funksionit kompozitiv është një veçori native e Live API . Kjo do të thotë që Live API mund të trajtojë thirrjen e funksionit në mënyrë të ngjashme me SDK-në e Python.
Python
# Light control schemas
turn_on_the_lights_schema = {'name': 'turn_on_the_lights'}
turn_off_the_lights_schema = {'name': 'turn_off_the_lights'}
prompt = """
Hey, can you write run some python code to turn on the lights, wait 10s and then turn off the lights?
"""
tools = [
{'code_execution': {}},
{'function_declarations': [turn_on_the_lights_schema, turn_off_the_lights_schema]}
]
await run(prompt, tools=tools, modality="AUDIO")
JavaScript
// Light control schemas
const turnOnTheLightsSchema = { name: 'turn_on_the_lights' };
const turnOffTheLightsSchema = { name: 'turn_off_the_lights' };
const prompt = `
Hey, can you write run some python code to turn on the lights, wait 10s and then turn off the lights?
`;
const tools = [
{ codeExecution: {} },
{ functionDeclarations: [turnOnTheLightsSchema, turnOffTheLightsSchema] }
];
await run(prompt, tools=tools, modality="AUDIO")
Modalitetet e thirrjes së funksionit
API-ja Gemini ju lejon të kontrolloni se si modeli përdor mjetet e ofruara (deklaratat e funksioneve). Në mënyrë specifike, mund ta vendosni modalitetin brenda function_calling_config
.
-
AUTO (Default)
: Modeli vendos nëse do të gjenerojë një përgjigje në gjuhën natyrore apo do të sugjerojë një thirrje funksioni bazuar në kërkesën dhe kontekstin. Ky është modaliteti më fleksibël dhe rekomandohet për shumicën e skenarëve. -
ANY
: Modeli është i kufizuar të parashikojë gjithmonë një thirrje funksioni dhe garanton përputhshmërinë me skemën e funksionit. Nëseallowed_function_names
nuk specifikohet, modeli mund të zgjedhë nga çdo deklaratë e dhënë e funksionit. Nëseallowed_function_names
ofrohet si listë, modeli mund të zgjedhë vetëm nga funksionet në atë listë. Përdoreni këtë modalitet kur keni nevojë për një përgjigje të thirrjes së funksionit për çdo kërkesë (nëse është e aplikueshme). NONE
: Modelit i ndalohet të bëjë thirrje funksionesh. Kjo është ekuivalente me dërgimin e një kërkese pa asnjë deklaratë funksioni. Përdoreni këtë për të çaktivizuar përkohësisht thirrjen e funksioneve pa hequr përkufizimet e mjeteve tuaja.
Python
from google.genai import types
# Configure function calling mode
tool_config = types.ToolConfig(
function_calling_config=types.FunctionCallingConfig(
mode="ANY", allowed_function_names=["get_current_temperature"]
)
)
# Create the generation config
config = types.GenerateContentConfig(
tools=[tools], # not defined here.
tool_config=tool_config,
)
JavaScript
import { FunctionCallingConfigMode } from '@google/genai';
// Configure function calling mode
const toolConfig = {
functionCallingConfig: {
mode: FunctionCallingConfigMode.ANY,
allowedFunctionNames: ['get_current_temperature']
}
};
// Create the generation config
const config = {
tools: tools, // not defined here.
toolConfig: toolConfig,
};
Thirrja automatike e funksionit (vetëm Python)
Kur përdorni SDK-në Python, mund të ofroni funksione Python direkt si mjete. SDK-ja i konverton këto funksione në deklarata, menaxhon ekzekutimin e thirrjes së funksionit dhe trajton ciklin e përgjigjes për ju. Përcaktoni funksionin tuaj me këshilla për llojin dhe një docstring. Për rezultate optimale, rekomandohet të përdorni docstrings në stilin Google. SDK-ja më pas automatikisht do të:
- Zbuloni përgjigjet e thirrjes së funksionit nga modeli.
- Thirrni funksionin përkatës të Python në kodin tuaj.
- Dërgo përgjigjen e funksionit përsëri te modeli.
- Kthen përgjigjen përfundimtare me tekst të modelit.
SDK aktualisht nuk i analizon përshkrimet e argumenteve në slotet e përshkrimit të vetive të deklaratës së funksionit të gjeneruar. Në vend të kësaj, ai dërgon të gjithë docstring-un si përshkrim të funksionit të nivelit të lartë.
Python
from google import genai
from google.genai import types
# Define the function with type hints and docstring
def get_current_temperature(location: str) -> dict:
"""Gets the current temperature for a given location.
Args:
location: The city and state, e.g. San Francisco, CA
Returns:
A dictionary containing the temperature and unit.
"""
# ... (implementation) ...
return {"temperature": 25, "unit": "Celsius"}
# Configure the client
client = genai.Client()
config = types.GenerateContentConfig(
tools=[get_current_temperature]
) # Pass the function itself
# Make the request
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="What's the temperature in Boston?",
config=config,
)
print(response.text) # The SDK handles the function call and returns the final text
Mund ta çaktivizoni thirrjen automatike të funksionit me:
Python
config = types.GenerateContentConfig(
tools=[get_current_temperature],
automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True)
)
Deklarimi automatik i skemës së funksionit
API është në gjendje të përshkruajë cilindo nga llojet e mëposhtme. Llojet Pydantic
lejohen, për sa kohë që fushat e përcaktuara në to përbëhen gjithashtu nga llojet e lejuara. Llojet Dict (si dict[str: int]
) nuk mbështeten mirë këtu, mos i përdorni.
Python
AllowedType = (
int | float | bool | str | list['AllowedType'] | pydantic.BaseModel)
Për të parë se si duket skema e nxjerrë, mund ta konvertoni atë duke përdorur from_callable
:
Python
from google import genai
from google.genai import types
def multiply(a: float, b: float):
"""Returns a * b."""
return a * b
client = genai.Client()
fn_decl = types.FunctionDeclaration.from_callable(callable=multiply, client=client)
# to_json_dict() provides a clean JSON representation.
print(fn_decl.to_json_dict())
Përdorimi i shumë mjeteve: Kombinoni mjetet vendase me thirrjen e funksioneve
Mund të aktivizoni mjete të shumta duke kombinuar mjetet native me thirrjen e funksioneve në të njëjtën kohë. Ja një shembull që aktivizon dy mjete, Grounding with Google Search dhe ekzekutimin e kodit , në një kërkesë duke përdorur Live API .
Python
# Multiple tasks example - combining lights, code execution, and search
prompt = """
Hey, I need you to do three things for me.
1. Turn on the lights.
2. Then compute the largest prime palindrome under 100000.
3. Then use Google Search to look up information about the largest earthquake in California the week of Dec 5 2024.
Thanks!
"""
tools = [
{'google_search': {}},
{'code_execution': {}},
{'function_declarations': [turn_on_the_lights_schema, turn_off_the_lights_schema]} # not defined here.
]
# Execute the prompt with specified tools in audio modality
await run(prompt, tools=tools, modality="AUDIO")
JavaScript
// Multiple tasks example - combining lights, code execution, and search
const prompt = `
Hey, I need you to do three things for me.
1. Turn on the lights.
2. Then compute the largest prime palindrome under 100000.
3. Then use Google Search to look up information about the largest earthquake in California the week of Dec 5 2024.
Thanks!
`;
const tools = [
{ googleSearch: {} },
{ codeExecution: {} },
{ functionDeclarations: [turnOnTheLightsSchema, turnOffTheLightsSchema] } // not defined here.
];
// Execute the prompt with specified tools in audio modality
await run(prompt, {tools: tools, modality: "AUDIO"});
Zhvilluesit e Python mund ta provojnë këtë në fletoren e përdorimit të mjetit Live API .
Protokolli i kontekstit të modelit (MCP)
Protokolli i Kontekstit të Modelit (MCP) është një standard i hapur për lidhjen e aplikacioneve të IA-së me mjete dhe të dhëna të jashtme. MCP ofron një protokoll të përbashkët për modelet për të aksesuar kontekstin, siç janë funksionet (mjetet), burimet e të dhënave (burimet) ose kërkesat e paracaktuara.
SDK-të Gemini kanë mbështetje të integruar për MCP, duke reduktuar kodin standard dhe duke ofruar thirrje automatike të mjeteve për mjetet MCP. Kur modeli gjeneron një thirrje të mjetit MCP, SDK-ja e klientit Python dhe JavaScript mund ta ekzekutojë automatikisht mjetin MCP dhe t'ia dërgojë përgjigjen modelit në një kërkesë pasuese, duke e vazhduar këtë cikël derisa të mos bëhen më thirrje mjetesh nga modeli.
Këtu, mund të gjeni një shembull se si të përdorni një server lokal MCP me Gemini dhe mcp
SDK.
Python
Sigurohuni që versioni më i fundit i mcp
SDK është instaluar në platformën tuaj të zgjedhur.
pip install mcp
import os
import asyncio
from datetime import datetime
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from google import genai
client = genai.Client()
# Create server parameters for stdio connection
server_params = StdioServerParameters(
command="npx", # Executable
args=["-y", "@philschmid/weather-mcp"], # MCP Server
env=None, # Optional environment variables
)
async def run():
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
# Prompt to get the weather for the current day in London.
prompt = f"What is the weather in London in {datetime.now().strftime('%Y-%m-%d')}?"
# Initialize the connection between client and server
await session.initialize()
# Send request to the model with MCP function declarations
response = await client.aio.models.generate_content(
model="gemini-2.5-flash",
contents=prompt,
config=genai.types.GenerateContentConfig(
temperature=0,
tools=[session], # uses the session, will automatically call the tool
# Uncomment if you **don't** want the SDK to automatically call the tool
# automatic_function_calling=genai.types.AutomaticFunctionCallingConfig(
# disable=True
# ),
),
)
print(response.text)
# Start the asyncio event loop and run the main function
asyncio.run(run())
JavaScript
Sigurohuni që versioni më i fundit i mcp
SDK është instaluar në platformën tuaj të zgjedhur.
npm install @modelcontextprotocol/sdk
import { GoogleGenAI, FunctionCallingConfigMode , mcpToTool} from '@google/genai';
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
// Create server parameters for stdio connection
const serverParams = new StdioClientTransport({
command: "npx", // Executable
args: ["-y", "@philschmid/weather-mcp"] // MCP Server
});
const client = new Client(
{
name: "example-client",
version: "1.0.0"
}
);
// Configure the client
const ai = new GoogleGenAI({});
// Initialize the connection between client and server
await client.connect(serverParams);
// Send request to the model with MCP tools
const response = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: `What is the weather in London in ${new Date().toLocaleDateString()}?`,
config: {
tools: [mcpToTool(client)], // uses the session, will automatically call the tool
// Uncomment if you **don't** want the sdk to automatically call the tool
// automaticFunctionCalling: {
// disable: true,
// },
},
});
console.log(response.text)
// Close the connection
await client.close();
Kufizime me mbështetjen e integruar të MCP
Mbështetja e integruar për MCP është një veçori eksperimentale në SDK-të tona dhe ka kufizimet e mëposhtme:
- Mbështeten vetëm mjetet, jo burimet dhe as kërkesat
- Është i disponueshëm për SDK-në e Python dhe JavaScript/TypeScript.
- Ndryshime të rëndësishme mund të ndodhin në versionet e ardhshme.
Integrimi manual i serverëve MCP është gjithmonë një mundësi nëse këta kufizojnë atë që po ndërtoni.
Modelet e mbështetura
Ky seksion rendit modelet dhe aftësitë e tyre për thirrjen e funksioneve. Modelet eksperimentale nuk përfshihen. Mund të gjeni një përmbledhje gjithëpërfshirëse të aftësive në faqen e përmbledhjes së modelit .
Model | Thirrja e funksionit | Thirrja e Funksionit Paralel | Thirrja e Funksionit Kompozitiv |
---|---|---|---|
Gemini 2.5 Pro | ✔️ | ✔️ | ✔️ |
Binjakët 2.5 Flash | ✔️ | ✔️ | ✔️ |
Gemini 2.5 Flash-Lite | ✔️ | ✔️ | ✔️ |
Binjakët 2.0 Flash | ✔️ | ✔️ | ✔️ |
Gemini 2.0 Flash-Lite | X | X | X |
Praktikat më të mira
- Përshkrimet e Funksioneve dhe Parametrave: Jini jashtëzakonisht të qartë dhe specifikë në përshkrimet tuaja. Modeli mbështetet në këto për të zgjedhur funksionin e saktë dhe për të ofruar argumentet e duhura.
- Emërtimi: Përdorni emra përshkrues të funksioneve (pa hapësira, pika ose viza).
- Shtypje e Fortë: Përdorni lloje specifike (numër i plotë, varg, numërim) për parametrat për të zvogëluar gabimet. Nëse një parametër ka një grup të kufizuar vlerash të vlefshme, përdorni një numërim.
- Përzgjedhja e Mjeteve: Ndërsa modeli mund të përdorë një numër arbitrar mjetesh, ofrimi i shumë mjeteve mund të rrisë rrezikun e zgjedhjes së një mjeti të pasaktë ose jo optimal. Për rezultatet më të mira, synoni të ofroni vetëm mjetet përkatëse për kontekstin ose detyrën, idealisht duke e mbajtur grupin aktiv në një maksimum prej 10-20. Konsideroni përzgjedhjen dinamike të mjeteve bazuar në kontekstin e bisedës nëse keni një numër të madh mjetesh gjithsej.
- Inxhinieri e Shpejtë:
- Jepni kontekst: Tregojini modelit rolin e tij (p.sh., "Ju jeni një asistent i dobishëm i motit.").
- Jepni udhëzime: Specifikoni si dhe kur të përdoren funksionet (p.sh., "Mos hamendësoni datat; përdorni gjithmonë një datë të ardhshme për parashikimet.").
- Inkurajoni sqarimin: Udhëzojeni modelin të bëjë pyetje sqaruese nëse është e nevojshme.
- Temperatura: Përdorni një temperaturë të ulët (p.sh., 0) për thirrje funksionesh më deterministe dhe të besueshme.
- Validimi: Nëse një thirrje funksioni ka pasoja të rëndësishme (p.sh., vendosja e një porosie), validoni thirrjen me përdoruesin përpara se ta ekzekutoni atë.
- Kontrolloni Arsyen e Finishit: Kontrolloni gjithmonë
finishReason
në përgjigjen e modelit për të trajtuar rastet kur modeli dështoi të gjeneronte një thirrje të vlefshme funksioni. - Trajtimi i Gabimeve : Implementoni trajtim të fuqishëm të gabimeve në funksionet tuaja për të trajtuar me elegancë të dhënat e papritura ose dështimet e API-t. Ktheni mesazhe informuese gabimi që modeli mund t'i përdorë për të gjeneruar përgjigje të dobishme për përdoruesin.
- Siguria: Kini kujdes me sigurinë kur thirrni API-të e jashtme. Përdorni mekanizma të përshtatshëm autentifikimi dhe autorizimi. Shmangni ekspozimin e të dhënave të ndjeshme në thirrjet e funksioneve.
- Limitet e Tokenave: Përshkrimet dhe parametrat e funksioneve llogariten në limitin e tokenave hyrës. Nëse po arrini limitet e tokenave, merrni në konsideratë kufizimin e numrit të funksioneve ose gjatësinë e përshkrimeve, ndani detyrat komplekse në grupe funksionesh më të vogla dhe më të fokusuara.
Shënime dhe kufizime
- Mbështetet vetëm një nëngrup i skemës OpenAPI .
- Llojet e parametrave të mbështetur në Python janë të kufizuara.
- Thirrja automatike e funksionit është vetëm një veçori e Python SDK.