Tool Calling v1.0.0+

Give your models the ability to interact with the real world using a clean class-based DSL, automatic execution loops, and built-in safety guards.

Table of contents

  1. Class-Based Tools v1.11.0+
    1. OpenAI Strict Mode
    2. Benefits
    3. Inline Definition with defineTool()
    4. Defining Parameters with Zod
  2. Using Tools in Chat
  3. Tools Work in Streaming Too! v1.2.0+
  4. Tool Choice & Control v1.16.0+
    1. Tool Choice (choice)
    2. Tool Calls (calls)
  5. Concurrent Tool Execution v1.17.0+
    1. Capping Concurrent Calls v1.22.0+
  6. Loop Protection (Loop Guard) 🛡️
    1. Customizing the Limit
    2. Handling the Limit
    3. Stall Guard
  7. Ending With a Tool
  8. Many Tools: Deferred Loading v1.20.0+
  9. Long Tool Loops: Keeping Requests Small
    1. Context Budgets v1.22.0+
    2. Capping What a Loop Spends
    3. Counting Calls a Tool Makes
  10. Tool Execution Policies (Security) v1.5.0+
    1. Inspected Proposals
  11. Advanced Tool Metadata
  12. Error Handling & Flow Control v1.5.1+
    1. Zero-Config Safety (Fatal Errors)
    2. Hook-Based Flow Control (STOP | CONTINUE | RETRY)
    3. AI Self-Correction (Robust Error Handling) Enhanced in v1.16.0
    4. Rescuing Specific Errors (rescueFrom) v1.20.0+
    5. ToolHalt — Early Loop Termination v1.11.0+
  13. Advanced: Raw JSON Schema
  14. Function-Based Tools (Legacy)
  15. Security Considerations
  16. Debugging Tools

NodeLLM simplifies function calling (tool use) by handling the execution loop automatically. You define the tools, and the library invokes them when the model requests it.

npm install @node-llm/core

Looking for a real-world example? Check out the Brand Perception Checker, which uses the SerpTool to perform live Google searches and “read” the results to extract semantic signals.


Class-Based Tools v1.11.0+

The recommended way to define tools is by using the Tool class. This provides auto-generated JSON schemas and full type safety using zod.

import { NodeLLM, Tool } from "@node-llm/core";
import { z } from "zod"; // Zod 4

const weatherSchema = z.object({
  location: z.string().describe("The city and state, e.g. San Francisco, CA"),
  unit: z.enum(["celsius", "fahrenheit"]).default("celsius")
});

// Pass the schema's type so execute() is fully typed.
class WeatherTool extends Tool<z.infer<typeof weatherSchema>> {
  name = "get_weather";
  description = "Get the current weather for a location";

  // Auto-generates JSON Schema
  schema = weatherSchema;

  async execute({ location, unit }: z.infer<typeof weatherSchema>) {
    // Your business logic
    const weather = await fetchWeather(location);
    return { temp: 22, unit, condition: "Sunny" };
  }
}

// Register as a class (instantiated automatically) or instance
const chat = llm.chat().withTool(WeatherTool);
await chat.ask("What is the weather in SF?");

OpenAI Strict Mode

For mission-critical tool definitions on OpenAI, you can enable Strict Mode. This ensures OpenAI’s internal engine guarantees the schema is followed with zero hallucinations.

class WeatherTool extends Tool {
  name = "get_weather";
  strict = true; // Required: enforces additionalProperties: false and required fields
  schema = z.object({ ... });
}

When strict = true is set, NodeLLM automatically translates your Zod schema into a compliant OpenAI strict schema.

Benefits

  • No Boilerplate: No need to write manual JSON schemas.
  • Type Safety: declare the tool as Tool<z.infer<typeof schema>> and execute() is fully typed from your schema. (TypeScript cannot infer it from the schema property alone, so without the type argument the arguments are Record<string, any>.)
  • Self-Documenting: The Zod .describe() calls are automatically pulled into the tool’s description for the LLM.

Inline Definition with defineTool()

For a tool that doesn’t need its own class, defineTool() returns one, with the arguments of execute typed from the schema. Return new ToolHalt(message) from execute to end the turn.

import { defineTool } from "@node-llm/core";
import { z } from "zod"; // Zod 4

const WeatherTool = defineTool({
  name: "get_weather",
  description: "Get the current weather for a location",
  schema: z.object({ location: z.string().describe("The city, e.g. Paris") }),
  execute: async ({ location }) => ({ location, condition: "Sunny" })
});

