@enkaliprime/react-native-chat-sdk
v1.1.2
Published
Official React Native SDK for EnkaliPrime Chat API - Direct API integration for mobile applications with custom UI/UX design
Readme
💬 @enkaliprime/react-native-chat-sdk
Official React Native SDK for EnkaliPrime Chat API
Powered by EnkaliBridge for secure, unified API access with custom UI/UX design
✨ Features
| 🚀 Core Features | 🎨 UI/UX | 🔒 Security | |---------------------|--------------|-----------------| | ✅ RAG-Enabled AI | ✅ Custom UI/UX Design | ✅ EnkaliBridge Integration | | ✅ Real-time Messaging | ✅ Typing Indicators | ✅ Secure Gateway | | ✅ Streaming Support | ✅ Quick Replies | ✅ Unified API Key | | ✅ Conversation History | ✅ Session Management | ✅ No Credential Exposure |
🎯 Key Highlights
- 🤖 RAG-Enabled AI - Retrieval-Augmented Generation with Knowledge Base support
- 🔐 EnkaliBridge Integration - Secure unified API key authentication
- 🎨 Custom UI/UX Design - Build your own chat experience
- ⚡ Real-time Messaging - Instant message delivery with AI responses
- 📡 Streaming Support - Optional real-time streaming responses
- 💾 Conversation History - Automatic context management for better AI responses
- 🔄 Session Management - Persistent chat sessions
- ⌨️ Typing Indicators - Real-time typing feedback
- 🎯 Quick Replies - Interactive response options
- 📘 TypeScript Support - Full type safety
- 🛡️ Error Handling - Robust error management
- 🪝 React Native Hooks - Easy integration
📦 Installation
npm install @enkaliprime/react-native-chat-sdk📋 Peer Dependencies
Make sure you have these dependencies installed:
npm install @react-native-async-storage/async-storage
npm install expo-blur
npm install expo-linear-gradient
npm install lottie-react-native
npm install react-native-reanimated🚀 Quick Start
🔑 Getting Your EnkaliBridge API Key
| Step | Action |
|------|--------|
| 1️⃣ | Connect your SDK to a Widget in the EnkaliPrime dashboard |
| 2️⃣ | Navigate to the EnkaliBridge API section |
| 3️⃣ | Copy your unified API key (starts with ek_bridge_) |
💻 Basic Usage
import React, { useEffect } from 'react';
import { View, Text } from 'react-native';
import { useReactNativeChat } from '@enkaliprime/react-native-chat-sdk';
const ChatScreen = () => {
const apiConfig = {
unifiedApiKey: 'ek_bridge_1763490675941_km8imacsz5', // Get this from EnkaliBridge API section
baseUrl: 'https://sdk.enkaliprime.com', // EnkaliBridge gateway URL
userId: 'user_123' // Optional: your user identifier
};
const {
messages,
isLoading,
error,
sendMessage,
createSession
} = useReactNativeChat(apiConfig, {
agentName: 'Support Agent',
onError: (error) => console.error('Chat error:', error)
});
useEffect(() => {
createSession();
}, []);
return (
<View>
{/* Your custom chat UI */}
{messages.map((message) => (
<View key={message.id}>
<Text>{message.text}</Text>
</View>
))}
</View>
);
};🎨 Complete Example
import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, TouchableOpacity, ScrollView, Alert } from 'react-native';
import { useReactNativeChat } from '@enkaliprime/react-native-chat-sdk';
const CustomChatScreen = () => {
const [inputText, setInputText] = useState('');
const apiConfig = {
unifiedApiKey: 'ek_bridge_1763490675941_km8imacsz5', // Get this from EnkaliBridge API section
baseUrl: 'https://sdk.enkaliprime.com', // EnkaliBridge gateway URL
userId: 'user_123' // Optional: your user identifier
};
const {
messages,
isLoading,
error,
sendMessage,
createSession,
isTyping,
clearHistory,
getHistory
} = useReactNativeChat(apiConfig, {
agentName: 'Sarah',
agentAvatar: 'https://example.com/avatar.jpg',
metadata: {
appVersion: '1.0.0',
platform: 'react-native'
},
enableStreaming: false, // Set to true for streaming responses
onError: (error) => Alert.alert('Error', error),
onMessageReceived: (message) => {
console.log('New message:', message);
},
onStreamingChunk: (chunk) => {
// Handle streaming chunks (if enableStreaming is true)
console.log('Streaming chunk:', chunk);
}
});
useEffect(() => {
createSession();
}, []);
const handleSendMessage = async () => {
if (inputText.trim()) {
await sendMessage(inputText.trim());
setInputText('');
}
};
return (
<View style={{ flex: 1 }}>
<ScrollView style={{ flex: 1 }}>
{messages.map((message) => (
<View key={message.id} style={{
alignSelf: message.isUser ? 'flex-end' : 'flex-start',
backgroundColor: message.isUser ? '#007AFF' : '#F0F0F0',
padding: 10,
margin: 5,
borderRadius: 10,
maxWidth: '80%'
}}>
<Text style={{
color: message.isUser ? 'white' : 'black'
}}>
{message.text}
</Text>
</View>
))}
{isTyping && (
<View style={{ alignSelf: 'flex-start', padding: 10 }}>
<Text>Agent is typing...</Text>
</View>
)}
</ScrollView>
<View style={{ flexDirection: 'row', padding: 10 }}>
<TextInput
value={inputText}
onChangeText={setInputText}
placeholder="Type your message..."
style={{
flex: 1,
borderWidth: 1,
borderColor: '#ccc',
borderRadius: 20,
paddingHorizontal: 15,
paddingVertical: 10,
marginRight: 10
}}
/>
<TouchableOpacity
onPress={handleSendMessage}
disabled={!inputText.trim() || isLoading}
style={{
backgroundColor: inputText.trim() ? '#007AFF' : '#ccc',
paddingHorizontal: 20,
paddingVertical: 10,
borderRadius: 20
}}
>
<Text style={{ color: 'white' }}>Send</Text>
</TouchableOpacity>
</View>
</View>
);
};
export default CustomChatScreen;📚 API Reference
🪝 useReactNativeChat Hook
The main hook for integrating chat functionality into your React Native app.
const {
messages, // Array of chat messages
isLoading, // Loading state
error, // Error message
isTyping, // Typing indicator state
sendMessage, // Function to send messages
createSession, // Function to create chat session
endSession, // Function to end chat session
loadMessages, // Function to load messages
clearError, // Function to clear errors
clearHistory, // Function to clear conversation history
getHistory // Function to get conversation history
} = useReactNativeChat(apiConfig, options);⚙️ Configuration
interface ChatApiConfig {
unifiedApiKey: string; // EnkaliBridge unified API key (REQUIRED - get from EnkaliBridge API section)
baseUrl: string; // EnkaliBridge gateway URL (e.g., 'https://sdk.enkaliprime.com')
userId?: string; // Optional: User identifier
// Legacy options (not needed when using unifiedApiKey):
// widgetId?: string; // Auto-resolved from unifiedApiKey
// supabaseUrl?: string; // Auto-resolved from unifiedApiKey
// supabaseAnonKey?: string; // Auto-resolved from unifiedApiKey
}
interface UseChatOptions {
agentName?: string; // Name of the chat agent
agentAvatar?: string; // Avatar URL for the agent
metadata?: any; // Additional metadata
enableStreaming?: boolean; // Enable streaming responses
onError?: (error: string) => void; // Error callback
onSessionCreated?: (session: ChatSession) => void; // Session created callback
onMessageReceived?: (message: ChatMessage) => void; // Message received callback
onStreamingChunk?: (chunk: string) => void; // Streaming chunk callback
}📨 Message Types
interface ChatMessage {
id: string;
text: string;
isUser: boolean;
timestamp: string;
status: 'sending' | 'sent' | 'delivered' | 'read';
type?: 'text' | 'system' | 'quick_reply';
quickReplies?: string[];
sessionId: string;
userId?: string;
}
interface ChatSession {
id: string;
userId?: string;
agentName: string;
agentAvatar?: string;
isActive: boolean;
startTime: string;
endTime?: string;
metadata?: any;
}🔌 Connection Status
You can check the connection status to verify that your app is properly connected to the EnkaliBridge server. This is useful for displaying connection indicators in your UI.
📊 Connection Status Types
type ConnectionStatus = 'checking' | 'connected' | 'disconnected' | 'error';| Status | Description |
|--------|-------------|
| 🔄 checking | Currently checking the connection |
| ✅ connected | Successfully connected to the server |
| ❌ disconnected | Connection failed (network error) |
| ⚠️ error | Configuration or server error |
💡 Implementing Connection Status Check
Here's how to implement connection status checking in your app:
import React, { useState, useEffect } from 'react';
import { View, Text } from 'react-native';
import { useReactNativeChat } from '@enkaliprime/react-native-chat-sdk';
type ConnectionStatus = 'checking' | 'connected' | 'disconnected' | 'error';
const ChatScreen = () => {
const [connectionStatus, setConnectionStatus] = useState<ConnectionStatus>('checking');
const [statusMessage, setStatusMessage] = useState('Checking connection...');
const apiConfig = {
unifiedApiKey: 'ek_bridge_1763490675941_km8imacsz5',
baseUrl: 'https://sdk.enkaliprime.com',
userId: 'user_123'
};
const { sendMessage, createSession } = useReactNativeChat(apiConfig, {
agentName: 'Support Agent',
onMessageReceived: (message) => {
// Update status on successful message receive
setConnectionStatus((prev) => {
if (prev !== 'connected') {
setStatusMessage('Connected and ready');
return 'connected';
}
return prev;
});
},
});
// Test connection status
const checkConnection = async () => {
setConnectionStatus('checking');
setStatusMessage('Checking connection...');
try {
// Resolve unified API key first (if needed)
let widgetId = '';
let currentWorkerUrl = apiConfig.baseUrl;
// Resolve via Cloudflare Worker
const resolveResponse = await fetch(
`${currentWorkerUrl}/resolve?unified_api_key=${encodeURIComponent(apiConfig.unifiedApiKey)}`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
'X-EnkaliBridge-Key': apiConfig.unifiedApiKey,
},
}
);
if (resolveResponse.ok) {
const resolveData = await resolveResponse.json();
if (resolveData.success && resolveData.connection) {
widgetId = resolveData.connection.widgetId;
currentWorkerUrl = resolveData.connection.baseUrl;
}
}
// Test the chat endpoint
const chatUrl = `${currentWorkerUrl}/chat`;
const response = await fetch(chatUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-EnkaliBridge-Key': apiConfig.unifiedApiKey,
},
body: JSON.stringify({
message: 'test',
sessionId: `test-${Date.now()}`,
stream: false,
context: [],
}),
});
if (response.ok) {
setConnectionStatus('connected');
setStatusMessage('Connected and ready');
} else {
const errorText = await response.text();
setConnectionStatus('error');
setStatusMessage(`Error: ${response.status} - ${errorText.substring(0, 50)}`);
}
} catch (error: any) {
setConnectionStatus('disconnected');
setStatusMessage(`Connection failed: ${error.message || 'Network error'}`);
}
};
useEffect(() => {
// Check connection on mount
checkConnection();
// Create session when component mounts
createSession()
.then(() => {
if (connectionStatus === 'checking') {
setConnectionStatus('connected');
setStatusMessage('Connected and ready');
}
})
.catch((err) => {
setConnectionStatus('error');
setStatusMessage(`Session error: ${err.message}`);
});
}, []);
// Update status on successful message send
const handleSend = async (text: string) => {
try {
await sendMessage(text);
setConnectionStatus((prev) => {
if (prev !== 'connected') {
setStatusMessage('Connected and ready');
return 'connected';
}
return prev;
});
} catch (err: any) {
setConnectionStatus('error');
setStatusMessage(`Send failed: ${err.message || 'Network error'}`);
}
};
// Status indicator component
const getStatusColor = () => {
switch (connectionStatus) {
case 'connected':
return '#10b981'; // Green
case 'checking':
return '#f59e0b'; // Amber
case 'error':
return '#ef4444'; // Red
default:
return '#6b7280'; // Gray
}
};
return (
<View>
{/* Connection Status Indicator */}
<View style={{ flexDirection: 'row', alignItems: 'center', padding: 10 }}>
<View
style={{
width: 12,
height: 12,
borderRadius: 6,
backgroundColor: getStatusColor(),
marginRight: 8,
}}
/>
<Text>{statusMessage}</Text>
</View>
{/* Your chat UI */}
</View>
);
};✅ Connection Status Best Practices
- ✅ Check on Mount - Always check connection status when your component mounts
- ✅ Update on Success - Update status to 'connected' when messages are successfully sent/received
- ✅ Handle Errors - Set status to 'error' or 'disconnected' when operations fail
- ✅ Visual Feedback - Display a visual indicator (colored dot, icon) to show connection state
- ✅ Manual Retry - Provide a way for users to manually retry the connection check
- ✅ Auto-Retry - Consider implementing automatic retry logic for failed connections
🌐 API Endpoints
The SDK communicates with EnkaliBridge (Cloudflare Worker gateway) which handles:
| Endpoint | Method | Description |
|----------|--------|-------------|
| /resolve | GET | Resolves unified API key to connection details (automatic) |
| /functions/v1/chat | POST | Send message with RAG support (Knowledge Base retrieval) |
📝 Chat Endpoint Details
- Requires:
message,widgetId,sessionId,context(conversation history) - Supports: Streaming responses (SSE)
- Features: Automatically retrieves relevant knowledge base entries for better AI responses
- Security: All authentication handled securely by EnkaliBridge
🌉 EnkaliBridge
EnkaliBridge is a secure gateway that simplifies SDK integration:
| Feature | Benefit | |---------|---------| | 🔑 Unified API Key | Single key replaces multiple credentials | | 🛡️ Secure Gateway | Cloudflare Worker acts as a secure proxy | | ⚡ Automatic Resolution | Unified key resolves to all required connection details | | 🚀 Easy Setup | Just connect SDK to Widget and get your unified key |
🔄 How EnkaliBridge Works
┌─────────────┐ ┌──────────────┐ ┌─────────────┐
│ Your App │──────▶│ EnkaliBridge │──────▶│ Supabase │
│ (SDK) │◀──────│ Gateway │◀──────│ Backend │
└─────────────┘ └──────────────┘ └─────────────┘
│ │ │
│ Unified API Key │ Resolves Key │
│ (ek_bridge_...) │ to Credentials │
└──────────────────────┴──────────────────────┘- 🔗 You connect your SDK to a Widget in the EnkaliPrime dashboard
- 🔑 EnkaliBridge generates a unified API key for that connection
- 🔐 SDK uses the unified key to authenticate with the Cloudflare Worker gateway
- 🔄 Gateway resolves the key to get widget ID, Supabase URL, and handles authentication
- ✅ All API calls go through the secure gateway - no direct Supabase credentials needed
🤖 RAG (Retrieval-Augmented Generation)
The SDK includes RAG support for intelligent, context-aware responses:
| Feature | Description | |---------|-------------| | 📚 Knowledge Base Retrieval | Automatically retrieves relevant KB entries based on user questions | | 🧠 Context-Aware Responses | AI uses both your knowledge base and general knowledge | | 💬 Conversation History | Maintains context across multiple messages (last 10 messages) | | 🎯 Better Accuracy | Responses are more accurate and relevant to your business |
🔄 How RAG Works
User Message
│
▼
┌─────────────────┐
│ SDK Includes │
│ Conversation │
│ History │
│ (Last 10 msgs) │
└────────┬────────┘
│
▼
┌─────────────────┐
│ Backend │
│ Retrieves Top │
│ 5 KB Entries │
└────────┬────────┘
│
▼
┌─────────────────┐
│ AI Generates │
│ Response Using │
│ KB + Context │
└────────┬────────┘
│
▼
Response- 👤 User sends a message
- 📝 SDK includes conversation history (last 10 messages) as context
- 🔍 Backend retrieves top 5 most relevant knowledge base entries
- 🤖 AI generates response using both KB data and conversation context
- ✅ Response is returned with full context awareness
⚠️ Error Handling
The SDK includes comprehensive error handling:
const { error, clearError } = useReactNativeChat(apiConfig, {
onError: (error) => {
console.error('Chat error:', error);
Alert.alert('Connection Error', error);
}
});
// Clear errors manually
clearError();💡 Best Practices
1️⃣ EnkaliBridge Setup
- ✅ Required: Always provide
unifiedApiKeyin your config - 🔑 Get your unified API key from the EnkaliBridge API section after connecting SDK to Widget
- 🔄 The unified key automatically resolves to widget ID, Supabase URL, and credentials
- 🔒 No need to manually configure Supabase credentials - EnkaliBridge handles this securely
2️⃣ Session Management
- 🆕 Create a new session when the user opens the chat
- 🆔 Session IDs are automatically generated
- 💾 Conversation history is maintained per session
- 🚪 End sessions when the user closes the chat
3️⃣ Message Handling
- ⏳ Show loading states while sending messages
- 🚀 Implement optimistic updates for better UX
- 🛡️ Handle network errors gracefully
- 📝 Conversation history is automatically included for context
4️⃣ Knowledge Base
- 📚 Add knowledge base entries in the EnkaliPrime dashboard for your Widget
- 🤖 The AI will automatically use relevant entries when answering questions
- 📈 More KB entries = better, more accurate responses
- 🔗 Knowledge base is automatically linked through your EnkaliBridge unified API key
5️⃣ Performance
- 📊 Conversation history is limited to last 10 messages (automatic)
- ⚡ Use React.memo for message components
- ⌨️ Debounce typing indicators
- 🔄 Streaming is optional (set
enableStreaming: falsefor better performance)
6️⃣ Security
- 🔐 Store your EnkaliBridge unified API key securely (use environment variables)
- 🚫 Never expose your unified API key in client-side code or commit it to version control
- 🛡️ EnkaliBridge acts as a secure gateway - your Supabase credentials are never exposed to the client
- ✅ Validate user input before sending
📘 TypeScript Support
The SDK is written in TypeScript and includes full type definitions:
import { ChatMessage, ChatSession, ChatApiConfig } from '@enkaliprime/react-native-chat-sdk';🤝 Contributing
We welcome contributions! Please see our Contributing Guide for details.
📄 License
MIT License - see LICENSE file for details.
💬 Support
| Resource | Link | |----------|------| | 📚 Documentation | docs.enkaliprime.com/mobile-chat-api | | 🐛 Report Issues | GitHub Issues | | 💬 Community Support | GitHub Discussions |
📋 Changelog
🎉 Version 1.1.1
- 📚 Updated Documentation - Enhanced README with connection status guide and improved visual design
🎉 Version 1.1.0
- ✨ EnkaliBridge Integration - Unified API key authentication (recommended)
- ✨ RAG Support - Retrieval-Augmented Generation with Knowledge Base
- ✨ Streaming Responses - Optional real-time streaming support
- ✨ Conversation History - Automatic context management
- ✨ Secure Gateway - Cloudflare Worker gateway for secure credential management
- 🔧 Improved Error Handling - Better error messages and troubleshooting
- 📚 Updated Documentation - Complete EnkaliBridge usage guide
🎉 Version 1.0.0
- 🚀 Initial release
- ⚛️ React Native chat SDK
- 📘 TypeScript support
- 💬 Real-time messaging
- 🔄 Session management
- ⚠️ Error handling
Made with ❤️ by EnkaliPrime
