BadgerFy.ai Docs

Tool Calls Script Setup

Tool Calls allow your AI Assistant to perform dynamic actions on your website based on user conversations. This guide covers how to implement the client-side script that handles these function calls.

ℹ️ AI Assistant Only: Tool Calls are currently only available for the AI Assistant agent type.
⚠️ Pro & Business Plans Only: Tool Calls are a premium feature available exclusively on Pro and Business subscription plans. Upgrade your plan to enable tool call functionality for your AI Assistant.

How Tool Calls Work

Tool calls create a bridge between the AI conversation and your website's functionality. The process works as follows:

  1. Configure in Dashboard: You define tool calls in the BadgerFy.ai dashboard, specifying the function name, description, response text, and parameters.
  2. AI Decision: During a conversation, the AI determines when to call a tool based on the user's request and the tool's description.
  3. Parameter Extraction: The AI extracts relevant parameters from the conversation and your data sources.
  4. Script Execution: Your client-side script receives the function call and executes the corresponding action.
  5. Response Handling: Your script returns a success or failure response, which the AI uses to continue the conversation.

Dashboard Configuration

Before implementing the script, configure your tool calls in the BadgerFy.ai dashboard under the "Tool Calls" tab of your AI Assistant:

  • Tool Name: A descriptive name that will be converted to camelCase (e.g., "Add To Cart" becomes addToCart).
  • Description: Instructions for the AI on when and how to use this tool. Be specific about the conditions that should trigger this tool call.
  • Response Text: The message the AI will use (or adapt) when calling this function. The AI may improvise slightly based on context.
  • Parameters: Define the data the AI should extract and pass to your function. Each parameter has a name, type (string, number, boolean), description, and optional default value.
⚠️ Data Source Requirement: All parameters should reference data available in your uploaded data sources. The AI can only extract parameter values from information it has access to through your knowledge base.

Static Website Installation

For static HTML websites, define your tool call handlers using the window.badgerfyaiConfig object before the BadgerFy.ai script loads.

Basic Implementation

<script>
// Define tool call handlers BEFORE the BadgerFy script loads
window.badgerfyaiConfig = {
functions: [
{
pageAgentId: 'YOUR_PAGE_AGENT_ID',
functionName: 'addToCart',
functionCall: async (parameters) => {
try {
console.log('Add to Cart called with:', parameters);
// Validate required parameters
if (!parameters.sku) {
return {
success: false,
error: 'Product SKU is required'
};
}
// Your cart logic here
const quantity = parseInt(parameters.quantity) || 1;
// Example: Call your cart API or update cart state
// await fetch('/api/cart/add', {
// method: 'POST',
// body: JSON.stringify({ sku: parameters.sku, quantity })
// });
return {
success: true,
data: {
sku: parameters.sku,
quantity: quantity,
message: 'Item added to cart'
}
};
} catch (error) {
console.error('Add to cart failed:', error);
return {
success: false,
error: error.message || 'Failed to add item to cart'
};
}
}
}
]
};
</script>
<!-- BadgerFy.ai Script - Load AFTER config -->
<script
src="https://app.badgerfy.ai/embeds/badgerfy.min.js"
data-project-id="YOUR_PROJECT_ID"
async
></script>

Multiple Tool Calls

You can define multiple tool calls in the functions array:

<script>
window.badgerfyaiConfig = {
functions: [
{
pageAgentId: 'YOUR_PAGE_AGENT_ID',
functionName: 'addToCart',
functionCall: async (parameters) => {
try {
// Add to cart logic
return { success: true, data: { sku: parameters.sku } };
} catch (error) {
return { success: false, error: error.message };
}
}
},
{
pageAgentId: 'YOUR_PAGE_AGENT_ID',
functionName: 'checkInventory',
functionCall: async (parameters) => {
try {
// Check inventory logic
const inStock = true; // Your logic here
return {
success: true,
data: {
sku: parameters.sku,
inStock: inStock,
quantity: 15
}
};
} catch (error) {
return { success: false, error: error.message };
}
}
},
{
pageAgentId: 'YOUR_PAGE_AGENT_ID',
functionName: 'subscribeNewsletter',
functionCall: async (parameters) => {
try {
// Newsletter subscription logic
return {
success: true,
data: { email: parameters.email }
};
} catch (error) {
return { success: false, error: error.message };
}
}
}
]
};
</script>

Next.js / React Installation

For React-based applications, define the configuration inside a useEffect hook to ensure it runs on the client side.

BadgerFy Embed Component

