iT邦幫忙

2025 iThome 鐵人賽

DAY 10
0
生成式 AI

AI 三十天,哎呀每天都很難:OpenAI API 生存指南系列 第 10

Day 10:數學不會算?用 Function Calling 做小計算機

  • 分享至 

  • xImage
  •  

昨天我們用 Function Calling 做了一個「查天氣外掛」,AI 能自己決定呼叫 get_weather
今天來挑戰更實用的功能小計算機
這樣 AI 不只會聊天,還能幫我們做加減乘除。

Step 1:寫一個計算函數

先準備一個函數,能處理四則運算。

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 "不支援的運算"

Step 2:把函數告訴 AI

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"]
            }
        }
    }
]

Step 3:呼叫 API

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)

Step 4:把結果再丟回 AI

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)

接下來是成果:
https://ithelp.ithome.com.tw/upload/images/20250924/20169376Ske4eubdVB.png

一樣calculate部分定義計算邏輯的tools、告訴 AI 這個函數能做什麼、要哪些參數。AI透過解析文字 自動抓出 a=12, b=3, op=divPython,再來呼叫 calculate(12, 3, "div")回傳結果給 AI 讓 AI 輸出更自然的回答

今天我們做了一個 Function Calling 小計算機,AI 可以:解析使用者輸入的數學問題,並且自動決定要帶的參數來呼叫 Python 函數計算

明天的我們要進入新的領域Embeddings 入門,學習怎麼把文字變成「向量」,這是做知識庫 QA 的第一步!


上一篇
# Day 9:Function Calling + 天氣 API 實戰
系列文
AI 三十天,哎呀每天都很難:OpenAI API 生存指南10
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言