const chat = llm.chat().withTool(WeatherTool);

Defining Parameters with Zod

NodeLLM turns the schema into JSON Schema for the model, with Zod’s own converter for Zod 4 schemas (Zod 3 schemas still work; see Zod 4 and Zod 3). Most standard Zod types work out of the box:

Zod Type Description
All Fields Required by default.
z.string() Basic text string.
z.number() Number (integer or float).
z.boolean() Boolean flag.
z.enum(["a", "b"]) String restricted to specific values.
z.object({...}) Nested object.
z.array(z.string()) Array of items.
.describe("...") Crucial: Adds a description for the LLM.
.optional() Marks the field as not required.
.default(val) Sets a default value if the LLM doesn’t provide it.

Using Tools in Chat

Use the fluent .withTool() or .withTools() API to register tools for a chat session. By default, tools are appended. You can use the replace option to clear previous tools.

// Append tools
const chat = llm.chat("gpt-5").withTools([WeatherTool, CalculatorTool]);

// Replace all existing tools with a new list
chat.withTools([SearchTool], { replace: true });

const reply = await chat.ask("What is the weather in London?");

Tools Work in Streaming Too! v1.2.0+

Tools now work seamlessly with streaming! The same tool execution happens automatically during streaming:

const chat = llm.chat("gpt-5").withTool(WeatherTool);

// Tool is automatically executed during streaming
for await (const chunk of chat.stream("What's the weather in Paris?")) {
  process.stdout.write(chunk.content || "");
}

See the Streaming documentation for more details.


Tool Choice & Control v1.16.0+

You can precisely control how the model uses tools using choice and calls.

Tool Choice (choice)

Use choice to control whether or how the LLM is allowed to call tools.

  • auto: (Default) The model decides if and which tools to call.
  • none: Prevents the LLM from calling any tools. It will only output text.
  • required: Forces the model to call at least one tool.
  • Specific Tool: Pass a tool name (string) to force the model to use that specific tool.
const chat = llm.chat("gpt-5")
  .withTools([WeatherTool, CalculatorTool], { choice: "required" });

// Or update dynamically
chat.withToolChoice("get_weather");

Claude Opus 5.5, Sonnet 5.5 and Fable 5.1 don’t accept required or a specific tool, and Anthropic rejects the request. With those models, keep auto and say in the instructions which tool to use.

Tool Calls (calls)

Use calls to control if the model can execute multiple tools in a single turn (Parallel Tool Calling).

  • many: (Default) Allows multiple tool calls in one turn.
  • one: Restricts the model to a single tool call per turn. This is useful for simpler models or strictly sequential tasks.

See parallel-tools.mjs for a demo.

chat.withToolCalls("one"); // Force sequential execution

Concurrent Tool Execution v1.17.0+

When a model returns multiple independent tool calls in the same turn, NodeLLM executes them one at a time by default. Enable toolConcurrency to run them in parallel instead, which can meaningfully cut latency for turns with several unrelated tool calls (e.g. looking up weather in three different cities):

const chat = llm.chat("gpt-5")
  .withTools([WeatherTool, CalculatorTool])
  .withToolConcurrency(true);

// If the model calls both tools in one turn, they now run concurrently
const reply = await chat.ask("What's the weather in Paris and what is 12 * 7?");

You can also enable it globally:

import { config } from "@node-llm/core";

config.toolConcurrency = true;

Confirm mode (toolExecution: "confirm") always runs sequentially regardless of this setting, since approval is interactive.

Capping Concurrent Calls v1.22.0+

With true, every call in a turn starts at once. When the tools reach a rate-limited API, or each call is heavy, pass a number instead:

const chat = NodeLLM.chat("gpt-4o").withTools([FetchPage]).withToolConcurrency(4);

Every call still runs and returns its result, four at a time. Results reach the conversation in the order the model asked for them. The same number works for toolConcurrency in chat options, agents and config.


Loop Protection (Loop Guard) 🛡️

To prevent infinite recursion and runaway costs (where a model keeps calling tools without reaching a conclusion), NodeLLM includes a built-in Loop Guard.

By default, NodeLLM throws a ToolCallLimitError if a model asks for a 6th round of tool calls in a single ask() or stream(). A round is one model response with its tool calls, however many calls it makes in parallel, so the default allows 5 rounds. ask() and stream() count the same way.

Customizing the Limit

You can configure this limit globally or override it for a specific request:

// 1. Global Change
const llm = createLLM({ maxToolCalls: 10 });

