AI
12/3/2026
12 min read

LLM Function Calling Explained: Build a Safe Tool Loop in Node.js

LLM Function Calling Explained: Build a Safe Tool Loop in Node.js

A customer types "Did my payment PAY-7Q2K9 go through?" into your support chat. A plain large language model (LLM) cannot answer that. It has never seen your database, and if you ask anyway, it will guess. Function calling is the feature that lets the model say "I need to look that up" and hand the lookup to your code.

That handoff is also where most of the risk sits. The model now decides which of your functions to call and with what arguments. This guide explains how function calling works, then builds a small tool loop in Node.js that treats every request from the model the way a good backend treats any request: validated, authorized, logged, and limited.

What LLM Function Calling Is

Function calling, also called tool calling or tool use, lets a model ask your application to run a function. You describe the functions in the request. The model reads the user's message and either answers directly or returns a structured call: the function's name and a JSON object of arguments.

The important detail is who does what. The model never runs your code. Anthropic's tool use documentation describes it plainly: the model determines when to call a tool and returns a structured call that your application runs. Your backend stays in control of what actually happens.

Think of the model as a new support agent who can read the customer's message and fill in a request form, but who has no access to the database. Your code receives the form, checks it, does the work, and hands back the answer. Everything in this guide follows from that picture.

How the Tool Loop Works

OpenAI's function calling guide breaks the flow into 5 steps. The same steps apply to Anthropic, Ollama, and most other providers:

  1. Send the request with tools. Your code sends the user's message plus a list of tools the model may use.
  2. Receive a tool call. The model replies with a call instead of a final answer. In Anthropic's API the response has a stop_reason of tool_use and one or more tool_use blocks.
  3. Run the function. Your code runs the named function with the arguments the model supplied.
  4. Send the result back. Your code makes a second request that includes the original conversation, the model's tool call, and the result.
  5. Receive the final answer, or more calls. The model uses the result to answer, or asks for another tool.

Step 5 is why this is a loop, not a single call. A question like "I was charged twice, refund one of them" may need a status lookup, then a refund request, then a final message. Your code keeps going until the model stops asking for tools.

Two rules from Anthropic's handling guide catch most beginners:

  • Every tool call needs a result. Each tool_use block must get a matching tool_result in the next message, even when the tool failed.
  • Results come straight after the call. You cannot insert other messages between the model's tool call and your tool results.

Defining a Tool: The Description Is the Interface

A tool definition has three parts: a name, a description, and a JSON Schema for the input. OpenAI's format wraps them in a function object and calls the schema parameters. Anthropic calls it input_schema. The ideas are identical.

Anthropic's documentation calls detailed descriptions "by far the most important factor in tool performance" and recommends at least 3 to 4 sentences per tool. A good description answers four questions:

  • What does the tool do? "Look up one payment made to this merchant."
  • When should the model use it, and when not? "Use it only when the customer clearly asks for their money back."
  • What does each parameter mean? "The payment reference, which starts with PAY-."
  • What can it not do? "It cannot see other merchants' payments and cannot change anything."

OpenAI's guide adds a test worth keeping: could an intern use the function correctly with nothing but what you gave the model? If not, the questions the intern would ask belong in the description.

Both providers also recommend designing the tool surface carefully:

  • Use enums for fixed choices. A reason field with 3 allowed values cannot receive a fourth.
  • Do not make the model fill in what you already know. OpenAI's guide gives the example of an order ID your code already has. Pass it in your code instead of asking the model for it.
  • Keep the list short. OpenAI suggests fewer than 20 functions at the start of a turn as a soft limit. Anthropic recommends consolidating related operations into fewer tools.

Tool definitions are not free. OpenAI's guide notes that they are injected into the system message and billed as input tokens on every request. On a dollar-priced API, a long tool list is a cost you pay on every call, whether or not the model uses the tools. Our guide to prompt engineering for backend engineers covers the same discipline for the rest of the prompt.

Build It: A Payment Support Tool Loop in Node.js

We will build the support assistant from the opening example. It has 2 tools: one that reads a payment's status and one that opens a refund request. The domain is a payments dashboard of the kind a Paystack, Flutterwave, or Stripe merchant runs, with amounts stored in kobo, the smallest unit of the naira.

The code uses Node.js with the Anthropic SDK and Zod. Install them:

npm install @anthropic-ai/sdk zod

Step 1: Define, Validate, and Run the Tools

Create the file tools.js:

import { z } from "zod";

