Panggilan fungsi memungkinkan Anda menghubungkan model ke alat dan API eksternal. Alih-alih menghasilkan respons teks, model memahami kapan harus memanggil fungsi tertentu dan memberikan parameter yang diperlukan untuk menjalankan tindakan dunia nyata. Hal ini memungkinkan model bertindak sebagai jembatan antara bahasa alami dan tindakan serta data dunia nyata. Panggilan fungsi memiliki 3 kasus penggunaan utama:
- Meningkatkan Pengetahuan: Mengakses informasi dari sumber eksternal seperti database, API, dan pusat informasi.
- Memperluas Kemampuan: Menggunakan alat eksternal untuk melakukan komputasi dan memperluas batasan model, seperti menggunakan kalkulator atau membuat diagram.
- Mengambil Tindakan: Berinteraksi dengan sistem eksternal menggunakan API, seperti menjadwalkan janji temu, membuat invoice, mengirim email, atau mengontrol perangkat smart home
Cara Kerja Panggilan Fungsi
Panggilan fungsi melibatkan interaksi terstruktur antara aplikasi, model, dan fungsi eksternal Anda. Berikut rincian prosesnya:
- Tentukan Deklarasi Fungsi: Tentukan deklarasi fungsi dalam kode aplikasi Anda. Deklarasi Fungsi menjelaskan nama, parameter, dan tujuan fungsi ke model.
- Memanggil LLM dengan deklarasi fungsi: Kirim perintah pengguna beserta deklarasi fungsi ke model. Fungsi ini menganalisis permintaan dan menentukan apakah panggilan fungsi akan berguna. Jika ya, objek akan merespons dengan objek JSON terstruktur.
- Mengeksekusi Kode Fungsi (Tanggung Jawab Anda): Model tidak
mengeksekusi fungsi itu sendiri. Aplikasi Anda bertanggung jawab untuk
memproses respons dan memeriksa Panggilan Fungsi, jika
- Ya: Ekstrak nama dan argumen fungsi, lalu jalankan fungsi yang sesuai di aplikasi Anda.
- Tidak: Model telah memberikan respons teks langsung ke perintah (alur ini kurang ditekankan dalam contoh, tetapi merupakan kemungkinan hasil).
- Buat Respons yang mudah digunakan: Jika fungsi dijalankan, tangkap hasilnya dan kirim kembali ke model pada giliran percakapan berikutnya. Fungsi ini akan menggunakan hasilnya untuk menghasilkan respons akhir yang mudah digunakan yang menggabungkan informasi dari panggilan fungsi.
Proses ini dapat diulang selama beberapa giliran, sehingga memungkinkan interaksi dan alur kerja yang kompleks. Model ini juga mendukung pemanggilan beberapa fungsi dalam satu giliran (panggilan fungsi paralel) dan secara berurutan (panggilan fungsi komposisi).
Langkah 1: Menentukan Pernyataan Fungsi
Tentukan fungsi dan deklarasinya dalam kode aplikasi Anda yang memungkinkan pengguna menetapkan nilai cahaya dan membuat permintaan API. Fungsi ini dapat memanggil layanan atau API eksternal.
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
};
}
Langkah 2: Panggil model dengan deklarasi fungsi
Setelah menentukan deklarasi fungsi, Anda dapat meminta model untuk menggunakan fungsi tersebut. Fungsi ini menganalisis perintah dan deklarasi fungsi, lalu memutuskan untuk merespons secara langsung atau memanggil fungsi. Jika fungsi dipanggil, objek respons akan berisi saran panggilan fungsi.
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]);
Model kemudian menampilkan objek functionCall
dalam skema yang kompatibel dengan
OpenAPI yang menentukan cara memanggil satu atau beberapa fungsi yang dideklarasikan untuk
merespons pertanyaan pengguna.
id=None args={'color_temp': 'warm', 'brightness': 25} name='set_light_values'
{
name: 'set_light_values',
args: { brightness: 25, color_temp: 'warm' }
}
Langkah 3: Jalankan kode fungsi set_light_values
Ekstrak detail panggilan fungsi dari respons model, mengurai argumen,
dan menjalankan fungsi set_light_values
dalam kode kita.
# 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)}`);
}
Langkah 4: Buat respons yang mudah digunakan dengan hasil fungsi dan panggil model lagi
Terakhir, kirim hasil eksekusi fungsi kembali ke model agar dapat menggabungkan informasi ini ke dalam respons akhirnya kepada pengguna.
# 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);
Tindakan ini akan menyelesaikan alur panggilan fungsi. Model berhasil menggunakan fungsi set_light_values
untuk melakukan tindakan permintaan pengguna.
Deklarasi fungsi
Saat menerapkan panggilan fungsi dalam perintah, Anda membuat objek tools
, yang berisi satu atau beberapa function declarations
. Anda menentukan fungsi menggunakan JSON, khususnya dengan subset tertentu dari format skema OpenAPI. Satu deklarasi fungsi dapat menyertakan parameter berikut:
name
(string): Nama unik untuk fungsi (get_weather_forecast
,send_email
). Gunakan nama deskriptif tanpa spasi atau karakter khusus (gunakan garis bawah atau camelCase).description
(string): Penjelasan yang jelas dan mendetail tentang tujuan dan kemampuan fungsi. Hal ini penting bagi model untuk memahami kapan harus menggunakan fungsi. Jelaskan secara spesifik dan berikan contoh jika bermanfaat ("Menemukan bioskop berdasarkan lokasi dan secara opsional judul film yang saat ini diputar di bioskop").parameters
(objek): Menentukan parameter input yang diharapkan fungsi.type
(string): Menentukan jenis data secara keseluruhan, sepertiobject
.properties
(objek): Mencantumkan setiap parameter, masing-masing dengan:type
(string): Jenis data parameter, sepertistring
,integer
,boolean, array
.description
(string): Deskripsi tujuan dan format parameter. Berikan contoh dan batasan ("Kota dan negara bagian, misalnya, 'Jakarta, Indonesia' atau kode pos, misalnya, '95616'.").enum
(array, opsional): Jika nilai parameter berasal dari kumpulan tetap, gunakan "enum" untuk mencantumkan nilai yang diizinkan, bukan hanya mendeskripsikannya dalam deskripsi. Hal ini meningkatkan akurasi ("enum": ["daylight", "cool", "warm"]).
required
(array): Array string yang mencantumkan nama parameter yang wajib agar fungsi dapat beroperasi.
Panggilan Fungsi Paralel
Selain panggilan fungsi satu belokan, Anda juga dapat memanggil beberapa fungsi sekaligus. Panggilan fungsi paralel memungkinkan Anda menjalankan beberapa fungsi sekaligus dan digunakan saat fungsi tidak bergantung satu sama lain. Hal ini berguna dalam skenario seperti mengumpulkan data dari beberapa sumber independen, seperti mengambil detail pelanggan dari database yang berbeda atau memeriksa tingkat inventaris di berbagai gudang atau melakukan beberapa tindakan seperti mengubah apartemen Anda menjadi 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']
}
};
Panggil model dengan petunjuk yang dapat menggunakan semua alat yang ditentukan. Contoh ini menggunakan tool_config
. Untuk mempelajari lebih lanjut, Anda dapat membaca artikel tentang mengonfigurasi panggilan fungsi.
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})`);
}
Setiap hasil yang dicetak mencerminkan satu panggilan fungsi yang telah diminta model. Untuk mengirim kembali hasilnya, sertakan respons dalam urutan yang sama seperti yang diminta.
Python SDK mendukung fitur yang disebut panggilan fungsi otomatis yang mengonversi fungsi Python menjadi deklarasi, menangani siklus respons dan eksekusi panggilan fungsi untuk Anda. Berikut adalah contoh untuk kasus penggunaan disco.
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!
Panggilan Fungsi Komposisi
Gemini 2.0 mendukung panggilan fungsi komposisi, yang berarti model dapat merantai beberapa panggilan fungsi secara bersamaan. Misalnya, untuk menjawab "Dapatkan suhu di lokasi saya saat ini", Gemini API mungkin memanggil fungsi get_current_location()
dan fungsi get_weather()
yang menggunakan lokasi sebagai parameter.
# 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")
Mode panggilan fungsi
Gemini API memungkinkan Anda mengontrol cara model menggunakan alat yang disediakan (deklarasi fungsi). Secara khusus, Anda dapat menetapkan mode dalam function_calling_config
.
AUTO (Default)
: Model memutuskan apakah akan menghasilkan respons natural language atau menyarankan panggilan fungsi berdasarkan perintah dan konteks. Ini adalah mode yang paling fleksibel dan direkomendasikan untuk sebagian besar skenario.ANY
: Model dibatasi untuk selalu memprediksi panggilan fungsi dan menjamin kepatuhan skema fungsi. Jikaallowed_function_names
tidak ditentukan, model dapat memilih dari salah satu deklarasi fungsi yang disediakan. Jikaallowed_function_names
diberikan sebagai daftar, model hanya dapat memilih dari fungsi dalam daftar tersebut. Gunakan mode ini saat Anda memerlukan panggilan fungsi sebagai respons terhadap setiap perintah (jika berlaku).NONE
: Model dilarang melakukan panggilan fungsi. Hal ini setara dengan mengirim permintaan tanpa deklarasi fungsi apa pun. Gunakan ini untuk menonaktifkan panggilan fungsi untuk sementara tanpa menghapus definisi alat Anda.
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,
};
Panggilan Fungsi Otomatis (Khusus Python)
Saat menggunakan Python SDK, Anda dapat menyediakan fungsi Python secara langsung sebagai alat. SDK secara otomatis mengonversi fungsi Python menjadi deklarasi, menangani siklus respons dan eksekusi panggilan fungsi untuk Anda. Python SDK kemudian akan otomatis:
- Mendeteksi respons panggilan fungsi dari model.
- Panggil fungsi Python yang sesuai dalam kode Anda.
- Mengirim respons fungsi kembali ke model.
- Menampilkan respons teks akhir model.
Untuk menggunakannya, tentukan fungsi Anda dengan petunjuk jenis dan docstring, lalu teruskan fungsi itu sendiri (bukan deklarasi JSON) sebagai alat:
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
Anda dapat menonaktifkan panggilan fungsi otomatis dengan:
# To disable automatic function calling:
config = types.GenerateContentConfig(
tools=[get_current_temperature],
automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True)
)
Deklarasi skema Fungsi Otomatis
Ekstraksi skema otomatis dari fungsi Python tidak berfungsi dalam semua kasus. Misalnya: tidak menangani kasus saat Anda mendeskripsikan kolom objek kamus bertingkat. API ini dapat mendeskripsikan salah satu jenis berikut:
AllowedType = (int | float | bool | str | list['AllowedType'] | dict[str, AllowedType])
Untuk melihat tampilan skema yang diinferensikan, Anda dapat mengonversinya menggunakan 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())
Penggunaan multi-alat: Menggabungkan Alat Native dengan Panggilan Fungsi
Dengan Gemini 2.0, Anda dapat mengaktifkan beberapa alat yang menggabungkan alat native dengan panggilan fungsi secara bersamaan. Berikut adalah contoh yang mengaktifkan dua alat, Pembumian dengan Google Penelusuran dan eksekusi kode, dalam permintaan menggunakan 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"});
Developer Python dapat mencobanya di notebook Penggunaan Alat API Live.
Model yang Didukung
Model eksperimental tidak disertakan. Anda dapat menemukan kemampuannya di halaman ringkasan model.
Model | Panggilan Fungsi | Panggilan Fungsi Paralel | Panggilan Fungsi Komposisi (Khusus Live API) |
---|---|---|---|
Gemini 2.0 Flash | ✔️ | ✔️ | ✔️ |
Gemini 2.0 Flash-Lite | X | X | X |
Gemini 1.5 Flash | ✔️ | ✔️ | ✔️ |
Gemini 1.5 Pro | ✔️ | ✔️ | ✔️ |
Praktik Terbaik
- Deskripsi Fungsi dan Parameter: Deskripsi harus sangat jelas dan spesifik. Model ini mengandalkan hal ini untuk memilih fungsi yang benar dan memberikan argumen yang sesuai.
- Penamaan: Gunakan nama fungsi deskriptif (tanpa spasi, titik, atau tanda hubung).
- Strong Typing: Gunakan jenis tertentu (bilangan bulat, string, enum) untuk parameter guna mengurangi error. Jika parameter memiliki kumpulan nilai valid yang terbatas, gunakan enum.
- Rekayasa Perintah:
- Berikan konteks: Beri tahu model peran yang harus dilakukannya (misalnya, "Anda adalah asisten cuaca yang membantu.").
- Memberikan petunjuk: Menentukan cara dan waktu menggunakan fungsi (misalnya, "Jangan menebak tanggal; selalu gunakan tanggal di masa mendatang untuk perkiraan").
- Dorong klarifikasi: Minta model untuk mengajukan pertanyaan klarifikasi jika diperlukan.
- Suhu: Gunakan suhu rendah (misalnya, 0) untuk panggilan fungsi yang lebih deterministik dan andal.
- Validasi: Jika panggilan fungsi memiliki konsekuensi yang signifikan (misalnya, melakukan pemesanan), validasi panggilan dengan pengguna sebelum menjalankannya.
- Penanganan Error: Terapkan penanganan error yang andal dalam fungsi Anda untuk menangani input yang tidak terduga atau kegagalan API dengan baik. Menampilkan pesan error informatif yang dapat digunakan model untuk menghasilkan respons yang bermanfaat bagi pengguna.
- Keamanan: Perhatikan keamanan saat memanggil API eksternal. Gunakan mekanisme autentikasi dan otorisasi yang sesuai. Hindari mengekspos data sensitif dalam panggilan fungsi.
- Batas Token: Deskripsi dan parameter fungsi dihitung dalam batas token input Anda. Jika Anda mencapai batas token, pertimbangkan untuk membatasi jumlah fungsi atau panjang deskripsi, bagi tugas yang kompleks menjadi kumpulan fungsi yang lebih kecil dan lebih terfokus.
Catatan dan Batasan
- Hanya subkumpulan skema OpenAPI yang didukung.
- Jenis parameter yang didukung di Python terbatas.
- Panggilan fungsi otomatis hanya merupakan fitur Python SDK.