到目前為止,我們的 AI 都只能聊天。
但如果要讓它幫我們做事呢?
像是查天氣、算數學、查資料庫……光靠純文字的話 AI 不行,這時候就要用到 Function Calling。
簡單來說:
讓 AI 先決定要不要呼叫某個函數、把參數傳回來、程式去執行、再把結果回給 AI。這樣 AI 就可以動手做事
我們先做一個簡單的 加法計算器
import os
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
# 定義一個函數
def add_numbers(a: int, b: int) -> int:
return a + b
tools = [
{
"type": "function",
"function": {
"name": "add_numbers",
"description": "加總兩個數字",
"parameters": {
"type": "object",
"properties": {
"a": {"type": "integer", "description": "第一個數字"},
"b": {"type": "integer", "description": "第二個數字"},
},
"required": ["a", "b"]
}
}
}
]
# 使用者問 AI
user_input = "幫我算 3 加 5"
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": user_input}],
tools=tools
)
# 解析 AI 的回覆
tool_call = response.choices[0].message.tool_calls[0]
print(tool_call)
# 取出參數並執行
args = tool_call.function.arguments
import json
parsed_args = json.loads(args)
result = add_numbers(parsed_args["a"], parsed_args["b"])
print("計算結果:", result)
我們來看成果:
tools:告訴 AI有哪些函數可以用
tool_call:AI 會回傳 要呼叫哪個函數+要帶哪些參數
程式執行結果:我們自己呼叫 Python 函數,得到真正結果
AI 本身不會真的去算數學,它只會決定呼叫函數。
真正執行的工作,還是我們的程式在做。
為什麼這麼好用
因為只要我們把函數定義清楚,AI 就能幫我們:
自動抓參數、動決定該用哪個工具
未來我們可以用這招做:
查天氣 API、資料庫、家裡 IoT 裝置
今天我們第一次玩 Function Calling,成功做出了一個小小的加法外掛
明天的 Day 9,我們就來實戰用 Function Calling 去查天氣,讓 AI 幫我們當氣象主播!