// 1. What the model sees: a name, a description, and a JSON Schema.
export const tools = [
  {
    name: "get_payment_status",
    description:
      "Look up one payment made to this merchant. Use it when the customer asks whether a payment went through, failed, or was reversed. Needs the payment reference the customer received, which starts with PAY-. Returns the status, amount, currency, and date. It cannot see other merchants' payments and cannot change anything.",
    input_schema: {
      type: "object",
      properties: {
        reference: { type: "string", description: "Payment reference, for example PAY-7Q2K9" },
      },
      required: ["reference"],
      additionalProperties: false,
    },
  },
  {
    name: "request_refund",
    description:
      "Open a refund request for a successful payment. Use it only when the customer clearly asks for their money back. It does not move money: it creates a request that a staff member must approve. Returns the request ID.",
    input_schema: {
      type: "object",
      properties: {
        reference: { type: "string", description: "Payment reference, for example PAY-7Q2K9" },
        reason: { type: "string", enum: ["duplicate_charge", "not_delivered", "other"] },
      },
      required: ["reference", "reason"],
      additionalProperties: false,
    },
  },
];

// 2. What your code checks. The model's arguments are untrusted input.
const reference = z.string().regex(/^PAY-[A-Z0-9]{5,12}$/, "must look like PAY-7Q2K9");
const schemas = {
  get_payment_status: z.object({ reference }).strict(),
  request_refund: z
    .object({ reference, reason: z.enum(["duplicate_charge", "not_delivered", "other"]) })
    .strict(),
};

// Stand-in for your database. Amounts are stored in kobo.
const payments = new Map([
  ["PAY-7Q2K9", { merchantId: "m_001", status: "success", amount: 1500000, currency: "NGN", paidAt: "2026-11-28" }],
  ["PAY-X81LM", { merchantId: "m_002", status: "failed", amount: 420000, currency: "NGN", paidAt: "2026-11-30" }],
]);

// 3. What actually runs. ctx comes from the logged-in session, never from the model.
const handlers = {
  async get_payment_status({ reference }, ctx) {
    const p = payments.get(reference);
    if (!p || p.merchantId !== ctx.merchantId) {
      return { error: `No payment ${reference} found for this account.` };
    }
    return { reference, status: p.status, amount: p.amount / 100, currency: p.currency, paidAt: p.paidAt };
  },
  async request_refund({ reference, reason }, ctx) {
    const p = payments.get(reference);
    if (!p || p.merchantId !== ctx.merchantId) {
      return { error: `No payment ${reference} found for this account.` };
    }
    if (p.status !== "success") {
      return { error: `Payment ${reference} is ${p.status}, so there is nothing to refund.` };
    }
    // In production: insert a row into refund_requests with status "pending_approval".
    return { refundRequestId: `RFD-${reference.slice(4)}`, reason, status: "pending_approval" };
  },
};

export async function runTool(name, input, ctx) {
  const handler = handlers[name];
  if (!handler) return { isError: true, content: `Unknown tool: ${name}` };

  const parsed = schemas[name].safeParse(input);
  if (!parsed.success) {
    const problems = parsed.error.issues.map((i) => `${i.path.join(".") || "input"}: ${i.message}`);
    return { isError: true, content: `Invalid input. ${problems.join("; ")}` };
  }

  try {
    const result = await handler(parsed.data, ctx);
    if (result.error) return { isError: true, content: result.error };
    return { isError: false, content: JSON.stringify(result) };
  } catch (err) {
    console.error("tool crashed", name, err);
    return { isError: true, content: "The tool failed. Tell the customer to try again later." };
  }
}

The file has three layers, and each one exists for a different reader.

  • tools is for the model. Names, descriptions, and JSON Schemas. This array goes into every request.
  • schemas is for your code. The same rules again, written in Zod, because the arguments come from a model and must be treated as untrusted input. The .strict() call rejects any field you did not define.
  • handlers do the work. Each one receives the validated arguments and a ctx object built from the logged-in session.

The ctx object is the most important line in the file. The merchant ID comes from your authentication layer, not from the model. Notice that neither tool has a merchantId parameter. If a user writes "check PAY-X81LM for merchant m_002", the model cannot pass that merchant ID, and the handler only searches the current merchant's payments. We tested this: an argument object with an extra merchantId field is rejected by the strict Zod schema with "Unrecognized key(s) in object: 'merchantId'".

runTool() never throws. An unknown tool name, invalid arguments, a business-rule failure, and a crash all come back as an object with isError: true and a message the model can read. That matters because the loop must send a result for every call, including the failed ones.

The refund tool does not move money. It creates a request with the status pending_approval. Any action that cannot be undone, such as a refund, a transfer, or a deleted account, should wait for a person to approve it. The model can prepare the action. It should not complete it.

Step 2: Run the Loop

