Clatter LabsHelp Center

How do I use tool calling in JavaScript?

How-toUpdated

When the reply has tool_calls, run each tool and send the result back with its tool_call_id, then ask again.

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.gateway.clatterlabs.xyz/v1",
  apiKey: process.env.CLATTER_API_KEY,
  defaultHeaders: { "X-Clatter-Account": process.env.CLATTER_ACCOUNT_ID },
});

const tools = [{
  type: "function",
  function: {
    name: "get_weather",
    description: "Get the current weather for a city.",
    parameters: { type: "object", properties: { city: { type: "string" } }, required: ["city"] },
  },
}];
const getWeather = ({ city }) => ({ temp_c: 18, sky: "light rain" });

const msgs = [{ role: "user", content: "What's the weather in Paris?" }];
let r = await client.chat.completions.create({ model: "supercosmos-max", messages: msgs, tools });
let msg = r.choices[0].message;
while (msg.tool_calls?.length) {
  msgs.push(msg);
  for (const call of msg.tool_calls) {
    const out = getWeather(JSON.parse(call.function.arguments));
    msgs.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(out) });
  }
  r = await client.chat.completions.create({ model: "supercosmos-max", messages: msgs, tools });
  msg = r.choices[0].message;
}
console.log(msg.content);

Up to 64 tools per request. tool_choice can be auto, none, required or a specific function.

Every JavaScript example uses the same client (base URL, key and the X-Clatter-Account header); see Set up the JavaScript SDK. Full parameter list: Create a chat completion.

Still need help?#

We usually reply within the first hour, and always within 24 hours. A full support team is with you.

Related articles

Still need help?

Tried the steps above and still stuck? Email us. We usually reply within the first hour, and always within 24 hours. A full support team is with you.

Infrastructure questions, or permanent deletion of your data
infrastructure@clatterlabs.xyz
For deleting your whole account or the data of one service.