await chat.ask("Perform a complex deep research task", {
  maxToolCalls: 15
});

Handling the Limit

ToolCallLimitError carries the limit and the usage of every request in that ask, so you can report what the run spent. The calls the model asked for but that weren’t run are answered with an error result, so the chat history stays valid and you can ask again, for example with a higher limit:

import { ToolCallLimitError } from "@node-llm/core";

try {
  await chat.ask("Research and summarise the topic");
} catch (error) {
  if (error instanceof ToolCallLimitError) {
    console.log(`Stopped after ${error.limit} rounds, ${error.usage.total_tokens} tokens`);
    await chat.ask("Finish with what you have", { maxToolCalls: 2 });
  }
}

Stall Guard

maxToolCalls stops a long loop, but a model that is stuck often repeats itself well before the limit: it clicks the same missing button again, or keeps getting the same answer. stallGuard stops such a loop early, before its next request, with StalledError:

const chat = llm.chat("claude-sonnet-5-5", {
  tools: [LookTool, ClickTool],
  stallGuard: {
    repeats: 3, // the same call, with the same arguments, got the same result 3 times
    noProgress: 8 // 8 calls in a row made no progress
  }
});

// Or on an agent
class Tester extends Agent {
  static stallGuard = { repeats: 3, noProgress: 8 };
}

A call made progress when it didn’t fail and its result differs from every earlier result of the same tool in the ask. A call failed when its tool threw, including errors a Tool returns to the model as text. Pass progress(call, result, failed) to decide for yourself, for example when a tool’s result says whether the page changed. Each limit is off unless set, and each ask counts on its own.

StalledError has the reason ("repeated" or "no_progress"), the calls involved, their count and the ask’s usage. Its message says what happened, such as Stalled: the model called click({"label":"Save"}) 3 times with the same result. Every call that ran has its result in the history, so you can ask again:

import { StalledError } from "@node-llm/core";

try {
  await tester.ask("Save the form");
} catch (error) {
  if (error instanceof StalledError) {
    console.log(error.reason, error.message);
    await tester.ask("That isn't working. Try another way, or report what blocks you.");
  }
}

Ending With a Tool

An agent that reports its result through a tool, such as finish or submit_verdict, sometimes ends its turn with plain text instead. endWith names the tool the model must call before its turn ends. When the model ends its turn without calling it, NodeLLM reminds it once and carries on; if it still doesn’t call it, the ask throws EndToolNotCalledError:

class Tester extends Agent {
  static tools = [LookTool, ClickTool, FinishTool];
  static endWith = "finish";
}

// Or on a chat, with a reminder of your own
const chat = llm.chat("claude-sonnet-5-5", {
  tools: [LookTool, FinishTool],
  endWith: { tool: "finish", reminder: "Call finish with your verdict." }
});

Only calls made during the current ask count. A tool that halts the loop counts as called. Pass endWith: null to an ask that doesn’t need the tool, such as a follow-up question:

import { EndToolNotCalledError } from "@node-llm/core";

try {
  await tester.ask("Test the sign-in page");
} catch (error) {
  if (error instanceof EndToolNotCalledError) {
    console.log(`No ${error.tool} after ${error.usage.total_tokens} tokens`);
  }
}

await tester.ask("What did you find on the page?", { endWith: null });

Many Tools: Deferred Loading v1.20.0+

Every tool definition is sent with every request. With dozens of tools, that costs tokens and makes the model choose worse. Mark rarely used tools defer: true:

class IssueRefundTool extends Tool<{ orderId: string }> {
  name = "issue_refund";
  description = "Refund an order to the customer's card";
  schema = z.object({ orderId: z.string() });
  defer = true;

  async execute({ orderId }: { orderId: string }) {
    return refunds.create(orderId);
  }
}

// or: defineTool({ ..., defer: true })
chat.withTools([LookupOrderTool, IssueRefundTool, SendInvoiceTool /* ... */]);

When a chat has deferred tools:

  1. Requests leave out the deferred tools’ definitions and add a built-in tool_search tool, whose description lists the deferred tools by name.
  2. The model calls tool_search with a few words about the task (or select:issue_refund to load by name).
  3. From the next step on, the matching tools’ definitions are sent too, for the rest of the conversation.

Which tools are loaded is read from the conversation history, so it survives saving and restoring a chat. Tools without defer are sent as before, and a chat with no deferred tools is unchanged.

This works the same on every provider.

