New:Introducing Socket Scanning for VS Code Marketplace Extensions.Learn more →
Get Started

@astermind/chatbot-template

Package Overview
Dependencies
Maintainers
2
Versions
26
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@astermind/chatbot-template

Embeddable AI chatbot widget with React support for AsterMind RAG

npmnpm
Version
1.0.3
Version published
Weekly downloads
2
-66.67%
Maintainers
2
Weekly downloads
 
Created
Source

@astermind/chatbot-template

Embeddable AI chatbot widget for AsterMind RAG - a drop-in chat UI that connects to your AsterMind backend with full agentic capabilities.

npm version License: MIT

Table of Contents

Features

Core Widget Features

  • Embeddable Floating Chat Bubble - Position anywhere on the page (4 corners)
  • React Components Library - 11 fully customizable components
  • Vanilla JS Standalone Bundle - IIFE format with React bundled for non-React sites
  • Full TypeScript Support - Complete type definitions exported

RAG Integration

  • AsterMind Backend Integration - Connects to /api/external/chat endpoints
  • Streaming Responses - SSE-based token-by-token message display
  • Source Citations - Collapsible source references with confidence levels
  • Session Management - Automatic sessionId handling across conversations
  • Confidence Indicators - Visual display of high/medium/low/none confidence

Agentic Capabilities

  • Navigation Actions - Navigate users to specific pages
  • Form Filling - Auto-fill form fields with suggested values
  • Element Clicking - Programmatically click buttons and links
  • Modal Triggering - Open dialogs and modals
  • Scrolling - Scroll to specific elements
  • Element Highlighting - Draw attention to page elements
  • Custom Action Handlers - Define your own action types
  • Action Cards UI - Confirm/cancel interface for proposed actions
  • Confidence Thresholds - Auto-execute high-confidence actions
  • Site Map Configuration - Define navigable pages for the agent

Offline & Fallback

  • Graceful Degradation - Works when connection is lost
  • Custom Offline Message - Configure what users see offline
  • Connection Status Indicator - Shows online/offline/connecting/error states
  • Optional Local RAG Fallback - Use Cybernetic RAG locally when offline

Theming & Customization

  • 20+ CSS Custom Properties - Full visual customization via CSS variables
  • JavaScript Theme Object - Configure themes programmatically
  • 4 Position Options - bottom-right, bottom-left, top-right, top-left
  • Configurable Dimensions - Width, height, bubble size
  • Full Color Customization - Every color is customizable
  • Typography Settings - Font family and size
  • Border Radius & Shadows - Visual effects customization

Installation

NPM (React Projects)

npm install @astermind/chatbot-template

CDN (Vanilla JS)

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@astermind/chatbot-template/dist/astermind-chatbot.css">
<script src="https://cdn.jsdelivr.net/npm/@astermind/chatbot-template/dist/astermind-chatbot.min.js"></script>

Quick Start

React Usage

import { ChatbotWidget } from '@astermind/chatbot-template';
import '@astermind/chatbot-template/styles';

function App() {
  return (
    <ChatbotWidget
      apiUrl="https://your-api-url.com"
      apiKey="am_your-api-key"
      position="bottom-right"
      greeting="Hi! How can I help you today?"
    />
  );
}

Vanilla JS Usage

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@astermind/chatbot-template/dist/astermind-chatbot.css">
</head>
<body>
  <script src="https://cdn.jsdelivr.net/npm/@astermind/chatbot-template/dist/astermind-chatbot.min.js"></script>
  <script>
    AsterMindChatbot.init({
      apiUrl: 'https://your-api-url.com',
      apiKey: 'am_your-api-key',
      position: 'bottom-right',
      greeting: 'Hi! How can I help you today?'
    });
  </script>
</body>
</html>

Configuration Reference

Required Options

