npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

paltextsdk-react

v0.2.8

Published

React SDK for PalText AI Customer Support Agents

Downloads

50

Readme

PalTextSDK React

A powerful React SDK for seamless AI and human agent live chat integration in your web applications.

Overview

PalTextSDK React is a comprehensive solution for integrating conversational AI capabilities with human agent escalation into your React applications. It provides real-time chat functionality, message persistence, and a smooth transition between AI and human support agents.

Tech Stack

Frontend

  • React: Component-based integration with React applications
  • TypeScript: Type-safe SDK implementation for better developer experience
  • WebSockets: Real-time bidirectional communication with support agents
  • LocalStorage: Client-side persistence for chat sessions

Backend

  • Node.js: Backend API that handles chat messages, tickets, and user sessions
  • WebSockets: Real-time server using Socket.io for instant message delivery
  • REST API: HTTP-based API for non-real-time operations

Database

  • MongoDB: Stores chat history, tickets, and user information
  • Redis: Optional caching layer for improved performance

AI

  • Large Language Models: Powers the AI chat capabilities
  • Contextual Understanding: Maintains conversation context for relevant responses
  • Sentiment Analysis: Detects when to offer human escalation

Installation

npm install paltextsdk-react

Quick Start

import React from 'react';
import { PalTextProvider, usePalText } from 'paltextsdk-react';

// Chat component that uses the SDK
const ChatComponent = () => {
  const { 
    sendMessage, 
    escalateToHuman, 
    chatHistory, 
    isLoading, 
    chatMode 
  } = usePalText();

  const handleSendMessage = async (message) => {
    try {
      await sendMessage(message);
    } catch (error) {
      console.error('Failed to send message:', error);
    }
  };

  const handleEscalate = async () => {
    try {
      await escalateToHuman('Customer requested human agent');
    } catch (error) {
      console.error('Failed to escalate:', error);
    }
  };

  return (
    <div className="chat-container">
      <div className="messages">
        {chatHistory.map((msg, index) => (
          <div key={index} className={`message ${msg.role}`}>
            {msg.content}
          </div>
        ))}
      </div>
      {isLoading && <div className="loading">Loading...</div>}
      <button onClick={handleEscalate}>Talk to a Human</button>
      <div className="input-area">
        <input 
          type="text" 
          placeholder="Type your message..." 
          onKeyPress={(e) => e.key === 'Enter' && handleSendMessage(e.target.value)}
        />
        <button onClick={() => handleSendMessage(document.querySelector('input').value)}>
          Send
        </button>
      </div>
    </div>
  );
};

// Wrap your application with the PalTextProvider
const App = () => {
  return (
    <PalTextProvider 
      apiKey="your-api-key-here"
      enableWebsocket={true}
      debug={false}
    >
      <div className="app">
        <h1>Customer Support</h1>
        <ChatComponent />
      </div>
    </PalTextProvider>
  );
};

export default App;

Key Features

  1. Dual-Mode Chat: Seamless switching between AI and human support agents
  2. Real-Time Communication: WebSocket-based communication for instant messaging with human agents
  3. Local Ticket Management: Creates local tickets that convert to real tickets upon escalation
  4. Message Persistence: Maintains chat history across page refreshes using localStorage
  5. Optimized Performance: Throttled updates to prevent excessive renders
  6. Robust Error Handling: Graceful handling of connection issues and service interruptions

API Reference

PalTextProvider Props

| Prop | Type | Default | Description | |------|------|---------|-------------| | apiKey | string | (required) | Your PalText API key | | apiUrl | string | "http://localhost:8888" | Base URL for the REST API | | webSocketUrl | string | "ws://localhost:8888" | URL for WebSocket connections | | enableWebsocket | boolean | false | Enable WebSocket communication | | businessId | string | undefined | Optional business ID | | debug | boolean | false | Enable debug logging | | logLevel | 'debug' | 'info' | 'warn' | 'error' | 'none' | 'info' | Logging level | | maxHistorySize | number | 50 | Maximum number of messages to keep in history |

usePalText Hook

Returns an object with the following properties and methods:

Properties

| Property | Type | Description | |----------|------|-------------| | sdk | PalTextSDK | Direct access to the underlying SDK instance | | isInitialized | boolean | Whether the SDK is initialized | | isAuthenticated | boolean | Whether the user is authenticated | | chatHistory | ChatMessage[] | Array of chat messages | | businessName | string | Name of the business | | chatMode | ChatMode | Current chat mode (AI or HUMAN) | | isLoading | boolean | Whether an operation is in progress | | initError | string | Initialization error message if any |