On Anthropic (Claude 4.5 and later, v1.21.0+), NodeLLM also uses Claude’s own deferred loading. Every tool is sent on every request, deferred ones with defer_loading: true, and a tool_search result is sent as tool_reference blocks that the API expands into full definitions. The tool list then never changes during a conversation, so prompt caching keeps working after the model loads a tool. Search itself still runs in NodeLLM, so results are the same as on other providers.


Long Tool Loops: Keeping Requests Small

Every request in a tool loop resends the conversation so far, including every earlier tool result. When results are large, such as pages, files or search results, an agent that takes many steps pays for the same results again and again. keepToolResults sends only the most recent results in full and replaces older ones with a short placeholder:

const chat = llm.chat("claude-sonnet-5-5", { keepToolResults: 3 });

class PageReader extends Agent {
  static keepToolResults = 3;
}

Older results are left out in blocks: with keepToolResults: 3, between three and six recent results are sent in full, and once there are six, the oldest three are replaced together. The start of the conversation then changes only every three requests, so prompt caching keeps working in between.

Each result keeps its place and tool call id, so the conversation stays valid for every provider, and the model still sees every step it took. The chat’s own history keeps every result in full.

Context Budgets v1.22.0+

keepToolResults counts results. A context budget measures them instead, as shares of the model’s context window, so one huge result or many medium ones can’t push a request past the window:

import { config } from "@node-llm/core";

config.contextBudget = { perResult: 0.25, perRequest: 0.7 };
  • perResult: a tool result longer than this share is cut when it is added, ending with a note that tells the model how much it saw and to ask for a narrower query or the next page. The chat’s history keeps the cut result.
  • perRequest: a request larger than this share leaves out its oldest tool results, each replaced by a one-line note telling the model to call the tool again if it needs it. Only the request changes; chat.history keeps every result.
  • Latest round: this round’s results go out whenever they fit, since the model hasn’t seen them yet. When the round alone is over the share, its oldest results are left out too, with a note to ask for less, so the chat can’t get stuck failing every request.
  • Prompt caching: the cut point moves in steps of about 15% of the budget rather than one result at a time, so the start of the request stays the same for many rounds.
  • Tool search: tool_search results are never left out.

Shares are of the context window the model registry lists for the model. Sizes are estimated at two characters a token, which is how dense JSON and HTML run, so the budget errs on the side of leaving results out. Raise perRequest if your tools return mostly prose.

A chat or agent can set its own, and null turns off a budget set in config:

const chat = llm.chat("gpt-4.1").withContextBudget({ perResult: 0.1, perRequest: 0.5 });
const plain = llm.chat("gpt-4.1").withContextBudget(null);

class ResearchAgent extends Agent {
  static model = "my-local-model";
  static contextBudget = { window: 32_000, perRequest: 0.7 }; // window for a model the registry doesn't know
}

The budget only cuts and counts the text of messages and tool call arguments. Attachments, tool definitions and a long question can still overflow a request.

Capping What a Loop Spends

maxCost stops a tool loop once an ask has spent that many US dollars, before its next request, and throws CostLimitError with the limit and the usage so far. It guards against a tool that returns far more than expected, such as a page with thousands of rows:

const chat = llm.chat("gpt-5.5", { maxCost: 0.5 });

It needs the model’s pricing to know the cost, so it does nothing for models without it.

Counting Calls a Tool Makes

A tool sometimes calls a model itself, such as asking a vision model about a screenshot. Count that call on the chat or agent with countUsage(), so it is part of the ask’s usage, the chat’s totalUsage and maxCost:

const describeScreen = defineTool({
  name: "describe_screen",
  description: "Describe what is on the screen",
  schema: z.object({}),
  execute: async () => {
    const answer = await llm.chat("claude-haiku-5-5").ask("What is on this screen?", {
      images: [await screenshot()]
    });
    agent.countUsage(answer.usage);
    return String(answer);
  }
});

A call counted while no ask is running goes to totalUsage only. With @node-llm/orm, use session.countCall(answer) instead: it also saves the call as a request row of the session.

Tool Execution Policies (Security) v1.5.0+

For sensitive operations, you can control the “autonomy” of the tool execution loop using withToolExecution().

  • auto: (Default) Tools are executed immediately as proposed by the LLM.
  • confirm: Enables Human-in-the-loop. NodeLLM pauses before execution and awaits approval via the onConfirmToolCall hook.
  • dry-run: Proposes the tool call structure but never executes it. Useful for UI previews or verification-only flows.
