Thirrja e funksionit ju lejon të lidhni modelet me mjete të jashtme dhe API. Në vend të gjenerimit të përgjigjeve me tekst, modeli kupton se kur duhet të thërrasë funksione specifike dhe ofron parametrat e nevojshëm për të ekzekutuar veprime në botën reale. Kjo lejon që modeli të veprojë si një urë lidhëse midis gjuhës natyrore dhe veprimeve dhe të dhënave të botës reale. Thirrja e funksionit ka 3 raste të përdorimit parësor:
- Rritja e njohurive: Qasuni në informacion nga burime të jashtme si bazat e të dhënave, API-të dhe bazat e njohurive.
- Zgjeroni aftësitë: Përdorni mjete të jashtme për të kryer llogaritjet dhe për të zgjeruar kufizimet e modelit, të tilla si përdorimi i një kalkulatori ose krijimi i grafikëve.
- Merrni veprime: Ndërveproni me sisteme të jashtme duke përdorur API, të tilla si planifikimi i takimeve, krijimi i faturave, dërgimi i emaileve ose kontrollimi i pajisjeve inteligjente të shtëpisë
Si funksionon "Thirrja e funksionit".
Thirrja e funksionit përfshin një ndërveprim të strukturuar midis aplikacionit tuaj, modelit dhe funksioneve të jashtme. Këtu është një përmbledhje e procesit:
- Përcaktoni deklaratën e funksionit: Përcaktoni deklaratën e funksionit në kodin e aplikacionit tuaj. Deklaratat e funksionit përshkruajnë emrin e funksionit, parametrat dhe qëllimin e modelit.
- Thirrni LLM me deklaratat e funksionit: Dërgoni kërkesën e përdoruesit së bashku me deklaratën(et) 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, ai përgjigjet me një objekt të strukturuar JSON.
- Ekzekutoni kodin e 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 : Ekstraktoni emrin dhe args e funksionit dhe ekzekutoni funksionin përkatës në aplikacionin tuaj.
- Jo: Modeli ka dhënë 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 përgjigje miqësore për përdoruesit: Nëse një funksion është ekzekutuar, kapni rezultatin dhe dërgojeni përsëri te modeli në një kthesë të mëvonshme të bisedës. Ai do të përdorë rezultatin për të gjeneruar një përgjigje përfundimtare, miqësore për përdoruesit që përfshin informacionin nga thirrja e funksionit.
Ky proces mund të përsëritet me kthesa të shumta, duke lejuar ndërveprime komplekse dhe rrjedha pune. Modeli gjithashtu mbështet thirrjen e shumë funksioneve në një kthesë të vetme ( thirrja e funksionit paralel ) dhe në sekuencë ( thirrja e funksionit kompozicional ).
Hapi 1: Përcaktoni deklaratën e funksionit
Përcaktoni një funksion dhe deklaratën e tij brenda kodit të aplikacionit tuaj që lejon përdoruesit të vendosin vlerat e dritës dhe të bëjnë një kërkesë API. Ky funksion mund të thërrasë shërbime të jashtme ose API.
from google.genai import types
# 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}
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 të përdorë funksionin. Ai analizon deklaratat e shpejta dhe të funksioneve dhe vendos të përgjigjet drejtpërdrejt ose të thërrasë një funksion. Nëse një funksion quhet, objekti i përgjigjes do të përmbajë një sugjerim për thirrjen e funksionit.
from google import genai
# Generation Config with Function Declaration
tools = types.Tool(function_declarations=[set_light_values_declaration])
config = types.GenerateContentConfig(tools=[tools])
# Configure the client
client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))
# 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.0-flash", config=config, contents=contents
)
print(response.candidates[0].content.parts[0].function_call)
import { GoogleGenAI } from '@google/genai';
// Generation Config with Function Declaration
const config = {
tools: [{
functionDeclarations: [setLightValuesFunctionDeclaration]
}]
};
// Configure the client
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
// 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.0-flash',
contents: contents,
config: config
});
console.log(response.functionCalls[0]);
Modeli më pas kthen një objekt functionCall
në një skemë të përputhshme me OpenAPI, duke specifikuar se si të thirret një ose më shumë nga funksionet e deklaruara në mënyrë që t'i përgjigjet pyetjes së përdoruesit.
id=None args={'color_temp': 'warm', 'brightness': 25} name='set_light_values'
{
name: 'set_light_values',
args: { brightness: 25, color_temp: 'warm' }
}
Hapi 3: Ekzekutoni kodin e funksionit set_light_values
Ekstraktoni detajet e thirrjes së funksionit nga përgjigja e modelit, analizoni argumentet dhe ekzekutoni funksionin set_light_values
në kodin tonë.
# Extract tool call details
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}")
// 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: Krijo përgjigje miqësore për përdoruesit me rezultatin e funksionit dhe telefono sërish modelin
Së fundi, dërgoni rezultatin e ekzekutimit të funksionit përsëri te modeli në mënyrë që ai të mund ta inkorporojë këtë informacion në përgjigjen e tij përfundimtare ndaj përdoruesit.
# 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(types.Content(role="model", parts=[types.Part(function_call=tool_call)])) # Append the model's function call message
contents.append(types.Content(role="user", parts=[function_response_part])) # Append the function response
final_response = client.models.generate_content(
model="gemini-2.0-flash",
config=config,
contents=contents,
)
print(final_response.text)
// 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({ role: 'model', parts: [{ functionCall: tool_call }] });
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.0-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 funksionit
Kur zbatoni thirrjen e funksionit në një prompt, krijoni një objekt tools
, i cili përmban një ose më shumë function declarations
. Ju përcaktoni funksionet duke përdorur JSON, veçanërisht 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 të veçanta (përdorni nënvizat ose camelCase). -
description
(string): 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 ju ndihmojnë ("Gjen kinematë bazuar në vendndodhjen dhe opsionalisht titullin e filmit që po shfaqet aktualisht në kinema."). -
parameters
(objekt): Përcakton parametrat hyrës që pret funksioni.-
type
(string): Përcakton llojin e përgjithshëm të të dhënave, si p.sh.object
. -
properties
(objekt): Liston parametra individualë, secili me:-
type
(string): Lloji i të dhënave të parametrit, të tilla sistring
,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 Francisko, CA" ose një kod postar p.sh. "95616"."). -
enum
(array, opsionale): Nëse vlerat e parametrave janë nga një grup fiks, përdorni "enum" për të renditur vlerat e lejuara në vend që thjesht t'i përshkruani ato në përshkrim. Kjo përmirëson saktësinë ("enum": ["dritë e ditës", "cool", "ngrohtë"]).
-
-
required
(array): Një grup vargjesh që listojnë emrat e parametrave që janë të detyrueshëm për funksionimin e funksionit.
-
Thirrja e funksionit paralel
Përveç thirrjes së funksionit me një kthesë, mund të telefononi gjithashtu disa funksione njëherësh. Thirrja e funksionit paralel ju lejon të ekzekutoni funksione të shumta në të njëjtën kohë dhe përdoret kur funksionet nuk varen nga njëri-tjetri. Kjo është e dobishme në skenarë si mbledhja e të dhënave nga burime të shumta të pavarura, si p.sh. marrja e detajeve të klientit nga baza të ndryshme të dhënash ose kontrollimi i niveleve të inventarit nëpër magazina të ndryshme ose kryerja e veprimeve të shumta, si p.sh. konvertimi i banesës suaj në një disko.
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"],
},
}
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']
}
};
Thirrni modelin me një udhëzim që mund të përdorë të gjitha mjetet e specifikuara. Ky shembull përdor një tool_config
. Për të mësuar më shumë, mund të lexoni rreth konfigurimit të thirrjes së funksionit .
from google import genai
from google.genai import types
# Set up function declarations
house_tools = [
types.Tool(function_declarations=[power_disco_ball, start_music, dim_lights])
]
config = {
"tools": house_tools,
"automatic_function_calling": {"disable": True},
# Force the model to call 'any' function, instead of chatting.
"tool_config": {"function_calling_config": {"mode": "any"}},
}
# Configure the client
client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))
chat = client.chats.create(model="gemini-2.0-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})")
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({ apiKey: process.env.GEMINI_API_KEY });
// Create a chat session
const chat = ai.chats.create({
model: 'gemini-2.0-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'i dërguar rezultatet, përfshini përgjigjet në të njëjtin rend siç janë kërkuar.
Python SDK mbështet një veçori të quajtur thirrje automatike e funksionit , e cila konverton funksionin Python në deklarata, trajton ekzekutimin e thirrjes së funksionit dhe ciklin e përgjigjes për ju. Më poshtë është një shembull për rastin tonë të përdorimit të disko.
from google import genai
from google.genai import types
# Actual implementation functions
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}
config = {
"tools": [power_disco_ball_impl, start_music_impl, dim_lights_impl],
}
chat = client.chats.create(model="gemini-2.0-flash", config=config)
response = chat.send_message("Do everything you need to this place into party!")
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 kompozicional
Gemini 2.0 mbështet thirrjen e funksioneve kompozicionale, që do të thotë se modeli mund të bashkojë thirrjet e shumëfishta funksionesh së bashku. Për shembull, për t'iu përgjigjur "Merr temperaturën në vendndodhjen time aktuale", API-ja e Gemini mund të thërrasë si një funksion get_current_location()
dhe një funksion get_weather()
që merr vendndodhjen si parametër.
# 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")
// 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")
Funksiononi mënyrat e thirrjes
Gemini API ju lejon të kontrolloni se si modeli përdor mjetet e dhëna (deklaratat e funksioneve). Në mënyrë të veçantë, ju mund të vendosni modalitetin brenda function_calling_config
.
-
AUTO (Default)
: Modeli vendos nëse do të gjenerojë një përgjigje të gjuhës natyrore ose do të sugjerojë një thirrje funksioni bazuar në kërkesën dhe kontekstin. Kjo është mënyra më fleksibël dhe e rekomanduar për shumicën e skenarëve. -
ANY
: Modeli është i kufizuar të parashikojë gjithmonë një thirrje funksioni dhe të garantojë respektimin e skemës së funksionit. Nëseallowed_function_names
nuk janë specifikuar, modeli mund të zgjedhë nga ndonjë prej deklaratave të funksionit të ofruar. Nëseallowed_function_names
jepen si listë, modeli mund të zgjedhë vetëm nga funksionet në atë listë. Përdoreni këtë modalitet kur kërkoni një thirrje funksioni në përgjigje të çdo kërkese (nëse është e aplikueshme). NONE
: Modelit i ndalohet të bëjë thirrje funksionesh. Kjo është e barabartë me dërgimin e një kërkese pa asnjë deklaratë funksioni. Përdoreni këtë për të çaktivizuar përkohësisht thirrjen e funksionit pa hequr përcaktimet e veglave tuaja.
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(
temperature=0,
tools=[tools], # not defined here.
tool_config=tool_config,
)
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 = {
temperature: 0,
tools: tools, // not defined here.
toolConfig: toolConfig,
};
Thirrja automatike e funksionit (vetëm Python)
Kur përdorni Python SDK, ju mund të siguroni funksionet e Python drejtpërdrejt si mjete. SDK konverton automatikisht funksionin Python në deklarata, trajton ekzekutimin e thirrjes së funksionit dhe ciklin e përgjigjes për ju. Python SDK pastaj automatikisht:
- Zbulon përgjigjet e thirrjeve të funksionit nga modeli.
- Thirrni funksionin përkatës Python në kodin tuaj.
- Dërgon përgjigjen e funksionit përsëri te modeli.
- Rikthen përgjigjen përfundimtare të tekstit të modelit.
Për ta përdorur këtë, përcaktoni funksionin tuaj me sugjerime për llojin dhe një varg docstring, dhe më pas kaloni vetë funksionin (jo një deklaratë JSON) si një mjet:
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 and model
client = genai.Client(api_key=os.getenv("GEMINI_API_KEY")) # Replace with your actual API key setup
config = types.GenerateContentConfig(
tools=[get_current_temperature]
) # Pass the function itself
# Make the request
response = client.models.generate_content(
model="gemini-2.0-flash",
contents="What's the temperature in London?",
config=config,
)
print(response.text) # The SDK handles the function call and returns the final text
Mund të çaktivizoni thirrjen automatike të funksionit me:
# To disable automatic function calling:
config = types.GenerateContentConfig(
tools=[get_current_temperature],
automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True)
)
Deklarata automatike e skemës së funksionit
Nxjerrja automatike e skemës nga funksionet e Python nuk funksionon në të gjitha rastet. Për shembull: nuk trajton rastet kur përshkruani fushat e një objekti fjalori të ndërthurur. API është në gjendje të përshkruajë cilindo nga llojet e mëposhtme:
AllowedType = (int | float | bool | str | list['AllowedType'] | dict[str, AllowedType])
Për të parë se si duket skema e konkluduar, mund ta konvertoni atë duke përdorur from_callable
:
def multiply(a: float, b: float):
"""Returns a * b."""
return a * b
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ë veglave: Kombinoni mjetet vendase me thirrjen funksionale
Me Gemini 2.0, mund të aktivizoni mjete të shumta duke kombinuar mjetet vendase me thirrjen e funksionit në të njëjtën kohë. Ja një shembull që mundëson dy mjete, Grounding with Google Search dhe ekzekutimin e kodit , në një kërkesë duke përdorur Live API .
# 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")
// 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 Live API Tool Use .
Modelet e mbështetura
Modelet eksperimentale nuk janë të përfshira. Mund të gjeni aftësitë e tyre në faqen e përmbledhjes së modelit .
Model | Funksioni Thirrja | Thirrja e funksionit paralel | Thirrja e funksionit kompozicional (Vetëm API live) |
---|---|---|---|
Binjakët 2.0 Flash | ✔️ | ✔️ | ✔️ |
Gemini 2.0 Flash-Lite | X | X | X |
Binjakët 1.5 Flash | ✔️ | ✔️ | ✔️ |
Gemini 1.5 Pro | ✔️ | ✔️ | ✔️ |
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 duhur dhe për të dhënë argumentet e duhura.
- Emërtimi: Përdorni emrat përshkrues të funksioneve (pa hapësira, pika ose viza).
- Shtypja e fortë: Përdorni lloje specifike (integer, string, enum) për parametra për të reduktuar gabimet. Nëse një parametër ka një grup të kufizuar vlerash të vlefshme, përdorni një numër.
- Inxhinieri e shpejtë:
- Jepni kontekstin: Tregojini modelit rolin e tij (p.sh., "Ju jeni një ndihmës i dobishëm për motin.").
- Jepni udhëzime: Specifikoni se si dhe kur të përdorni funksionet (p.sh., "Mos i hamendësoni datat; përdorni gjithmonë një datë të ardhshme për parashikimet.").
- Nxitni sqarimin: Udhëzoni 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.
- Vleresimi: Nëse një thirrje funksioni ka pasoja të rëndësishme (p.sh., vendosja e një porosie), vërtetoni thirrjen me përdoruesin përpara se ta ekzekutoni.
- Trajtimi i gabimeve : Zbatoni një trajtim të fuqishëm të gabimeve në funksionet tuaja për të trajtuar me hijeshi hyrjet e papritura ose dështimet e API-së. Ktheni mesazhe gabimi informativ që modeli mund të përdorë për të gjeneruar përgjigje të dobishme për përdoruesin.
- Siguria: Kini kujdes sigurinë kur telefononi API të jashtme. Përdorni mekanizmat e duhur të vërtetimit dhe autorizimit. Shmangni ekspozimin e të dhënave të ndjeshme në thirrjet e funksionit.
- Kufijtë e Tokenit: Përshkrimet dhe parametrat e funksioneve llogariten në kufirin tuaj të shenjës hyrëse. Nëse po arrini kufijtë e shenjave, merrni parasysh kufizimin e numrit të funksioneve ose gjatësisë së 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.