Voice+ Script

What is Voice+ Script?

Voice+ Script provides a programmatic API to trigger predefined voice steps from your web application. When a user performs specific actions on your frontend, you can send step IDs to the NLX platform to trigger corresponding voice prompts and advance the conversation flow.

Voice+ Script works by:

  1. Installing the Voice+ Core SDK in your application

  2. Calling sendStep() when specific user interactions occur

  3. Optionally passing context variables to customize the voice response

Quick Start

<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/@nlxai/voice-plus-core@latest/lib/index.umd.js"></script>
</head>
<body>
  <script>
    const getConversationId = () => {
      const urlParams = new URLSearchParams(window.location.search);
      return urlParams.get('cid');
    };

    const client = nlxai.voicePlusCore.create({
      apiKey: 'your-api-key',
      workspaceId: 'your-workspace-id', 
      scriptId: 'your-script-id',
      conversationId: getConversationId(),
      languageCode: 'en-US',
    });
  </script>
</body>
</html>

API Reference

create(config)

Creates a Voice+ client instance.

Parameters:

  • config (object): Configuration options

    • apiKey (string): API key generated for the script

    • workspaceId (string): Your workspace ID

    • scriptId (string): The script ID

    • conversationId (string): Conversation ID from voice bot (dynamic)

    • languageCode (string): Language code (e.g., 'en-US')

    • debug (boolean, optional): Enable debug logging. Default: false

Returns: Client instance with sendStep method

client.sendStep(stepId, context?)

Sends a step to trigger voice response.

Parameters:

  • stepId (string): UUID of the step to trigger

  • context (object, optional): Context variables to pass to NLX platform

Returns: Promise

Examples

Basic Step Trigger (No Context)

const WELCOME_STEP_ID = '123e4567-e89b-12d3-a456-426614174000';
const FORM_COMPLETE_STEP_ID = '987fcdeb-51a2-43d1-b789-123456789abc';

// Trigger welcome message when page loads
document.addEventListener('DOMContentLoaded', async () => {
  await client.sendStep(WELCOME_STEP_ID);
});

// Trigger completion message when form submitted
document.getElementById('contact-form').addEventListener('submit', async (e) => {
  e.preventDefault();
  await client.sendStep(FORM_COMPLETE_STEP_ID);
});

Step with Context Variables

const USER_SELECTION_STEP_ID = 'abc12345-6789-def0-1234-56789abcdef0';
const ORDER_SUMMARY_STEP_ID = 'def67890-abcd-1234-5678-9abcdef01234';

// Send user selection with context
const handleProductSelection = async (productId, productName, price) => {
  const productContext = {
    SELECTED_PRODUCT_ID: productId,
    SELECTED_PRODUCT_NAME: productName,
    SELECTED_PRODUCT_PRICE: price,
    SELECTION_TIMESTAMP: new Date().toISOString(),
  };
  
  await client.sendStep(USER_SELECTION_STEP_ID, productContext);
};

// Send order summary with structured data
const handleOrderComplete = async (orderData) => {
  const orderContext = {
    ORDER_ID: orderData.id,
    ORDER_TOTAL: orderData.total,
    CUSTOMER_INFO: {
      name: orderData.customer.name,
      email: orderData.customer.email,
      phone: orderData.customer.phone,
    },
    ORDER_ITEMS: orderData.items.map(item => ({
      id: item.id,
      name: item.name,
      quantity: item.quantity,
      price: item.price,
    })),
  };
  
  await client.sendStep(ORDER_SUMMARY_STEP_ID, orderContext);
};

// Usage examples
handleProductSelection('prod-123', 'Wireless Headphones', '$99.99');

handleOrderComplete({
  id: 'order-456', 
  total: '$199.98',
  customer: { name: 'John Doe', email: '[email protected]', phone: '555-0123' },
  items: [
    { id: 'prod-123', name: 'Wireless Headphones', quantity: 2, price: '$99.99' }
  ]
});

Context Variables

Context variables allow you to pass dynamic data from your application to the NLX platform. These variables can be referenced in voice scripts and used in intent flows.

