فراخوانی تابع به شما امکان می دهد مدل ها را به ابزارهای خارجی و API ها متصل کنید. به جای ایجاد پاسخ های متنی، مدل زمان فراخوانی توابع خاص را درک می کند و پارامترهای لازم را برای اجرای اقدامات دنیای واقعی ارائه می دهد. این به مدل اجازه می دهد تا به عنوان پلی بین زبان طبیعی و اقدامات و داده های دنیای واقعی عمل کند. فراخوانی تابع 3 مورد استفاده اصلی دارد:
- افزایش دانش: دسترسی به اطلاعات از منابع خارجی مانند پایگاه های داده، API ها و پایگاه های دانش.
- گسترش قابلیت ها: از ابزارهای خارجی برای انجام محاسبات و گسترش محدودیت های مدل استفاده کنید، مانند استفاده از ماشین حساب یا ایجاد نمودار.
- اقداماتی انجام دهید: با سیستمهای خارجی با استفاده از APIها تعامل داشته باشید، مانند برنامهریزی قرار ملاقات، ایجاد فاکتور، ارسال ایمیل، یا کنترل دستگاههای خانه هوشمند
نحوه کارکرد فراخوانی تابع
فراخوانی تابع شامل یک تعامل ساختاریافته بین برنامه شما، مدل و توابع خارجی است. در اینجا یک تفکیک از روند است:
- Define Function Declaration: اعلان تابع را در کد برنامه خود تعریف کنید. اعلانهای تابع نام، پارامترها و هدف تابع را برای مدل توصیف میکنند.
- فراخوانی LLM با اعلانهای تابع: درخواست کاربر را به همراه اعلانهای عملکرد به مدل ارسال کنید. این درخواست را تجزیه و تحلیل می کند و تعیین می کند که آیا فراخوانی تابع مفید است یا خیر. اگر چنین است، با یک شی JSON ساختار یافته پاسخ می دهد.
- اجرای کد تابع (مسئولیت شما): مدل خود تابع را اجرا نمی کند. این مسئولیت برنامه شما است که پاسخ را پردازش کند و اگر تابع فراخوانی را بررسی کند
- بله : نام و آرگ های تابع را استخراج کنید و تابع مربوطه را در برنامه خود اجرا کنید.
- خیر: مدل یک پاسخ متنی مستقیم به اعلان ارائه کرده است (این جریان در مثال کمتر تاکید شده است اما یک نتیجه ممکن است).
- ایجاد پاسخ کاربر پسند: اگر تابعی اجرا شد، نتیجه را بگیرید و در نوبت بعدی مکالمه آن را به مدل برگردانید. از نتیجه برای ایجاد یک پاسخ نهایی و کاربر پسند که اطلاعات فراخوانی تابع را در بر می گیرد، استفاده می کند.
این فرآیند میتواند در چندین نوبت تکرار شود و امکان تعاملات و گردشهای کاری پیچیده را فراهم کند. این مدل همچنین از فراخوانی چندین تابع در یک نوبت ( فراخوانی تابع موازی ) و به ترتیب ( فراخوانی تابع ترکیبی ) پشتیبانی می کند.
مرحله 1: تعریف تابع را تعریف کنید
یک تابع و اعلان آن را در کد برنامه خود تعریف کنید که به کاربران اجازه می دهد مقادیر نور را تنظیم کنند و درخواست API را انجام دهند. این تابع می تواند سرویس های خارجی یا 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
};
}
مرحله 2: مدل را با اعلان های تابع فراخوانی کنید
هنگامی که اعلان های تابع خود را تعریف کردید، می توانید از مدل بخواهید از تابع استفاده کند. اعلانات سریع و تابع را تجزیه و تحلیل می کند و تصمیم می گیرد که مستقیماً پاسخ دهد یا یک تابع را فراخوانی کند. اگر تابعی فراخوانی شود، شی پاسخ حاوی یک پیشنهاد فراخوانی تابع خواهد بود.
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]);
سپس مدل یک شی functionCall
را در طرحی سازگار با OpenAPI برمیگرداند که نحوه فراخوانی یک یا چند توابع اعلامشده را برای پاسخ به سؤال کاربر مشخص میکند.
id=None args={'color_temp': 'warm', 'brightness': 25} name='set_light_values'
{
name: 'set_light_values',
args: { brightness: 25, color_temp: 'warm' }
}
مرحله 3: کد تابع set_light_values را اجرا کنید
جزئیات فراخوانی تابع را از پاسخ مدل استخراج کنید، آرگومان ها را تجزیه کنید و تابع set_light_values
را در کد ما اجرا کنید.
# 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)}`);
}
مرحله 4: پاسخ کاربر پسند را با نتیجه تابع ایجاد کنید و دوباره مدل را فراخوانی کنید
در نهایت، نتیجه اجرای تابع را به مدل برگردانید تا بتواند این اطلاعات را در پاسخ نهایی خود به کاربر بگنجاند.
# 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);
این جریان فراخوانی تابع را کامل می کند. مدل با موفقیت از تابع set_light_values
برای انجام عمل درخواست کاربر استفاده کرد.
اعلامیه های عملکرد
هنگامی که فراخوانی تابع را در یک درخواست پیاده سازی می کنید، یک شی tools
ایجاد می کنید که حاوی یک یا چند function declarations
است. توابع را با استفاده از JSON تعریف میکنید، بهویژه با یک زیرمجموعه انتخابی از قالب طرحواره OpenAPI . یک اعلان تابع می تواند شامل پارامترهای زیر باشد:
-
name
(رشته): یک نام منحصر به فرد برای تابع (get_weather_forecast
،send_email
). از نام های توصیفی بدون فاصله یا نویسه های خاص استفاده کنید (از زیرخط یا camelCase استفاده کنید). -
description
(رشته): توضیح واضح و دقیق از هدف و قابلیت های تابع. این برای مدل برای درک زمان استفاده از تابع بسیار مهم است. مشخص باشید و در صورت مفید بودن مثالهایی ارائه دهید ("سینماها را بر اساس موقعیت مکانی و به صورت اختیاری عنوان فیلمی که در حال حاضر در سینماها پخش میشود، پیدا میکند."). -
parameters
(شیء): پارامترهای ورودی مورد انتظار تابع را تعریف می کند.-
type
(string): نوع کلی داده را مشخص می کند، مانندobject
. -
properties
(شیء): پارامترهای فردی را فهرست می کند که هر کدام دارای:-
type
(رشته): نوع داده پارامتر مانندstring
،integer
،boolean, array
. -
description
(رشته): شرحی از هدف و قالب پارامتر. مثالها و محدودیتهایی را ارائه کنید ("شهر و ایالت، به عنوان مثال، "سان فرانسیسکو، کالیفرنیا" یا یک کد پستی مانند "95616"."). -
enum
(آرایه، اختیاری): اگر مقادیر پارامتر از یک مجموعه ثابت هستند، به جای اینکه فقط آنها را در توضیحات توضیح دهید، از "enum" برای فهرست کردن مقادیر مجاز استفاده کنید. این دقت را بهبود می بخشد ("enum": ["نور روز"، "سرد"، "گرم"]).
-
-
required
(آرایه): آرایه ای از رشته ها که نام پارامترهایی را که برای عملکرد تابع اجباری هستند فهرست می کند.
-
فراخوانی تابع موازی
علاوه بر فراخوانی تابع تک نوبتی، میتوانید چندین تابع را همزمان فراخوانی کنید. فراخوانی تابع موازی به شما امکان می دهد چندین تابع را همزمان اجرا کنید و زمانی استفاده می شود که توابع به یکدیگر وابسته نباشند. این در سناریوهایی مانند جمعآوری دادهها از چندین منبع مستقل مفید است، مانند بازیابی اطلاعات مشتری از پایگاههای داده مختلف یا بررسی سطح موجودی در انبارهای مختلف یا انجام اقدامات متعدد مانند تبدیل آپارتمان شما به دیسکو.
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']
}
};
مدل را با دستورالعملی فراخوانی کنید که بتواند از همه ابزارهای مشخص شده استفاده کند. این مثال از یک tool_config
استفاده می کند. برای کسب اطلاعات بیشتر می توانید در مورد پیکربندی فراخوانی تابع مطالعه کنید.
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})`);
}
هر یک از نتایج چاپ شده منعکس کننده یک فراخوانی تابعی است که مدل درخواست کرده است. برای بازگرداندن نتایج، پاسخها را به همان ترتیبی که درخواست شده است وارد کنید.
Python SDK از قابلیتی به نام فراخوانی خودکار تابع پشتیبانی می کند که تابع پایتون را به اعلان تبدیل می کند، اجرای فراخوانی تابع و چرخه پاسخ را برای شما مدیریت می کند. در زیر یک مثال برای مورد استفاده از دیسکو ما آورده شده است.
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!
فراخوانی تابع ترکیبی
Gemini 2.0 از فراخوانی تابع ترکیبی پشتیبانی میکند، به این معنی که مدل میتواند چندین فراخوانی تابع را با هم زنجیرهای کند. به عنوان مثال، برای پاسخ به "دریافت دما در مکان فعلی من"، API Gemini ممکن است هم تابع get_current_location()
و هم یک تابع get_weather()
را فراخوانی کند که موقعیت مکانی را به عنوان پارامتر می گیرد.
# 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")
عملکرد حالت های تماس
Gemini API به شما امکان می دهد نحوه استفاده مدل از ابزارهای ارائه شده (اعلان های عملکرد) را کنترل کنید. به طور خاص، می توانید حالت را در function_calling_config
تنظیم کنید.
-
AUTO (Default)
: مدل تصمیم میگیرد که یک پاسخ زبان طبیعی ایجاد کند یا یک فراخوانی تابع را بر اساس درخواست و زمینه پیشنهاد کند. این انعطاف پذیرترین حالت است و برای اکثر سناریوها توصیه می شود. -
ANY
: مدل محدود است تا همیشه یک فراخوانی تابع را پیش بینی کند و پایبندی طرحواره تابع را تضمین کند. اگرallowed_function_names
مشخص نشده باشد، مدل می تواند از هر یک از اعلان های تابع ارائه شده انتخاب کند. اگرallowed_function_names
به صورت لیست ارائه شود، مدل فقط می تواند از توابع موجود در آن لیست انتخاب کند. از این حالت زمانی استفاده کنید که نیاز به فراخوانی عملکرد در پاسخ به هر درخواست دارید (در صورت وجود). NONE
: مدل از برقراری فراخوانی تابع منع شده است. این معادل ارسال درخواست بدون هیچ گونه اعلان عملکرد است. از این برای غیرفعال کردن موقت فراخوانی عملکرد بدون حذف تعاریف ابزار خود استفاده کنید.
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,
};
فراخوانی خودکار تابع (فقط پایتون)
هنگام استفاده از Python SDK، می توانید توابع پایتون را مستقیماً به عنوان ابزار ارائه دهید. SDK به طور خودکار تابع پایتون را به اعلان تبدیل می کند، اجرای فراخوانی تابع و چرخه پاسخ را برای شما مدیریت می کند. سپس Python SDK به طور خودکار:
- پاسخ های فراخوانی تابع را از مدل تشخیص می دهد.
- تابع Python مربوطه را در کد خود فراخوانی کنید.
- پاسخ تابع را به مدل برمی گرداند.
- پاسخ متنی نهایی مدل را برمیگرداند.
برای استفاده از این، تابع خود را با راهنمایی نوع و یک رشته docstring تعریف کنید، و سپس خود تابع (نه یک اعلان JSON) را به عنوان ابزار ارسال کنید:
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
می توانید تماس خودکار عملکردی را با موارد زیر غیرفعال کنید:
# To disable automatic function calling:
config = types.GenerateContentConfig(
tools=[get_current_temperature],
automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True)
)
اعلام طرح عملکرد خودکار
استخراج خودکار طرحواره از توابع پایتون در همه موارد کار نمی کند. به عنوان مثال: مواردی را که در آن شما فیلدهای یک دیکشنری-شیء تودرتو را توصیف می کنید، رسیدگی نمی کند. API قادر است هر یک از انواع زیر را توصیف کند:
AllowedType = (int | float | bool | str | list['AllowedType'] | dict[str, AllowedType])
برای اینکه ببینید طرح استنتاج شده چگونه به نظر می رسد، می توانید آن را با استفاده از 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())
استفاده از چند ابزار: ترکیب Native Tools با Function Calling
با Gemini 2.0، میتوانید چندین ابزار را فعال کنید که همزمان ابزارهای بومی را با فراخوانی تابع ترکیب میکنند. در اینجا یک مثال است که دو ابزار، Grounding با جستجوی Google و اجرای کد را در یک درخواست با استفاده از 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"});
توسعه دهندگان پایتون می توانند این را در دفترچه یادداشت Live API Tool Use امتحان کنند.
مدل های پشتیبانی شده
مدل های آزمایشی گنجانده نشده است. می توانید قابلیت های آنها را در صفحه نمای کلی مدل بیابید.
مدل | فراخوانی تابع | فراخوانی تابع موازی | فراخوانی تابع ترکیبی (فقط Live API) |
---|---|---|---|
فلش جمینی 2.0 | ✔️ | ✔️ | ✔️ |
Gemini 2.0 Flash-Lite | X | X | X |
فلش جمینی 1.5 | ✔️ | ✔️ | ✔️ |
جمینی 1.5 پرو | ✔️ | ✔️ | ✔️ |
بهترین شیوه ها
- توضیحات عملکرد و پارامتر: در توضیحات خود بسیار واضح و مشخص باشید. مدل برای انتخاب تابع صحیح و ارائه آرگومان های مناسب بر اینها متکی است.
- نامگذاری: از نام توابع توصیفی (بدون فاصله، نقطه یا خط تیره) استفاده کنید.
- تایپ قوی: از انواع خاصی (عدد صحیح، رشته، enum) برای پارامترها برای کاهش خطاها استفاده کنید. اگر پارامتری دارای مجموعه محدودی از مقادیر معتبر است، از یک enum استفاده کنید.
- مهندسی سریع:
- زمینه را ارائه دهید: نقش مدل را بگویید (به عنوان مثال، "شما یک دستیار آب و هوای مفید هستید.").
- دستورالعملها را ارائه دهید: نحوه و زمان استفاده از توابع را مشخص کنید (به عنوان مثال، "تاریخها را حدس نزنید، همیشه از تاریخ آینده برای پیشبینیها استفاده کنید.").
- تشويق شفاف سازي: به مدل دستور دهيد در صورت نياز سؤالات روشنگري بپرسد.
- دما: از دمای پایین (مثلاً 0) برای فراخوانی عملکرد قطعی تر و مطمئن تر استفاده کنید.
- اعتبارسنجی: اگر فراخوانی تابع پیامدهای مهمی دارد (مثلاً ثبت سفارش)، قبل از اجرای آن تماس را با کاربر تأیید کنید.
- مدیریت خطا : مدیریت خطای قوی را در توابع خود اجرا کنید تا ورودی های غیرمنتظره یا خرابی های API را به خوبی مدیریت کنید. پیامهای خطای آموزندهای را که مدل میتواند برای ایجاد پاسخهای مفید برای کاربر استفاده کند، برگردانید.
- امنیت: هنگام فراخوانی APIهای خارجی مراقب امنیت باشید. از مکانیسم های احراز هویت و مجوز مناسب استفاده کنید. از افشای داده های حساس در فراخوانی تابع خودداری کنید.
- محدودیتهای رمز: توضیحات و پارامترهای عملکرد در حد توکن ورودی شما به حساب میآیند. اگر به محدودیتهای نشانهای رسیدهاید، تعداد توابع یا طول توضیحات را محدود کنید، وظایف پیچیده را به مجموعههای عملکردی کوچکتر و متمرکزتر تقسیم کنید.
یادداشت ها و محدودیت ها
- فقط زیر مجموعه ای از طرحواره OpenAPI پشتیبانی می شود.
- انواع پارامترهای پشتیبانی شده در پایتون محدود است.
- فراخوانی خودکار تابع فقط یک ویژگی SDK پایتون است.