paltextsdk-react
v0.2.8
Published
React SDK for PalText AI Customer Support Agents
Downloads
50
Maintainers
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-reactQuick 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
- Dual-Mode Chat: Seamless switching between AI and human support agents
- Real-Time Communication: WebSocket-based communication for instant messaging with human agents
- Local Ticket Management: Creates local tickets that convert to real tickets upon escalation
- Message Persistence: Maintains chat history across page refreshes using localStorage
- Optimized Performance: Throttled updates to prevent excessive renders
- 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
- Local Ticket Creation: When a chat is initiated, a local ticket is created in memory and localStorage
- AI Conversation: Initial conversation happens with the AI in AI mode
- Escalation Process: When escalation is requested, the local ticket is converted to a real ticket in the backend
- WebSocket Connection: For human agent conversations, a WebSocket connection is established
- 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:
- Connects to the WebSocket server upon escalation
- Sets the active ticket for message routing
- Sends messages through the WebSocket when in HUMAN mode
- Falls back to REST API if WebSocket fails
- Handles reconnection and message queuing
Troubleshooting
Common Issues
- WebSocket Connection Failed: Ensure your WebSocket URL is correct and the server is running
- Messages Not Reaching Human Agent: Check if escalation was successful and the WebSocket connection is established
- 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].
