การเรียกใช้ฟังก์ชันช่วยให้คุณเชื่อมต่อโมเดลกับเครื่องมือและ API ภายนอกได้ แทนที่จะสร้างคำตอบที่เป็นข้อความ โมเดลจะเข้าใจว่าควรเรียกใช้ฟังก์ชันใดและระบุพารามิเตอร์ที่จำเป็นเพื่อดำเนินการในชีวิตจริง ซึ่งช่วยให้โมเดลทำหน้าที่เป็นสะพานเชื่อมระหว่างภาษาธรรมชาติกับการกระทำและข้อมูลในชีวิตจริง การเรียกใช้ฟังก์ชันมีกรณีการใช้งานหลัก 3 กรณีดังนี้
- เพิ่มความรู้: เข้าถึงข้อมูลจากแหล่งที่มาภายนอก เช่น ฐานข้อมูล, API และฐานความรู้
- ขยายความสามารถ: ใช้เครื่องมือภายนอกเพื่อดำเนินการคํานวณและขยายข้อจํากัดของโมเดล เช่น ใช้เครื่องคิดเลขหรือสร้างแผนภูมิ
- ดำเนินการ: โต้ตอบกับระบบภายนอกโดยใช้ API เช่น กำหนดเวลาการนัดหมาย สร้างใบแจ้งหนี้ ส่งอีเมล หรือควบคุมอุปกรณ์สมาร์ทโฮม
วิธีการทำงานของการเรียกฟังก์ชัน
การเรียกใช้ฟังก์ชันเกี่ยวข้องกับการโต้ตอบที่มีโครงสร้างระหว่างแอปพลิเคชัน โมเดล และฟังก์ชันภายนอก รายละเอียดของกระบวนการมีดังนี้
- กำหนดประกาศฟังก์ชัน: กำหนดประกาศฟังก์ชันในโค้ดแอปพลิเคชัน การประกาศฟังก์ชันจะอธิบายชื่อ พารามิเตอร์ และวัตถุประสงค์ของฟังก์ชันต่อโมเดล
- เรียก 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 ซึ่งระบุวิธีเรียกใช้ฟังก์ชันที่ประกาศอย่างน้อย 1 รายการเพื่อตอบคำถามของผู้ใช้
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
อย่างน้อย 1 รายการ คุณกําหนดฟังก์ชันโดยใช้ JSON โดยเฉพาะกับชุดย่อยที่เลือกของรูปแบบสคีมา OpenAPI การประกาศฟังก์ชันเดียวอาจมีพารามิเตอร์ต่อไปนี้
name
(สตริง): ชื่อที่ไม่ซ้ำสำหรับฟังก์ชัน (get_weather_forecast
,send_email
) ใช้ชื่อที่สื่อความหมายโดยไม่มีเว้นวรรคหรืออักขระพิเศษ (ใช้ขีดล่างหรือตัวพิมพ์ใหญ่ตามด้วยตัวพิมพ์เล็ก)description
(สตริง): คำอธิบายวัตถุประสงค์และความสามารถของฟังก์ชันอย่างชัดเจนและละเอียด ซึ่งข้อมูลนี้ช่วยให้โมเดลเข้าใจว่าควรใช้ฟังก์ชันเมื่อใด ระบุให้ชัดเจนและยกตัวอย่างหากเป็นประโยชน์ ("ค้นหาโรงภาพยนตร์ตามสถานที่ตั้งและชื่อภาพยนตร์ (ไม่บังคับ) ที่ฉายอยู่ในโรงภาพยนตร์")parameters
(ออบเจ็กต์): กําหนดพารามิเตอร์อินพุตที่ฟังก์ชันคาดหวังtype
(สตริง): ระบุประเภทข้อมูลโดยรวม เช่นobject
properties
(ออบเจ็กต์): แสดงรายการพารามิเตอร์แต่ละรายการ โดยแต่ละรายการจะมีข้อมูลต่อไปนี้type
(สตริง): ประเภทข้อมูลของพารามิเตอร์ เช่นstring
,integer
,boolean, array
description
(สตริง): คำอธิบายวัตถุประสงค์และรูปแบบของพารามิเตอร์ ระบุตัวอย่างและข้อจำกัด ("เมืองและรัฐ เช่น "ซานฟรานซิสโก รัฐแคลิฟอร์เนีย" หรือรหัสไปรษณีย์ เช่น '95616'.")enum
(อาร์เรย์ ไม่บังคับ): หากค่าพารามิเตอร์มาจากชุดค่าคงที่ ให้ใช้ "enum" เพื่อแสดงค่าที่อนุญาตแทนการอธิบายไว้ในคำอธิบาย ซึ่งจะช่วยเพิ่มความแม่นยำ ("enum": ["daylight", "cool", "warm"])
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 รองรับฟีเจอร์ที่เรียกว่าการเรียกใช้ฟังก์ชันอัตโนมัติ ซึ่งจะแปลงฟังก์ชัน Python เป็นการประกาศ จัดการการเรียกใช้ฟังก์ชัน และวงจรการตอบสนองให้คุณ ต่อไปนี้เป็นตัวอย่างกรณีการใช้งานของ 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!
การเรียกใช้ฟังก์ชันแบบคอมโพสิชัน
Gemini 2.0 รองรับการเรียกใช้ฟังก์ชันแบบคอมโพสิชัน ซึ่งหมายความว่าโมเดลสามารถต่อเชื่อมการเรียกใช้ฟังก์ชันหลายรายการเข้าด้วยกันได้ เช่น หากต้องการตอบ "รับอุณหภูมิ ณ ตําแหน่งปัจจุบันของฉัน" Gemini API อาจเรียกใช้ทั้งฟังก์ชัน 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 เท่านั้น)
เมื่อใช้ Python SDK คุณสามารถระบุฟังก์ชัน Python เป็นเครื่องมือได้โดยตรง SDK จะแปลงฟังก์ชัน Python เป็นการประกาศโดยอัตโนมัติ รวมถึงจัดการการเรียกใช้ฟังก์ชันและวงจรการตอบสนองให้คุณ จากนั้น Python SDK จะดำเนินการต่อไปนี้โดยอัตโนมัติ
- ตรวจหาการตอบกลับการเรียกใช้ฟังก์ชันจากโมเดล
- เรียกใช้ฟังก์ชัน Python ที่เกี่ยวข้องในโค้ด
- ส่งการตอบสนองของฟังก์ชันกลับไปยังโมเดล
- แสดงคำตอบที่เป็นข้อความสุดท้ายของโมเดล
หากต้องการใช้ โปรดกำหนดฟังก์ชันด้วยคำบอกใบ้ประเภทและสตริงเอกสาร จากนั้นส่งฟังก์ชันนั้นเอง (ไม่ใช่การประกาศ 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)
)
การประกาศสคีมาฟังก์ชันอัตโนมัติ
การสกัดสคีมาอัตโนมัติจากฟังก์ชัน Python อาจไม่ทำงานในบางกรณี เช่น จะไม่จัดการกรณีที่คุณอธิบายช่องของออบเจ็กต์พจนานุกรมที่ฝังอยู่ 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())
การใช้เครื่องมือหลายอย่าง: รวมเครื่องมือเนทีฟกับการเรียกใช้ฟังก์ชัน
Gemini 2.0 ช่วยให้คุณเปิดใช้เครื่องมือหลายรายการที่รวมเครื่องมือแบบเนทีฟกับการเรียกใช้ฟังก์ชันพร้อมกันได้ ต่อไปนี้คือตัวอย่างที่เปิดใช้เครื่องมือ 2 อย่าง ได้แก่ การกําหนดค่าโดยใช้ Google Search และการเรียกใช้โค้ดในคําขอโดยใช้ 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"});
นักพัฒนาซอฟต์แวร์ Python สามารถลองใช้ฟีเจอร์นี้ได้ในโน้ตบุ๊กการใช้เครื่องมือ Live API
โมเดลที่รองรับ
โดยไม่รวมโมเดลทดลอง คุณดูความสามารถของโมเดลได้ในหน้าภาพรวมของโมเดล
รุ่น | การเรียกใช้ฟังก์ชัน | การเรียกใช้ฟังก์ชันพร้อมกัน | การเรียกใช้ฟังก์ชันการคอมโพสิชัน (Live API เท่านั้น) |
---|---|---|---|
Gemini 2.0 Flash | ✔️ | ✔️ | ✔️ |
Gemini 2.0 Flash-Lite | X | X | X |
Gemini 1.5 Flash | ✔️ | ✔️ | ✔️ |
Gemini 1.5 Pro | ✔️ | ✔️ | ✔️ |
แนวทางปฏิบัติแนะนำ
- คำอธิบายฟังก์ชันและพารามิเตอร์: เขียนคำอธิบายให้ชัดเจนและเฉพาะเจาะจง โมเดลใช้ข้อมูลเหล่านี้เพื่อเลือกฟังก์ชันที่ถูกต้องและระบุอาร์กิวเมนต์ที่เหมาะสม
- การตั้งชื่อ: ใช้ชื่อฟังก์ชันที่สื่อความหมาย (ไม่เว้นวรรค ใส่จุด หรือขีดกลาง)
- การเขียนโปรแกรมแบบ Strong Typing: ใช้ประเภทที่เฉพาะเจาะจง (จำนวนเต็ม สตริง อาร์เรย์แบบจำกัด) สำหรับพารามิเตอร์เพื่อลดข้อผิดพลาด หากพารามิเตอร์มีค่าที่ถูกต้องแบบจํากัด ให้ใช้ enum
- Prompt Engineering:
- ระบุบริบท: บอกให้โมเดลทราบถึงบทบาท (เช่น "คุณเป็นผู้ช่วยด้านสภาพอากาศที่มีประโยชน์")
- ระบุวิธีการ: ระบุวิธีและเวลาที่ควรใช้ฟังก์ชัน (เช่น "อย่าเดาวันที่ ให้ใช้วันที่ในอนาคตสำหรับการคาดการณ์เสมอ")
- ส่งเสริมให้ชี้แจง: บอกให้นายแบบ/นางแบบถามคำถามเพื่อชี้แจงหากจำเป็น
- อุณหภูมิ: ใช้อุณหภูมิต่ำ (เช่น 0) เพื่อให้การเรียกใช้ฟังก์ชันมีความแน่นอนและเชื่อถือได้มากขึ้น
- การตรวจสอบ: หากการเรียกฟังก์ชันมีผลที่ตามมาอย่างมีนัยสําคัญ (เช่น การวางคําสั่งซื้อ) ให้ตรวจสอบการเรียกกับผู้ใช้ก่อนดำเนินการ
- การจัดการข้อผิดพลาด: ใช้การจัดการข้อผิดพลาดที่มีประสิทธิภาพในฟังก์ชันเพื่อจัดการกับอินพุตที่ไม่คาดคิดหรือข้อผิดพลาดของ API อย่างราบรื่น แสดงข้อความแสดงข้อผิดพลาดที่เป็นประโยชน์ซึ่งโมเดลสามารถใช้เพื่อสร้างคำตอบที่เป็นประโยชน์ให้แก่ผู้ใช้
- ความปลอดภัย: โปรดคำนึงถึงความปลอดภัยเมื่อเรียกใช้ API ภายนอก ใช้กลไกการตรวจสอบสิทธิ์และการให้สิทธิ์ที่เหมาะสม หลีกเลี่ยงการแสดงข้อมูลที่ละเอียดอ่อนในการเรียกใช้ฟังก์ชัน
- ขีดจํากัดของโทเค็น: คําอธิบายและพารามิเตอร์ของฟังก์ชันจะนับรวมในขีดจํากัดของโทเค็นอินพุต หากถึงขีดจํากัดของโทเค็น ให้ลองจํากัดจํานวนฟังก์ชันหรือความยาวของคําอธิบาย แบ่งงานที่ซับซ้อนออกเป็นชุดฟังก์ชันที่เล็กลงและมุ่งเน้นมากขึ้น
หมายเหตุและข้อจํากัด
- ระบบรองรับเฉพาะชุดย่อยของสคีมา OpenAPI เท่านั้น
- พารามิเตอร์ประเภทที่รองรับใน Python มีจํากัด
- การเรียกใช้ฟังก์ชันอัตโนมัติเป็นฟีเจอร์ของ Python SDK เท่านั้น