今天想一個問題:如果AI 助教自己算錯了呢?LLM有一個很常見的問題叫做計算幻覺(Calculation Hallucination):它可以用無比自信的語氣給出一個錯誤的數字答案。
所以今天我們要做一件事:讓 AI 在確認數字時,不靠記憶,改靠工具。
calculate 與 check_answer)。functionCalls,執行本地安全計算,並將結果送回 Gemini。要讓 Gemini 具備調用外部函數的能力,我們需要透過宣告工具清單(tools 與 functionDeclarations),讓模型知道有哪些外部工具可以使用。
我們在服務層(如 geminiService.js)定義了計算與驗算工具,並使用嚴格的白名單正規表達式確保運算安全,絕對不直接使用危險的 eval():
// 定義工具宣告
const CALCULATOR_TOOLS = [
{
name: "calculate",
description: "執行數學運算,適用於需要精確數字計算的場景。",
parameters: {
type: "OBJECT",
properties: {
expression: { type: "STRING", description: "合法的數學算式,例如 12 / 4 或 (5+3)*2" }
},
required: ["expression"]
}
}
];
// 安全計算函式
function executeCalculatorTool(expression){
// 使用白名單過濾,只允許數字與基本運算子
const safeRegex = /^[\d\s\+\-\*\/\(\)\.\^%]+$/;
if (!safeRegex.test(expression)) {
return { result: "錯誤:包含不合法的字元" };
}
try {
const result = Function(`'use strict'; return (${expression})`)();
return { result, expression };
} catch (error) {
return { result: `計算錯誤: ${error.message}` };
}
}
當使用者發送訊息時,我們將工具設定帶入 tools 中,並透過迴圈處理模型的 functionCalls:
// 支援 Agentic Loop 的主生成邏輯
async function generateTutorReply(contents){
let response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: contents,
config: {
tools: CALCULATOR_TOOLS,
systemInstruction: SYSTEM_INSTRUCTION
}
});
// 偵測模型是否要求呼叫 Function
if (response.functionCalls && response.functionCalls.length > 0) {
const call = response.functionCalls[0];
if (call.name === 'calculate') {
const toolOutput = executeCalculatorTool(call.args.expression);
// 將工具結果以 functionResponse 送回給 Gemini
response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: [
...contents,
{ role: 'model', parts: [{ functionCall: call }] },
{ role: 'function', parts: [{ functionResponse: { name: 'calculate', response: toolOutput } }] }
],
config: { systemInstruction: SYSTEM_INSTRUCTION }
});
}
}
return response.text;
}
在教育現場中,「計算正確性」是建立學生信心的基石。如果 AI 助教連基本的數學運算都會算錯,學生對其產出的信任度就會崩塌。我們導入 Google GenAI SDK 的 Function Calling,將LLM 的「語言理解與引導能力」與傳統程式的「絕對精確計算」結合,消除了計算幻覺。
明天我們將進入 Day 18:【雙模態教學分流機制】導入「理解門」讓 AI 助教學會動態切換角色