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.
How Tool Calls Work
Tool calls create a bridge between the AI conversation and your website's functionality. The process works as follows:
- Configure in Dashboard: You define tool calls in the BadgerFy.ai dashboard, specifying the function name, description, response text, and parameters.
- AI Decision: During a conversation, the AI determines when to call a tool based on the user's request and the tool's description.
- Parameter Extraction: The AI extracts relevant parameters from the conversation and your data sources.
- Script Execution: Your client-side script receives the function call and executes the corresponding action.
- 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.
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 loadswindow.badgerfyaiConfig = {functions: [{pageAgentId: 'YOUR_PAGE_AGENT_ID',functionName: 'addToCart',functionCall: async (parameters) => {try {console.log('Add to Cart called with:', parameters);// Validate required parametersif (!parameters.sku) {return {success: false,error: 'Product SKU is required'};}// Your cart logic hereconst 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 --><scriptsrc="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 logicreturn { 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 logicconst inStock = true; // Your logic herereturn {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 logicreturn {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.jsimport Script from 'next/script';import { useEffect, useState, useCallback } from 'react';import { useCart } from '../context/CartContext'; // Your cart contextexport default function BadgerfyEmbed() {const { addToCart } = useCart();const [scriptError, setScriptError] = useState(false);// Memoize the configuration setupconst setupToolCalls = useCallback(() => {// Safety check for SSR - window may not existif (typeof window === 'undefined') {console.warn('[BadgerFy] Window not available (SSR)');return;}// Define the tool call configurationwindow.badgerfyaiConfig = {functions: [{pageAgentId: 'YOUR_PAGE_AGENT_ID',functionName: 'addToCart',functionCall: async (parameters) => {try {console.log('🛒 Add to Cart called with:', parameters);// Validate required parametersif (!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 managementaddToCart(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 loadsuseEffect(() => {setupToolCalls();// Cleanup on unmountreturn () => {if (typeof window !== 'undefined') {delete window.badgerfyaiConfig;}};}, [setupToolCalls]);const handleScriptLoad = () => {console.log('✅ BadgerFy.ai script loaded successfully');setScriptError(false);// Verify the global object is availableif (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 SSRif (typeof window === 'undefined') {return null;}return (<><Scriptsrc="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 exampleasync function findProductBySku(sku) {// Your product lookup logic// Could be from context, API call, or local datareturn null;}
Add to Your Layout
// Layout.js or _app.jsimport 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 formatreturn {success: true,data: {// Optional: Include any relevant data// This can be used by the AI to provide contextsku: 'PROD-123',quantity: 2,message: 'Added successfully'}};
Failure Response
// Failure response - required formatreturn {success: false,error: 'Descriptive error message for the AI'};
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()orparseFloat(). - boolean: True/false values (gift wrap, express shipping)
Validation Example
functionCall: async (parameters) => {try {// Validate required string parameterif (!parameters.sku || typeof parameters.sku !== 'string') {return { success: false, error: 'Valid SKU is required' };}// Parse and validate number parameterconst quantity = parseInt(parameters.quantity);if (isNaN(quantity) || quantity < 1) {return { success: false, error: 'Quantity must be at least 1' };}// Handle optional boolean parameterconst giftWrap = parameters.giftWrap === true;// Proceed with validated parametersreturn {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:
- Local Development: Add
data-test-mode="true"to your script tag to enable test mode, which loads disabled agents and provides console logging. - Console Logging: Add
console.logstatements in your function calls to verify parameters are received correctly. - Staging Environment: Deploy to a staging site to test the full integration before going live.
<!-- Enable test mode for local development --><scriptsrc="https://app.badgerfy.ai/embeds/badgerfy.min.js"data-project-id="YOUR_PROJECT_ID"data-test-mode="true"async></script>
- 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.