TopFlow
LearnBuildSecurity
Integration Node

Tool Node

Define custom functions that AI models can call dynamically. Tool nodes enable function calling, structured interactions with external systems, and advanced AI agent capabilities.

Overview

The Tool Node is a powerful component that defines custom functions AI models can invoke during execution. Instead of returning unstructured text, AI models can call your tools to perform specific actions—query databases, call APIs, perform calculations, or interact with external services.

Tool nodes work with AI providers that support function calling:

  • OpenAI: GPT-4, GPT-4o, GPT-4 Turbo (function calling)
  • Anthropic: Claude 3.5 Sonnet, Claude 3 Opus (tool use)
  • Google: Gemini 1.5 Pro, Gemini 1.5 Flash (function calling)
  • Groq: Models with function calling support
Use Cases
  • Query external APIs - Fetch real-time data (weather, stock prices, news)
  • Database operations - Search, retrieve, or analyze data from databases
  • Calculations - Perform complex computations or financial projections
  • Business logic - Execute conditional workflows and decision-making processes
  • Third-party integrations - Connect to external services and platforms
Key Concept

You define what the function does and how to call it. The AI model decides when to call it based on the user's prompt and conversation context.

Configuration

Required Parameters

name

  • Type: string
  • Required: Yes
  • Description: Function name the AI will call. Must be a valid JavaScript identifier (alphanumeric + underscores, no spaces)
  • Example: "get_weather", "searchDatabase"

description

  • Type: string
  • Required: Yes
  • Description: Clear explanation of what the function does. The AI uses this to decide when to call it. Be specific and include when to use it
  • Example: "Get current weather for a city. Use when user asks about weather conditions."
Optional Parameters

parameters

  • Type: Record<string, any>
  • Required: No
  • Description: JSON Schema defining function parameters. Follows OpenAI function calling format. Defines parameter types, descriptions, required fields, and validation rules

code

  • Type: string
  • Required: No
  • Description: JavaScript function body to execute when AI calls this tool. Has access to parameters passed by the AI. Can be async. Must return a value (string, object, or JSON)
Configuration Tips
Clear descriptions - Be explicit about what the function does, when to use it, and what it doesn't do
Descriptive parameters - Use meaningful parameter names like city, temperature_unit instead of arg1, param
Keep it focused - Each tool should do one thing well. Create multiple tools instead of one "do_everything" function
Environment variables - Use process.env for API keys and secrets, never hardcode them

Node Data Interface

TypeScript Definition
export type ToolNodeData = {
  // Configuration
  name: string                      // Function name (required)
  description: string               // What the function does (required)
  parameters?: Record<string, any>  // JSON Schema for parameters
  code?: string                     // JavaScript function body

  // Execution state (managed by system)
  status?: "idle" | "running" | "completed" | "error"
  output?: any
  error?: string
}

Usage Examples

Example 1: Get Current Weather
Fetch weather data from an external API

Tool Configuration

  • Name: get_weather
  • Description: "Get the current weather for a specific city. Use when the user asks about weather conditions."

Parameters Schema

{
  "type": "object",
  "properties": {
    "city": {
      "type": "string",
      "description": "The city name (e.g., 'San Francisco', 'London')"
    },
    "unit": {
      "type": "string",
      "enum": ["celsius", "fahrenheit"],
      "description": "Temperature unit"
    }
  },
  "required": ["city"]
}

Function Code

