昨天我們用 Function Calling 做了一個「查天氣外掛」,AI 能自己決定呼叫 get_weather
。
今天來挑戰更實用的功能小計算機。
這樣 AI 不只會聊天,還能幫我們做加減乘除。
先準備一個函數,能處理四則運算。
def calculate(a: float, b: float, op: str) -> float:
if op == "add":
return a + b
elif op == "sub":
return a - b
elif op == "mul":
return a * b
elif op == "div":
return a / b if b != 0 else "除數不能是 0"
else:
return "不支援的運算"
tools = [
{
"type": "function",
"function": {
"name": "calculate",
"description": "執行四則運算",
"parameters": {
"type": "object",
"properties": {
"a": {"type": "number", "description": "第一個數字"},
"b": {"type": "number", "description": "第二個數字"},
"op": {
"type": "string",
"enum": ["add", "sub", "mul", "div"],
"description": "運算方式:add=加,sub=減,mul=乘,div=除"
}
},
"required": ["a", "b", "op"]
}
}
}
]
import os, json
from openai import OpenAI
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
user_input = "幫我算 12 除以 3"
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": user_input}],
tools=tools
)
tool_call = response.choices[0].message.tool_calls[0]
args = json.loads(tool_call.function.arguments)
result = calculate(args["a"], args["b"], args["op"])
print("計算結果:", result)
followup = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": user_input},
{"role": "assistant", "tool_calls": response.choices[0].message.tool_calls},
{"role": "tool", "tool_call_id": tool_call.id, "content": str(result)}
]
)
print("小計算機:", followup.choices[0].message.content)
接下來是成果:
一樣calculate部分定義計算邏輯的tools、告訴 AI 這個函數能做什麼、要哪些參數。AI透過解析文字 自動抓出 a=12, b=3, op=divPython,再來呼叫 calculate(12, 3, "div")回傳結果給 AI 讓 AI 輸出更自然的回答
今天我們做了一個 Function Calling 小計算機,AI 可以:解析使用者輸入的數學問題,並且自動決定要帶的參數來呼叫 Python 函數計算
明天的我們要進入新的領域Embeddings 入門,學習怎麼把文字變成「向量」,這是做知識庫 QA 的第一步!