Create the file tool-loop.js:

import Anthropic from "@anthropic-ai/sdk";
import { tools, runTool } from "./tools.js";

const client = new Anthropic(); // reads ANTHROPIC_API_KEY
const MODEL = process.env.LLM_MODEL ?? "claude-haiku-5-5";
const MAX_STEPS = 5;

const SYSTEM = `You are the support assistant inside a payments dashboard.
Use the tools to check facts before you answer. Never guess a payment status.
If a tool returns an error, explain the problem to the customer in one sentence.`;

export async function answer(userMessage, ctx) {
  const messages = [{ role: "user", content: userMessage }];

  for (let step = 0; step < MAX_STEPS; step++) {
    const response = await client.messages.create({
      model: MODEL,
      max_tokens: 1024,
      system: SYSTEM,
      tools,
      messages,
    });

    if (response.stop_reason !== "tool_use") {
      return response.content.filter((b) => b.type === "text").map((b) => b.text).join("\n");
    }

    messages.push({ role: "assistant", content: response.content });

    const results = [];
    for (const block of response.content) {
      if (block.type !== "tool_use") continue;
      const { isError, content } = await runTool(block.name, block.input, ctx);
      console.log(JSON.stringify({ userId: ctx.userId, tool: block.name, input: block.input, isError }));
      results.push({ type: "tool_result", tool_use_id: block.id, content, is_error: isError });
    }
    messages.push({ role: "user", content: results });
  }

  return "We could not finish this request automatically. A support agent will follow up.";
}

answer() follows the 5 steps from earlier. It sends the conversation with the tools, and if the response's stop_reason is not tool_use, it returns the text as the final answer. Otherwise it appends the model's response unchanged as an assistant message, runs every tool_use block, and sends all the results back together in one user message, each matched to its call by tool_use_id.

Three details make it safe to run behind a real endpoint:

  • MAX_STEPS caps the loop. A confused model can keep calling tools. After 5 rounds the function stops and returns a handoff message instead of spending money forever.
  • is_error tells the model a call failed. Anthropic's API accepts is_error: true on a tool_result. The model reads the message and can correct its arguments or explain the problem to the customer.
  • Every call is logged with the user ID, the tool, the arguments, and the outcome. When an answer looks wrong in production, this log is the first thing you read.

The model ID lives in an environment variable so you can change it without a code change. We ran this loop on 3 December 2026 against a local mock of the Messages API that replayed a realistic conversation: a malformed reference, two parallel lookups, and a refund request. The output shows each step:

{"userId":"u_9","tool":"get_payment_status","input":{"reference":"7Q2K9"},"isError":true}
{"userId":"u_9","tool":"get_payment_status","input":{"reference":"PAY-7Q2K9"},"isError":false}
{"userId":"u_9","tool":"get_payment_status","input":{"reference":"PAY-X81LM"},"isError":true}
{"userId":"u_9","tool":"request_refund","input":{"reference":"PAY-7Q2K9","reason":"duplicate_charge"},"isError":false}

The first call fails validation because the reference is missing its PAY- prefix, and the model receives "Invalid input. reference: must look like PAY-7Q2K9". The third call fails because PAY-X81LM belongs to a different merchant. Neither failure crashes the request. Both become information the model can act on.

The same loop works with other providers. OpenAI's Responses API returns function_call items and expects function_call_output items back, matched by call_id. Ollama returns tool_calls and expects messages with the tool role. Only the message shapes change. The validation, authorization, and step limit stay exactly where they are.

Five Rules for Production Tool Calling

Function calling turns an LLM from something that writes text into something that takes actions in your system. OWASP lists this risk as Excessive Agency in its Top 10 for LLM applications. These rules come from its mitigations and from both providers' documentation.

1. Give the Model the Smallest Set of Tools

OWASP's first two mitigations are to offer only the tools a feature needs and to limit what each tool can do. A support assistant that reads payments does not need a tool that can update them. Avoid open-ended tools such as "run this SQL" or "fetch this URL". Build narrow tools that do one job.

2. Run Every Tool With the User's Permissions

OWASP recommends running tool actions in the context of the user who made the request, with the minimum privileges needed. In practice, the database user behind a read-only tool should only have read access, and every query should be scoped to the logged-in account through ctx, never through an argument the model chose.

3. Validate Arguments Even With Strict Mode

OpenAI recommends always enabling strict mode, which makes function calls match the schema. Anthropic offers the same guarantee with strict: true on a tool definition. Turn it on when your provider supports it. Then validate anyway: a schema checks that a reference is a string, not that it belongs to this customer, and a fallback or local model may not support strict mode at all.