Methods

| Method | Parameters | Return | Description | |--------|------------|--------|-------------| | initChat | (subject: string) | Promise<ActionResult> | Initialize a new chat | | sendMessage | (message: string) | Promise<ActionResult> | Send a message | | escalateToHuman | (reason?: string) | Promise<EscalationResult> | Escalate to a human agent | | closeTicket | (reason?: string) | Promise<ActionResult> | Close the current ticket | | clearChatHistory | () | void | Clear chat history | | switchChatMode | (mode: ChatMode) | void | Switch between AI and HUMAN modes |

Advanced Usage

Custom Chat UI

import { usePalText, ChatMode } from 'paltextsdk-react';
import { useState } from 'react';

const CustomChatUI = () => {
  const [inputText, setInputText] = useState('');
  const {
    sendMessage,
    escalateToHuman,
    closeTicket,
    chatHistory,
    chatMode,
    isLoading
  } = usePalText();

  const handleSendMessage = async () => {
    if (!inputText.trim()) return;
    
    try {
      await sendMessage(inputText);
      setInputText('');
    } catch (error) {
      console.error('Error sending message:', error);
    }
  };

  return (
    <div className="custom-chat">
      <div className="chat-header">
        <h2>Support Chat</h2>
        <div className="chat-status">
          {chatMode === ChatMode.HUMAN ? 
            <span className="human-mode">Talking to a Human Agent</span> : 
            <span className="ai-mode">AI Assistant</span>
          }
        </div>
      </div>
      
      <div className="message-container">
        {chatHistory.map((msg, idx) => (
          <div key={idx} className={`message ${msg.role}`}>
            <div className="message-sender">
              {msg.role === 'user' ? 'You' : 
               msg.role === 'assistant' ? 'AI Assistant' : 
               msg.role === 'agent' ? 'Support Agent' : 'System'}
            </div>
            <div className="message-content">{msg.content}</div>
            <div className="message-time">
              {msg.timestamp.toLocaleTimeString()}
            </div>
          </div>
        ))}
        {isLoading && <div className="typing-indicator">...</div>}
      </div>
      
      <div className="chat-actions">
        {chatMode === ChatMode.AI && (
          <button 
            onClick={() => escalateToHuman("Customer requested human assistance")}
            className="escalate-button"
          >
            Talk to a Human
          </button>
        )}
        <button 
          onClick={() => closeTicket("User ended conversation")}
          className="close-button"
        >
          End Chat
        </button>
      </div>
      
      <div className="message-input">
        <textarea
          value={inputText}
          onChange={(e) => setInputText(e.target.value)}
          placeholder="Type your message here..."
          onKeyPress={(e) => e.key === 'Enter' && !e.shiftKey && handleSendMessage()}
        />
        <button onClick={handleSendMessage} disabled={isLoading}>
          Send
        </button>
      </div>
    </div>
  );
};

Implementation Details

Ticket Lifecycle

  1. Local Ticket Creation: When a chat is initiated, a local ticket is created in memory and localStorage
  2. AI Conversation: Initial conversation happens with the AI in AI mode
  3. Escalation Process: When escalation is requested, the local ticket is converted to a real ticket in the backend
  4. WebSocket Connection: For human agent conversations, a WebSocket connection is established
  5. Ticket Closure: When the conversation ends, the ticket is closed and the chat history is maintained

WebSocket Communication

The SDK automatically handles the WebSocket connection for real-time communication with human agents:

  1. Connects to the WebSocket server upon escalation
  2. Sets the active ticket for message routing
  3. Sends messages through the WebSocket when in HUMAN mode
  4. Falls back to REST API if WebSocket fails
  5. Handles reconnection and message queuing

Troubleshooting

Common Issues

  1. WebSocket Connection Failed: Ensure your WebSocket URL is correct and the server is running
  2. Messages Not Reaching Human Agent: Check if escalation was successful and the WebSocket connection is established
  3. Initialization Errors: Verify your API key and ensure the API server is accessible

Debugging

Enable debug mode for detailed logging:

<PalTextProvider 
  apiKey="your-api-key"
  debug={true}
  logLevel="debug"
>
  {/* Your components */}
</PalTextProvider>

License

MIT


For more information, visit our documentation website or contact our support team at [email protected].