// components/BadgerfyEmbed.js
import Script from 'next/script';
import { useEffect, useState, useCallback } from 'react';
import { useCart } from '../context/CartContext'; // Your cart context
export default function BadgerfyEmbed() {
const { addToCart } = useCart();
const [scriptError, setScriptError] = useState(false);
// Memoize the configuration setup
const setupToolCalls = useCallback(() => {
// Safety check for SSR - window may not exist
if (typeof window === 'undefined') {
console.warn('[BadgerFy] Window not available (SSR)');
return;
}
// Define the tool call configuration
window.badgerfyaiConfig = {
functions: [
{
pageAgentId: 'YOUR_PAGE_AGENT_ID',
functionName: 'addToCart',
functionCall: async (parameters) => {
try {
console.log('🛒 Add to Cart called with:', parameters);
// Validate required parameters
if (!parameters.sku) {
return {
success: false,
error: 'SKU is required'
};
}
// Find product in your data (example)
const product = await findProductBySku(parameters.sku);
if (!product) {
return {
success: false,
error: `Product with SKU ${parameters.sku} not found`
};
}
const qty = parseInt(parameters.quantity) || 1;
// Use your cart context or state management
addToCart(product, qty);
return {
success: true,
data: {
cartId: 'user-cart',
sku: parameters.sku,
quantity: qty,
productName: product.name
}
};
} catch (error) {
console.error('[BadgerFy] Add to cart error:', error);
return {
success: false,
error: error.message || 'Failed to add to cart'
};
}
}
}
]
};
console.log('✅ BadgerFy.ai tool calls configured');
}, [addToCart]);
// Set up configuration before script loads
useEffect(() => {
setupToolCalls();
// Cleanup on unmount
return () => {
if (typeof window !== 'undefined') {
delete window.badgerfyaiConfig;
}
};
}, [setupToolCalls]);
const handleScriptLoad = () => {
console.log('✅ BadgerFy.ai script loaded successfully');
setScriptError(false);
// Verify the global object is available
if (typeof window !== 'undefined' && !window.badgerfyai) {
console.warn('[BadgerFy] Script loaded but badgerfyai not initialized');
}
};
const handleScriptError = (error) => {
console.error('[BadgerFy] Failed to load script:', error);
setScriptError(true);
// Optional: Report to error tracking service
// reportError('BadgerFy script failed to load', error);
};
// Don't render script if we're in SSR
if (typeof window === 'undefined') {
return null;
}
return (
<>
<Script
src="https://app.badgerfy.ai/embeds/badgerfy.min.js"
data-project-id="YOUR_PROJECT_ID"
strategy="afterInteractive"
onLoad={handleScriptLoad}
onError={handleScriptError}
/>
{scriptError && (
<div style={{ display: 'none' }}>
{/* Hidden error state - handle as needed */}
</div>
)}
</>
);
}
// Helper function example
async function findProductBySku(sku) {
// Your product lookup logic
// Could be from context, API call, or local data
return null;
}

Add to Your Layout

// Layout.js or _app.js
import BadgerfyEmbed from '../components/BadgerfyEmbed';
export default function Layout({ children }) {
return (
<>
<header>{/* Your header */}</header>
<main>{children}</main>
<footer>{/* Your footer */}</footer>
{/* BadgerFy.ai with Tool Calls */}
<BadgerfyEmbed />
</>
);
}

Response Format

Your tool call functions must return a response object with the following structure:

Success Response

// Success response - required format
return {
success: true,
data: {
// Optional: Include any relevant data
// This can be used by the AI to provide context
sku: 'PROD-123',
quantity: 2,
message: 'Added successfully'
}
};

Failure Response

// Failure response - required format
return {
success: false,
error: 'Descriptive error message for the AI'
};
💡 Error Messages: Provide clear, user-friendly error messages. The AI may use these to explain what went wrong to the user.

Parameter Handling

Parameters defined in your dashboard configuration are passed to your function as a single parameters object. Always validate parameters before using them.

Parameter Types

  • string: Text values (product names, SKUs, emails)
  • number: Numeric values (quantities, prices). Parse with parseInt() or parseFloat().
  • boolean: True/false values (gift wrap, express shipping)

Validation Example

functionCall: async (parameters) => {
try {
// Validate required string parameter
if (!parameters.sku || typeof parameters.sku !== 'string') {
return { success: false, error: 'Valid SKU is required' };
}
// Parse and validate number parameter
const quantity = parseInt(parameters.quantity);
if (isNaN(quantity) || quantity < 1) {
return { success: false, error: 'Quantity must be at least 1' };
}
// Handle optional boolean parameter
const giftWrap = parameters.giftWrap === true;
// Proceed with validated parameters
return {
success: true,
data: { sku: parameters.sku, quantity, giftWrap }
};
} catch (error) {
return { success: false, error: error.message };
}
}

Testing Tool Calls

Tool calls cannot be tested in the dashboard test environment. To test your implementation:

  1. Local Development: Add data-test-mode="true" to your script tag to enable test mode, which loads disabled agents and provides console logging.
  2. Console Logging: Add console.log statements in your function calls to verify parameters are received correctly.
  3. Staging Environment: Deploy to a staging site to test the full integration before going live.
<!-- Enable test mode for local development -->
<script
src="https://app.badgerfy.ai/embeds/badgerfy.min.js"
data-project-id="YOUR_PROJECT_ID"
data-test-mode="true"
async
></script>
⚠️ Test Mode Limitations:
  • Test mode only works on localhost — it will not function on production or staging servers.
  • Performance may be slower due to uncached data lookups.
  • AI generations in test mode will consume tokens from your plan allocation.

Best Practices

  • Always Use Try/Catch: Wrap your function logic in try/catch blocks to handle unexpected errors gracefully.
  • Validate All Parameters: Never assume parameters are present or correctly typed. Always validate before using.
  • Return Quickly: Tool calls should complete within a reasonable time. Long-running operations should be queued for background processing.
  • Meaningful Errors: Return descriptive error messages that help the AI explain issues to users.
  • Data Source Alignment: Ensure parameter values (like SKUs or product IDs) match what's in your uploaded data sources.
  • Logging: Add console logging during development to debug parameter values and function execution.