OptionTypeDescription
apiKeystringYour AsterMind API key (starts with am_)
apiUrlstringBackend API URL (e.g., https://api.example.com)

Widget Options

OptionTypeDefaultDescription
position'bottom-right' | 'bottom-left' | 'top-right' | 'top-left''bottom-right'Widget position on screen
greetingstring'Hi! How can I help you today?'Initial greeting message
placeholderstring'Type your message...'Input placeholder text
headerTitlestring'AsterMind'Chat window header title
headerSubtitlestring'AI Assistant'Chat window header subtitle
defaultOpenbooleanfalseStart with chat window open
showPoweredBybooleantrueShow "Powered by AsterMind" badge
zIndexnumber9999Z-index for the widget

Theme Options

Customize appearance via the theme object:

{
  theme: {
    primaryColor: '#4F46E5',        // Primary brand color
    primaryHover: '#4338CA',        // Primary color on hover
    backgroundColor: '#ffffff',     // Background color
    surfaceColor: '#f3f4f6',        // Surface/card background
    textColor: '#1f2937',           // Primary text color
    textMuted: '#6b7280',           // Muted/secondary text
    borderColor: '#e5e7eb',         // Border color
    userBubbleBackground: '#4F46E5', // User message background
    userBubbleText: '#ffffff',      // User message text
    botBubbleBackground: '#f3f4f6', // Bot message background
    botBubbleText: '#1f2937',       // Bot message text
    widgetWidth: '380px',           // Widget width
    widgetHeight: '520px',          // Widget height
    bubbleSize: '60px',             // Trigger bubble size
    borderRadius: '12px',           // Border radius
    fontFamily: "'Inter', system-ui, sans-serif",
    fontSize: '14px',
    shadow: '0 4px 20px rgba(0, 0, 0, 0.15)'
  }
}

Agent Configuration

Enable agentic capabilities:

{
  agent: {
    enabled: true,
    confidenceThreshold: 0.8,     // Minimum confidence for auto-execution
    siteMap: [
      { path: '/products', name: 'Products', description: 'View products' },
      { path: '/contact', name: 'Contact', description: 'Contact us' },
      { path: '/pricing', name: 'Pricing', description: 'View pricing plans' }
    ],
    customActions: {
      openModal: async (params) => {
        // Custom action handler - open a modal
        document.getElementById(params.modalId).showModal();
      },
      trackEvent: async (params) => {
        // Custom analytics tracking
        analytics.track(params.eventName, params.data);
      }
    }
  }
}

Fallback Configuration

Configure offline behavior:

{
  fallback: {
    enabled: true,
    message: 'Working in offline mode. Some features may be limited.'
  }
}

Event Callbacks

CallbackParametersDescription
onReady()Called when widget is ready
onMessage(message: ChatMessage)Called on each message sent/received
onAction(action: AgentAction)Called when an agentic action occurs
onError(error: Error)Called when an error occurs
onToggle(isOpen: boolean)Called when widget opens/closes

Cybernetic Chatbot Integration

This widget is designed to work seamlessly with the @astermind/cybernetic-chatbot-client for advanced RAG capabilities.

How It Works

  • Widget sends messages to your AsterMind backend via the configured apiUrl
  • Backend processes queries using your RAG pipeline and returns responses
  • Streaming responses arrive via Server-Sent Events (SSE) for real-time display
  • Agentic actions are proposed by the AI and confirmed via Action Cards

API Endpoints

The widget connects to these backend endpoints:

EndpointMethodDescription
/api/external/healthGETHealth check, verifies connection
/api/external/chatPOSTNon-streaming chat endpoint
/api/external/chat/streamPOSTStreaming chat endpoint (SSE)

SSE Event Format

data: {"type": "chunk", "content": "Hello"}
data: {"type": "chunk", "content": " there!"}
data: {"type": "sources", "sources": [{"title": "Doc", "url": "..."}]}
data: {"type": "action", "action": {"type": "navigate", "path": "/products"}}
data: {"type": "done", "sessionId": "sess_xxx"}
data: {"type": "error", "error": "Error message"}

Offline Fallback

When offline or disconnected:

  • Widget shows connection status indicator
  • Custom offline message is displayed
  • If @astermind/cybernetic-chatbot-client is installed with local RAG enabled, queries can still be processed locally

Theming

CSS Variables

Override CSS variables in your stylesheet for quick customization:

:root {
  /* Colors */
  --astermind-primary: #10B981;
  --astermind-primary-hover: #059669;
  --astermind-background: #ffffff;
  --astermind-surface: #f3f4f6;
  --astermind-text: #1f2937;
  --astermind-text-muted: #6b7280;
  --astermind-border: #e5e7eb;

  /* User messages */
  --astermind-user-bubble-bg: #10B981;
  --astermind-user-bubble-text: #ffffff;

  /* Bot messages */
  --astermind-bot-bubble-bg: #f3f4f6;
  --astermind-bot-bubble-text: #1f2937;

  /* Dimensions */
  --astermind-widget-width: 400px;
  --astermind-widget-height: 600px;
  --astermind-bubble-size: 64px;

  /* Effects */
  --astermind-border-radius: 16px;
  --astermind-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);

  /* Typography */
  --astermind-font-family: 'Inter', system-ui, sans-serif;
  --astermind-font-size: 14px;
}

CSS Classes

All elements use the astermind- prefix for easy targeting:

ClassElement
.astermind-chatbotMain container
.astermind-bubbleFloating trigger button
.astermind-windowChat window
.astermind-headerWindow header
.astermind-messagesMessage list container
.astermind-messageIndividual message
.astermind-message--userUser message modifier
.astermind-message--botBot message modifier
.astermind-inputInput area
.astermind-statusStatus indicator
.astermind-action-cardAction confirmation card
.astermind-sourcesSource citations container

React Hooks API

useOmega

Direct API client access for custom implementations:

import { useOmega } from '@astermind/chatbot-template';

