Tool calling in ten minutes

Let the model request a function, execute that function in your application, and return the result for the final answer.

  1. Define a JSON-schema function in the request.
  2. Inspect the response for a function call.
  3. Run the function in your own trusted application code.
  4. Send the tool output back with the call identifier.
  5. Store the response request ID for support diagnostics.
const host = "magnetapi-org.p.rapidapi.com";
const headers = {
  "Content-Type": "application/json",
  "X-RapidAPI-Key": process.env.RAPIDAPI_KEY,
  "X-RapidAPI-Host": host,
};

const first = await fetch(`https://${host}/v1/responses`, {
  method: "POST",
  headers,
  body: JSON.stringify({
    model: "gpt-5.6",
    input: "What is the weather in Durban?",
    tools: [{
      type: "function",
      name: "get_weather",
      description: "Return current weather for a city.",
      parameters: {
        type: "object",
        properties: { city: { type: "string" } },
        required: ["city"],
        additionalProperties: false
      }
    }]
  })
});
console.log("Request ID:", first.headers.get("X-MagnetAPI-Request-ID"));
const result = await first.json();
const call = result.output.find(item => item.type === "function_call");

// Execute only allow-listed functions. Never evaluate model-provided code.
const weather = await getWeather(JSON.parse(call.arguments).city);
const final = await fetch(`https://${host}/v1/responses`, {
  method: "POST",
  headers,
  body: JSON.stringify({
    model: "gpt-5.6",
    previous_response_id: result.id,
    input: [{ type: "function_call_output", call_id: call.call_id, output: JSON.stringify(weather) }]
  })
});

Safety: Validate tool arguments, allow-list callable functions, set timeouts, and keep filesystem or shell execution inside your own application boundary.

Back to the RapidAPI guide