Function Calling & Tool Use — AI Web

Function Calling LLM bisa "memanggil fungsi" di backend kamu. Model tidak benar-benar execute kode — model menghasilkan JSON yang menunjukkan fungsi mana yang h

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

Yang akan kamu pelajari