4. Require a Person for Actions You Cannot Undo

OWASP's guidance includes human approval for high-impact actions. Let the model draft the refund, the email, or the account change. Store it as pending, and let a staff member or the customer confirm it. This one rule turns most bad tool calls from incidents into rejected requests.

5. Treat Tool Results as Untrusted Too

Tool results often carry text you do not control: a web page, an email, a customer's note on an order. Anthropic warns that an attacker who controls that text can embed instructions that try to redirect the model, an attack called indirect prompt injection. Keep that content inside the tool result, not in the system prompt, and rely on rules 1 to 4 so that a hijacked model still cannot do much damage.

When a tool calls a third-party API, it inherits that API's limits too. Our guide to handling LLM API rate limits and retries in Node.js applies to the model call and to the services your tools call. When a tool loop misbehaves in production, the request traces in our guide to debugging AI backend systems show you which step went wrong.

Function Calling on a Budget

Every round of the loop is a full request, and each one resends the whole conversation, the tool definitions, and the earlier results. A question that needs 3 tool calls in a row costs 4 requests, not 1. On an API billed in dollars, that adds up fast for a team paying from a naira, shilling, or cedi budget.

Three habits keep the bill under control:

  • Return only what the model needs. Anthropic recommends tool responses that carry only high-signal fields. Our get_payment_status returns 5 fields, not the whole database row.
  • Combine steps the model always takes together. OpenAI's guide suggests merging functions that are always called in sequence into one.
  • Build and test on a local model. Ollama supports tool calling with the same name, description, and JSON Schema shape, so you can develop the loop on your own machine with no per-token cost and switch to a hosted model when you deploy. Expect smaller local models to choose tools less reliably, which is one more reason to keep the validation layer.

Where to Go From Here

A tool loop that keeps choosing its next step is the core of an AI agent. Once you are comfortable with the loop above, our guide to building AI agents with LangChain, CrewAI, and AutoGen shows how agent frameworks package the same pattern with memory and planning.

If you want to work through function calling, agent loops, and human-in-the-loop patterns in order, with hands-on tasks, the AI Engineering course covers function calling in its foundations chapter and agent loops, tool integration, and error handling in its AI Agent Fundamentals chapter.

Summary

LLM function calling lets a model ask your backend to run a function. The model returns a name and arguments, your code runs the function, and you send the result back until the model gives a final answer. The model never touches your database directly.

Write tool descriptions like documentation for a new hire, keep the tool list short, and remember that every definition is billed as input on every request. In your code, validate every argument, take identity from the session instead of the model, return a result for every call even when it fails, cap the number of steps, log every call, and make a person approve anything that cannot be undone.

Frequently Asked Questions

What Is the Difference Between Function Calling and Tool Use?

Nothing important. They are two names for the same feature. OpenAI's documentation calls it function calling and notes it is also known as tool calling, and Anthropic's documentation calls it tool use and notes it is also called function calling. In both cases the model returns a structured request to run a function, and your code decides whether to run it.

Does the LLM Run the Function Itself?

No. For functions you define, the model only returns the function's name and the arguments it wants to pass. Your application runs the code, then sends the result back in a second request. Some providers also offer server tools, such as web search, that run on the provider's own infrastructure, but your own business functions always run in your backend.

Do Tool Definitions Cost Tokens?

Yes. OpenAI's function calling guide says function definitions are injected into the system message, count against the context limit, and are billed as input tokens. Anthropic builds a special system prompt from your tool definitions in the same way. Every tool you add makes every request in that conversation longer, so keep the list short and the descriptions precise.

How Many Tools Should I Give the Model?

As few as the feature needs. OpenAI's guide suggests aiming for fewer than 20 functions available at the start of a turn and calls that a soft suggestion. Anthropic recommends consolidating related operations into fewer tools. Fewer tools mean less confusion about which one to pick and fewer input tokens on every call.

Can I Use Function Calling With a Local Model?

Yes. Ollama supports tool calling through its chat API with the same name, description, and JSON Schema shape, so you can build and test a tool loop on your own machine with no per-token bill. Smaller local models make more mistakes when picking tools and filling arguments, which makes the validation step in your code even more important.

Is Strict Mode Enough to Trust the Model's Arguments?

No. Strict mode in OpenAI's API and strict tool use in Anthropic's API make the arguments match your JSON Schema. A schema checks shape, not meaning. It cannot tell whether the payment reference belongs to the logged-in customer or whether a refund is allowed. Your handler still has to check identity, ownership, and business rules before it does anything.

Tags

Enjoyed this article?

Subscribe to our newsletter for more backend engineering insights and tutorials.