async function get_weather({ city, unit = "celsius" }) {
  const apiKey = process.env.WEATHER_API_KEY
  const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=${
    unit === "celsius" ? "metric" : "imperial"
  }&appid=${apiKey}`

  const response = await fetch(url)
  const data = await response.json()

  return {
    city: data.name,
    temperature: data.main.temp,
    conditions: data.weather[0].description,
    unit: unit
  }
}
Result: When a user asks "What's the weather in Tokyo?", the AI calls get_weather({ city: "Tokyo", unit: "celsius" }) and uses the result to respond: "The current weather in Tokyo is 22°C with clear skies."
Example 2: Search Company Database
Query an internal database for employee or project information

Tool Configuration

  • Name: search_database
  • Description: "Search the company database for employees or projects. Use when user asks about team members or project details."

Parameters Schema

{
  "type": "object",
  "properties": {
    "query": {
      "type": "string",
      "description": "Search query (name, department, or project)"
    },
    "type": {
      "type": "string",
      "enum": ["employee", "project"],
      "description": "Type of search"
    }
  },
  "required": ["query", "type"]
}

Function Code

async function search_database({ query, type }) {
  const db = await getDatabase()

  if (type === "employee") {
    const results = await db.employees.find({
      $or: [
        { name: { $regex: query, $options: "i" } },
        { department: { $regex: query, $options: "i" } }
      ]
    }).limit(5)

    return results.map(emp => ({
      name: emp.name,
      department: emp.department,
      role: emp.role
    }))
  } else {
    const results = await db.projects.find({
      name: { $regex: query, $options: "i" }
    }).limit(5)

    return results.map(proj => ({
      name: proj.name,
      status: proj.status,
      team_size: proj.team.length
    }))
  }
}
Result: Returns structured data about employees or projects that the AI can summarize in natural language
Example 3: Calculate Investment Returns
Pure computation tool without external API calls

Tool Configuration

  • Name: calculate_returns
  • Description: "Calculate compound investment returns over time. Use when user asks about investment growth or financial projections."

Function Code

function calculate_returns({ principal, rate, years }) {
  if (principal <= 0 || rate < 0 || years <= 0) {
    return { error: "Invalid input: all values must be positive numbers" }
  }

  const finalAmount = principal * Math.pow(1 + rate, years)
  const totalGain = finalAmount - principal
  const percentageGain = (totalGain / principal) * 100

  return {
    initial: principal,
    final: finalAmount.toFixed(2),
    gain: totalGain.toFixed(2),
    percentage: percentageGain.toFixed(2),
    years: years
  }
}
Result: Returns calculated investment data that the AI uses to explain financial projections in plain language

Function Calling Flow

Step-by-Step Execution
  1. 1
    Tool Definition - You configure the Tool node with name, description, parameters, and code
  2. 2
    Registration - Tool definition is passed to the AI model along with the user's prompt
  3. 3
    AI Decision - AI analyzes the prompt and decides whether to call your tool
  4. 4
    Function Call - If tool is needed, AI generates function call with appropriate arguments
  5. 5
    Code Execution - Your tool's JavaScript code runs with AI-provided arguments
  6. 6
    Result Return - Function result is fed back to the AI model
  7. 7
    Final Response - AI uses tool result to generate natural language response to user
Multi-Tool Workflows

You can provide multiple Tool nodes to a single AI model. The AI will choose which tool(s) to call based on the user's request.

Example Multi-Tool Scenario

User: "What's the weather in New York and how should I invest $10,000 at 5% for 10 years?"

The AI will call both tools:

  • 1. get_weather({ city: "New York" })
  • 2. calculate_returns({ principal: 10000, rate: 0.05, years: 10 })

Then formulates a response using both results.

Validation Rules

Errors (Block Execution)
  • ❌
    Missing Tool Name

    Tool node must have a valid function name

  • ❌
    Missing Description

    Tool node must have a description to help AI decide when to use it

  • ❌
    Invalid Function Name

    Function name must be a valid JavaScript identifier (alphanumeric + underscores only)

  • ❌
    Invalid Parameters Schema

    If provided, parameters must be valid JSON Schema format

Warnings
  • ⚠️
    No Function Code

    Tool has no implementation. AI can call it but it won't execute anything

  • ⚠️
    Vague Description

    Description is too short or unclear. AI may not know when to use this tool

Best Practices

Do
  • ✓
    Write clear, specific descriptions with use cases
  • ✓
    Use descriptive parameter names (city, temperature_unit)
  • ✓
    Add error handling with try/catch blocks
  • ✓
    Validate inputs at the start of the function
  • ✓
    Keep each tool focused on one specific task
  • ✓
    Use environment variables for API keys and secrets
  • ✓
    Always return a value (string, object, or JSON)
  • ✓
    Test tools independently before integrating
Don't
  • ✗
    Don't write vague descriptions ("gets weather")
  • ✗
    Don't use generic parameter names (arg1, param, x)
  • ✗
    Don't skip error handling for async operations
  • ✗
    Don't create "do_everything" multi-purpose functions
  • ✗
    Don't hardcode API keys or secrets in code
  • ✗
    Don't return undefined or null without explanation
  • ✗
    Don't assume AI will always call your tool correctly
  • ✗
    Don't skip validation of critical parameters

Troubleshooting

AI Doesn't Call My Tool
Tool is defined but never gets invoked

Possible Causes:

  • • Description is too vague or doesn't match user intent
  • • Tool name conflicts with another tool
  • • AI model doesn't support function calling
  • • User prompt doesn't require tool usage

Solutions:

  • • Rewrite description to be more specific and include use cases
  • • Test with a direct prompt: "Use the get_weather tool to check Tokyo's weather"
  • • Verify your AI model supports function calling (GPT-4, Claude 3.5, Gemini 1.5)
  • • Check execution logs for tool registration confirmation
Function Code Throws Error
Runtime error during tool execution

Possible Causes:

  • • Syntax error in JavaScript code
  • • Missing dependencies or environment variables
  • • Network timeout for external API calls
  • • Invalid parameters passed by AI

Solutions:

  • • Add try/catch blocks around all async operations
  • • Validate inputs at the start of the function
  • • Check execution panel for error messages and stack traces
  • • Test function independently before integrating
AI Calls Tool with Wrong Arguments
Parameters don't match expected format

Possible Causes:

  • • Parameter descriptions are unclear
  • • Parameter types don't match schema
  • • Missing required parameters in schema

Solutions:

  • • Add detailed descriptions for each parameter
  • • Use enum for parameters with fixed options
  • • Mark critical parameters as required in schema
  • • Add input validation in function code
Tool Returns But AI Ignores Result
Function executes but result isn't used

Possible Causes:

  • • Function returns undefined or null
  • • Return format doesn't match AI expectations
  • • Error occurred but was silently caught

Solutions:

  • • Always return a value (string, object, or JSON)
  • • Use consistent return format across all code paths
  • • Log return values for debugging: console.log(result)
  • • Return error objects instead of throwing: { error: true, message: "..." }

Related Nodes

Text Model Node
Use tools with AI models for function calling
View Documentation
Structured Output Node
Force specific response formats from AI
View Documentation
JavaScript Node
Execute custom JavaScript for data transformation
View Documentation
HTTP Request Node
Make API calls to external services
View Documentation

Next Steps

Continue learning about other node types and advanced workflow patterns:

Text Model NodeView All NodesWorkflows 101