Context Variable Types

const contextExample = {
  // String variables
  USER_NAME: "John Doe",
  PRODUCT_CATEGORY: "electronics",
  
  // Numeric variables  
  ORDER_TOTAL: 299.99,
  ITEM_COUNT: 3,
  
  // Boolean variables
  IS_PREMIUM_USER: true,
  HAS_DISCOUNT: false,
  
  // Object variables
  USER_PROFILE: {
    id: "user-123",
    tier: "gold",
    preferences: ["tech", "gadgets"]
  },
  
  // Array variables
  SELECTED_ITEMS: ["item-1", "item-2", "item-3"],
  CATEGORIES: [
    { id: "cat-1", name: "Electronics" },
    { id: "cat-2", name: "Books" }
  ]
};

await client.sendStep(STEP_ID, contextExample);

Using Context in NLX Platform

Context variables can be referenced in your NLX voice scripts and intent flows:

  • Voice Scripts: Use {VARIABLE_NAME} syntax in voice prompts

  • Intent Flows: Access via context attributes in flow nodes

  • Data Requests: Pass context variables to external APIs

Best Practices

Error Handling

const sendStepSafely = async (stepId, context = {}) => {
  try {
    await client.sendStep(stepId, context);
  } catch (error) {
    console.error('Failed to send Voice+ step:', error);
    // Fallback behavior - don't break user experience
  }
};

Conversation ID Management

// Get conversation ID from URL and persist in session
const getOrCreateConversationId = () => {
  const SESSION_KEY = 'nlx-conversation-id';
  const EXPIRY_MINUTES = 30;
  
  // Check URL first
  const urlParams = new URLSearchParams(window.location.search);
  const cidFromUrl = urlParams.get('cid');
  
  if (cidFromUrl) {
    const sessionData = {
      conversationId: cidFromUrl,
      timestamp: Date.now()
    };
    sessionStorage.setItem(SESSION_KEY, JSON.stringify(sessionData));
    return cidFromUrl;
  }
  
  // Check session storage
  const storedData = sessionStorage.getItem(SESSION_KEY);
  if (storedData) {
    const { conversationId, timestamp } = JSON.parse(storedData);
    const isExpired = (Date.now() - timestamp) > (EXPIRY_MINUTES * 60 * 1000);
    
    if (!isExpired) {
      return conversationId;
    }
  }
  
  return null;
};

Step ID Management

// Centralize step IDs as constants
const VOICE_STEPS = {
  WELCOME: '123e4567-e89b-12d3-a456-426614174000',
  FORM_START: '234e5678-e89b-12d3-a456-426614174111', 
  FORM_COMPLETE: '345e6789-e89b-12d3-a456-426614174222',
  ERROR_OCCURRED: '456e7890-e89b-12d3-a456-426614174333',
  GOODBYE: '567e8901-e89b-12d3-a456-426614174444',
};

// Validate step IDs at startup
const validateStepIds = () => {
  const stepIdRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
  
  Object.entries(VOICE_STEPS).forEach(([name, id]) => {
    if (!stepIdRegex.test(id)) {
      console.error(`Invalid step ID for ${name}: ${id}`);
    }
  });
};

E-commerce Integration

const trackPurchaseFlow = {
  productView: async (product) => {
    await client.sendStep(VOICE_STEPS.PRODUCT_VIEW, {
      PRODUCT_ID: product.id,
      PRODUCT_NAME: product.name,
      PRODUCT_PRICE: product.price,
      PRODUCT_CATEGORY: product.category,
    });
  },
  
  addToCart: async (product, quantity) => {
    await client.sendStep(VOICE_STEPS.ADD_TO_CART, {
      PRODUCT_ID: product.id,
      QUANTITY: quantity,
      CART_VALUE: product.price * quantity,
    });
  },
  
  checkout: async (cartItems, total) => {
    await client.sendStep(VOICE_STEPS.CHECKOUT_START, {
      CART_ITEMS: cartItems,
      CART_TOTAL: total,
      ITEM_COUNT: cartItems.length,
    });
  }
};

Last updated