function MyComponent() {
  const {
    sendMessage,        // Send a message (non-streaming)
    sendMessageStream,  // Send a message (streaming)
    connectionStatus,   // 'online' | 'offline' | 'connecting' | 'error'
    isProcessing,       // Whether a request is in progress
    lastError,          // Last error that occurred
    sessionId,          // Current session ID
    clearSession        // Clear the current session
  } = useOmega({
    apiUrl: 'https://api.example.com',
    apiKey: 'am_your-api-key'
  });

  const handleSend = async () => {
    const response = await sendMessage('Hello!');
    console.log(response.reply, response.sources);
  };

  const handleStreamingSend = () => {
    sendMessageStream('Tell me about...', {
      onChunk: (chunk) => console.log('Chunk:', chunk),
      onSources: (sources) => console.log('Sources:', sources),
      onDone: (sessionId) => console.log('Done:', sessionId),
      onError: (error) => console.error('Error:', error)
    });
  };
}

useChat

Chat state management:

import { useChat } from '@astermind/chatbot-template';

function MyComponent() {
  const {
    messages,          // Array of chat messages
    addMessage,        // Add a new message
    updateMessage,     // Update an existing message
    clearMessages,     // Clear all messages
    pendingAction,     // Currently pending agent action
    setPendingAction   // Set pending action
  } = useChat();
}

useTheme

Theme customization hook:

import { useTheme } from '@astermind/chatbot-template';

function MyComponent() {
  const { theme, cssVariables } = useTheme({
    primaryColor: '#10B981',
    borderRadius: '16px'
  });

  // cssVariables contains the CSS custom property declarations
  return <div style={cssVariables}>...</div>;
}

useScrollToBottom

Auto-scroll behavior for message lists:

import { useScrollToBottom } from '@astermind/chatbot-template';

function MessageList({ messages }) {
  const { containerRef, scrollToBottom } = useScrollToBottom();

  return (
    <div ref={containerRef}>
      {messages.map(msg => <Message key={msg.id} {...msg} />)}
    </div>
  );
}

Components API

All components are exported for custom compositions:

import {
  ChatbotWidget,    // Main widget (includes bubble + window)
  ChatBubble,       // Floating trigger button
  ChatWindow,       // Chat window container
  ChatHeader,       // Window header with title/subtitle
  ChatInput,        // Message input with send button
  MessageList,      // Scrollable message container
  MessageBubble,    // Individual message bubble
  ActionCard,       // Agentic action confirmation card
  SourceCitation,   // Source reference component
  StatusIndicator,  // Connection status display
  TypingIndicator   // Typing/loading animation
} from '@astermind/chatbot-template';

Component Example

Build a custom chat interface:

import {
  ChatWindow,
  ChatHeader,
  MessageList,
  MessageBubble,
  ChatInput,
  StatusIndicator
} from '@astermind/chatbot-template';
import '@astermind/chatbot-template/styles';

function CustomChat({ messages, onSend, status }) {
  return (
    <ChatWindow>
      <ChatHeader
        title="Support Bot"
        subtitle="Always here to help"
      />
      <StatusIndicator status={status} />
      <MessageList>
        {messages.map(msg => (
          <MessageBubble
            key={msg.id}
            content={msg.content}
            role={msg.role}
            timestamp={msg.timestamp}
          />
        ))}
      </MessageList>
      <ChatInput
        onSend={onSend}
        placeholder="Ask a question..."
      />
    </ChatWindow>
  );
}

TypeScript Support

Full TypeScript support with exported types:

import type {
  // Configuration
  ChatbotConfig,
  ThemeConfig,
  AgentConfig,
  FallbackConfig,

  // Messages
  ChatMessage,
  MessageRole,

  // Actions
  AgentAction,
  ActionType,
  NavigateAction,
  FormFillAction,
  ClickAction,

  // Sources
  Source,
  SourceCitation,

  // Status
  ConnectionStatus,

  // Events
  ChatbotCallbacks
} from '@astermind/chatbot-template';

Troubleshooting

Widget not appearing

  • Ensure styles are imported: import '@astermind/chatbot-template/styles'
  • Check that apiUrl and apiKey are provided
  • Verify the widget container has position: relative or is in the document flow

Connection errors

  • Check that your apiUrl is correct and accessible
  • Verify your API key is valid and has the correct permissions
  • Check browser console for CORS errors - ensure your backend allows the origin

Streaming not working

  • Verify your backend supports the /api/external/chat/stream endpoint
  • Check that SSE is not being blocked by proxies or firewalls
  • Ensure Content-Type: text/event-stream header is set on responses

Actions not executing

  • Confirm agent.enabled is set to true
  • Check that actions meet the confidenceThreshold
  • Verify custom action handlers are properly defined

Styles not applying

  • Ensure the CSS file is loaded before the JS
  • Check for CSS specificity conflicts with your existing styles
  • Use !important or increase specificity if needed

Browser Support

BrowserVersion
Chrome80+
Firefox75+
Safari13+
Edge80+

The standalone bundle includes necessary polyfills for broader compatibility.

Build Outputs

FileFormatDescription
astermind-chatbot.esm.jsESMES Module for bundlers (tree-shakeable)
astermind-chatbot.umd.jsUMDUniversal Module Definition
astermind-chatbot.min.jsIIFEStandalone bundle with React included
astermind-chatbot.cssCSSCompiled and minified styles

License

MIT License - see LICENSE for details.

Built with care by the AsterMind team.

Keywords

chatbot

FAQs

Package last updated on 17 Jan 2026

Related posts