chat.withToolExecution("confirm").onConfirmToolCall(async (call) => {
  // Audit the call or ask the user
  console.log(`LLM wants to call ${call.function.name}`);
  return true; // Return true to execute, false to cancel
});

Inspected Proposals

In confirm and dry-run modes, the ChatResponseString object returned by .ask() includes a .tool_calls property. This allows you to inspect exactly what the model wanted to do.

const res = await chat.withToolExecution("dry-run").ask("Delete all users");
console.log(res.tool_calls); // [{ id: '...', function: { name: 'delete_users', ... } }]

Advanced Tool Metadata

Some providers support additional metadata in tool definitions, such as Anthropic’s Prompt Caching. You can include these fields in your tool class, and NodeLLM will pass them through.

class HistoryTool extends Tool {
  name = "get_history";
  description = "Get chat history";
  schema = z.object({ limit: z.number().default(10) });

  // Add provider-specific metadata
  cache_control = { type: 'ephemeral' };

  async execute({ limit }: { limit: number }) {
    return [...];
  }

  // Override toLLMTool to include custom metadata if needed
  toLLMTool() {
    const def = super.toLLMTool();
    return {
      ...def,
      cache_control: this.cache_control
    };
  }
}

Error Handling & Flow Control v1.5.1+

NodeLLM handles tool errors intelligently to prevent infinite retry loops through a combination of automatic infrastructure protection and manual flow control.

Zero-Config Safety (Fatal Errors)

By default, the agent loop will immediately stop and throw if it encounters an unrecoverable “fatal” error. This prevents wasting tokens on retries that are guaranteed to fail.

Fatal errors include:

  • Authentication Errors: HTTP 401 or 403 errors from LLM providers or external APIs.
  • Explicit Fatal Errors: Any error thrown using the ToolError class with fatal: true.
import { Tool, ToolError, z } from "@node-llm/core";

class DatabaseTool extends Tool<{ query: string }> {
  name = "db_tool";
  description = "Run a read-only query";
  schema = z.object({ query: z.string() });

  async execute({ query }: { query: string }) {
    if (isMalicious(query)) {
      // Force the agent to stop immediately
      throw new ToolError("Security Violation", "db_tool", true);
    }
  }
}

Hook-Based Flow Control (STOP | CONTINUE | RETRY)

For granular control, you can use the onToolCallError hook to override internal logic. This allows you to differentiate between tools that are “mission-critical” and those that are “optional.”

The hook can return one of three directives:

  • "STOP": Force the agent to crash and bubble the error up to your code.
  • "CONTINUE": Catch the error, log it, and tell the agent to ignore it and move to the next turn.
  • "RETRY" v1.15.0+: Immediately re-execute the same tool call once. If the retry also fails, the error is reported back to the model as usual.
const chat = llm.chat("gpt-5", {
  onToolCallError: (toolCall, error) => {
    // 1. Critical Tool: Stop everything
    if (toolCall.function.name === "process_payment") {
      return "STOP";
    }

    // 2. Optional Tool: Just ignore if it fails
    if (toolCall.function.name === "fetch_avatar") {
      console.warn("Avatar fetch failed, but continuing...");
      return "CONTINUE";
    }

    // 3. Transient Tool: Try executing it again once
    if (toolCall.function.name === "fetch_stock_price") {
      return "RETRY";
    }

    // 4. Default: Let NodeLLM decide (e.g. stop on 401/403)
  }
});

AI Self-Correction (Robust Error Handling) Enhanced in v1.16.0

NodeLLM makes tool calling highly resilient by turning common failures into self-correction signals for the model. Instead of throwing app exceptions, it feeds the error details back to the LLM to allow it to recover.

  • Invalid Arguments: If the model provides arguments that fail Zod validation, the error message is sent back as a tool result. The model can then fix its parameters and try again.
  • Hallucinated Tools: If a model tries to call a tool that isn’t registered, NodeLLM returns an error listing the available tools.
  • Execution Failures: Errors thrown inside your execute() method are caught and returned to the model as descriptive strings.
async execute({ date }: { date: string }) {
  // If you want the model to see the error and try to fix its own parameters,
  // simply return a string or object from your handler.
  if (!isValid(date)) {
    return { error: "Invalid date format. Please use YYYY-MM-DD." };
  }
}

Rescuing Specific Errors (rescueFrom) v1.20.0+

