Function Calling 是 LLM 從「聊天機器人」升級到「能執行任務的 Agent」的關鍵技術。這篇從 Hello World 到並行多 Tool 呼叫,完整教學。
Function Calling 是什麼?
讓 AI 在回答前可以「呼叫你的程式」。例如用戶問「我的訂單到哪了?」,AI 不能猜,但可以呼叫您的 查訂單(訂單號) 函式,拿到結果後再回答。
流程
- 你定義「工具清單」(函式名、參數、回傳格式)
- AI 看用戶提問,判斷該不該呼叫工具
- 如果該呼叫,AI 回傳「我要呼叫 OO,參數 OO」
- 你的程式執行這個函式,把結果回傳給 AI
- AI 用結果產生自然語言回答
Hello World
from google import genai
from google.genai import types
client = genai.Client(api_key="YOUR_KEY")
# 1. 定義工具
def get_weather(city: str) -> str:
# 實際應該呼叫氣象 API
return f"{city}今天 28°C,多雲"
# 2. 把工具給 Gemini
config = types.GenerateContentConfig(
tools=[get_weather]
)
response = client.models.generate_content(
model='gemini-2.5-flash',
contents='高雄今天天氣?',
config=config
)
print(response.text)
實戰:AI 接 ERP 查庫存
def query_inventory(sku: str) -> dict:
"""查詢產品庫存
Args:
sku: 產品料號
Returns:
含庫存數量、預計補貨日期
"""
# 呼叫公司 ERP API
result = requests.get(f'https://erp.company.com/api/sku/{sku}').json()
return {
'stock': result['quantity'],
'restock_date': result['next_restock']
}
def query_price(sku: str, customer_tier: str) -> dict:
"""查詢報價(含客戶分級折扣)"""
# ...
return {'price': 1200, 'discount': '8 折'}
config = types.GenerateContentConfig(
tools=[query_inventory, query_price],
system_instruction="你是專業業務助理,必要時呼叫工具查資料,回答務必準確。"
)
response = client.models.generate_content(
model='gemini-2.5-flash',
contents='SKU-A123 還有貨嗎?金級客戶報價多少?',
config=config
)
並行多 Tool 呼叫
Gemini 2.5 支援同時呼叫多個 Tool。上例的「SKU-A123 還有貨嗎?金級客戶報價多少?」會同時呼叫 query_inventory 和 query_price,比序列呼叫快 50%。
進階:強制 / 禁止呼叫工具
config = types.GenerateContentConfig(
tools=[query_inventory],
tool_config=types.ToolConfig(
function_calling_config=types.FunctionCallingConfig(
mode='ANY' # 強制呼叫工具
# mode='NONE' 禁止呼叫
# mode='AUTO' 預設,AI 自己決定
)
)
)
實戰建議
- 工具名稱與描述要清楚:AI 看不到實作,只看名稱與 docstring
- 參數明確:用 type hint 與 docstring 寫清楚
- 回傳結構化:用 dict 比 string 容易處理
- 錯誤處理:工具出錯要回傳
{'error': '...'},AI 會嘗試處理 - 權限驗證:每個 Tool 都要驗證呼叫者權限
常見錯誤
- 工具描述太模糊 → AI 不會用 / 用錯時機
- 沒做權限檢查 → AI 可能洩漏跨用戶資料
- 工具回傳太大 → AI 處理慢且貴
- 多次 round-trip 沒設上限 → 可能無限迴圈
場景:什麼時候該用 Function Calling?
- 需要查即時資料(庫存、訂單、價格)
- 需要寫入資料(建單、修改、寄信)
- 需要呼叫外部服務(地圖、翻譯、計算)
- 需要複雜邏輯(AI 不擅長算數時呼叫計算器)