Function Calling
LLM bisa "memanggil fungsi" di backend kamu. Model tidak benar-benar execute kode — model menghasilkan JSON yang menunjukkan fungsi mana yang harus dipanggil dengan parameter apa. Kamu yang execute.
Flow
User: "Berapa cuaca di Jakarta hari ini?"
// 1. Model memutuskan perlu panggil fungsi
Model response: {
tool_calls: [{
function: { name: "getWeather", arguments: '{"city": "Jakarta"}' }
}]
}
// 2. Kamu execute fungsi
const weather = await getWeather("Jakarta"); // { temp: 32, condition: "Cerah" }
// 3. Kirim hasil kembali ke model
// 4. Model menjawab dengan data real: "Cuaca di Jakarta 32°C, cerah."
Implementasi
const tools = [{
type: "function",
function: {
name: "getWeather",
description: "Get current weather for a city",
parameters: {
type: "object",
properties: {
city: { type: "string", description: "City name" },
},
required: ["city"],
},
},
}];
const response = await openai.chat.completions.create({
model: "gpt-4o",
messages,
tools,
});
// Check if model wants to call a function
const toolCall = response.choices[0].message.tool_calls?.[0];
if (toolCall) {
const args = JSON.parse(toolCall.function.arguments);
const result = await executeFunction(toolCall.function.name, args);
// Send result back
messages.push(response.choices[0].message);
messages.push({
role: "tool",
tool_call_id: toolCall.id,
content: JSON.stringify(result),
});
// Get final answer
const final = await openai.chat.completions.create({
model: "gpt-4o",
messages,
});
}
Use Cases
- Database queries — "Show me orders from last week" → SQL query
- API calls — "Send email to user" → email API
- Calculations — "Convert 100 USD to IDR" → exchange rate API
- CRUD operations — "Create a new ticket" → ticketing system API