By default, an error thrown in execute() reaches the model as Error executing tool '<name>': <message>. To send something more useful for a known error, register a handler with rescueFrom in the constructor. The handler gets the error and the tool’s arguments, and returns the result the model sees: a string, an object (sent as JSON) or a ToolHalt.

class OrderStatusTool extends Tool<{ id: string }> {
  name = "order_status";
  description = "Look up an order's status";
  schema = z.object({ id: z.string() });

  constructor() {
    super();
    this.rescueFrom(OrderNotFoundError, (_error, { id }) => ({
      error: `No order ${id}. Ask the customer to check the number.`
    }));
    this.rescueFrom(PaymentsDownError, () => this.halt("Payments are down. Try again later."));
  }

  async execute({ id }: { id: string }) {
    return orders.find(id); // throws OrderNotFoundError
  }
}
  • A handler also matches subclasses of its error class.
  • When several handlers match, the one registered last wins, so register general handlers first.
  • Errors that no handler matches keep the default result.

With defineTool, pass the handlers as [ErrorClass, handler] pairs:

const OrderStatus = defineTool({
  name: "order_status",
  description: "Look up an order's status",
  schema: z.object({ id: z.string() }),
  execute: async ({ id }) => orders.find(id),
  rescueFrom: [[OrderNotFoundError, (_error, { id }) => `No order ${id}`]]
});

ToolHalt — Early Loop Termination v1.11.0+

Sometimes a tool needs to stop the agentic loop immediately without making another LLM call. Use this.halt() to return a message directly to the user and break the loop.

import { Tool, z } from "@node-llm/core";

class PaymentTool extends Tool {
  name = "process_payment";
  description = "Process a payment";
  schema = z.object({
    amount: z.number().describe("Amount in dollars"),
    recipient: z.string().describe("Recipient name")
  });

  async execute({ amount, recipient }: { amount: number; recipient: string }) {
    // Halt on large amounts — requires human approval
    if (amount > 10000) {
      return this.halt(`Payment of $${amount} to ${recipient} requires manager approval.`);
    }

    // Halt on invalid amounts
    if (amount <= 0) {
      return this.halt(`Invalid payment amount: $${amount}. Must be positive.`);
    }

    // Normal execution continues
    return { success: true, transactionId: "TXN-123" };
  }
}

When to use halt():

  • Security boundaries: Block dangerous operations (delete, privileged access)
  • Approval workflows: Pause for human review on high-stakes actions
  • Validation failures: Stop immediately on invalid input instead of retrying
  • Resource limits: Halt when quotas or rate limits are exceeded

Difference from throwing errors:

  • throw new ToolError(...) — Stops the loop and bubbles an exception
  • return this.halt(...) — Stops the loop gracefully and returns the message as the final response

Advanced: Raw JSON Schema

If you prefer to define your parameters using standard JSON Schema instead of Zod, you can pass a schema object directly to the schema property in your Tool class. This is useful for migrating existing tools or when you already have schema definitions.

class CustomTool extends Tool {
  name = "custom_lookup";
  description = "Lookup items in a legacy system";

  // Use Raw JSON Schema instead of Zod
  schema = {
    type: "object",
    properties: {
      sku: { type: "string", description: "Product SKU" },
      limit: { type: "integer", minimum: 1, maximum: 100 }
    },
    required: ["sku"]
  };

  async execute({ sku, limit }: { sku: string; limit?: number }) {
    // Arguments are still passed as a single object
    return { status: "found" };
  }
}

Function-Based Tools (Legacy)

For simply wrapping a function without a class, you can define a tool as a plain object with a handler.

const weatherTool = {
  type: "function",
  function: {
    name: "get_weather",
    description: "Get the current weather for a location",
    parameters: {
      type: "object",
      properties: {
        location: { type: "string", description: "City and state" }
      },
      required: ["location"]
    }
  },
  handler: async ({ location }) => {
    return JSON.stringify({ location, temp: 22, unit: "celsius" });
  }
};

chat.withTool(weatherTool);

Security Considerations

Treat arguments passed to your execute method as untrusted user input.

  • Validate: Always validate parameter types and ranges using libraries like zod inside the handler if critical.
  • Sanitize: Sanitize strings before using them in database queries or shell commands.
  • Avoid Eval: Never use eval() on inputs provided by the model.

Debugging Tools

To see exactly what the model is calling and what your tool is returning, enable debug mode:

export NODELLM_DEBUG=true

You will see logs like: [NodeLLM] Tool call: get_weather { location: "Paris" } [NodeLLM] Tool result: { temp: 15 }