@volkansuner/aichat-react-native
v0.1.6
Published
AI-powered chat SDK for React Native with intelligent navigation and hybrid AI processing
Maintainers
Readme
AIChatSDK for React Native
AI-powered conversational interface for React Native applications with intelligent navigation and hybrid AI processing.
Note: This SDK connects to a backend API at
http://37.27.189.40:3001/api/v1by default. You can override this with your own backend URL.
📦 Installation
npm install @volkansuner/aichat-react-native
# or
yarn add @volkansuner/aichat-react-native
# or
pnpm add @volkansuner/aichat-react-nativePeer Dependencies
# Sadece AsyncStorage gerekli (axios kaldırıldı, native fetch kullanılıyor)
npm install react-native @react-navigation/native @react-native-async-storage/async-storage🚀 Quick Start
1. Initialize SDK
import { AIChatSDK } from '@volkansuner/aichat-react-native';
import { NavigationContainer } from '@react-navigation/native';
import { useNavigationContainerRef } from '@react-navigation/native';
function App() {
const navigationRef = useNavigationContainerRef();
useEffect(() => {
const initSDK = async () => {
const sdk = AIChatSDK.getInstance();
await sdk.initialize({
apiKey: 'your-api-key-here',
navigationRef,
enableLocalAI: true,
onStatusChange: (status) => {
console.log('SDK Status:', status);
},
onNavigationSuggest: (suggestion) => {
console.log('Navigate to:', suggestion.screenName);
},
});
};
initSDK();
}, []);
return (
<NavigationContainer ref={navigationRef}>
{/* Your navigation */}
</NavigationContainer>
);
}2. Send Messages
import { getSDK } from '@volkansuner/aichat-react-native';
async function handleUserMessage(message: string) {
const sdk = getSDK();
try {
const response = await sdk.sendMessage(message);
console.log('AI Response:', response.message);
console.log('Handled by:', response.handledBy); // 'local' or 'backend'
console.log('Confidence:', response.confidence);
if (response.navigationSuggestion) {
// AI suggested navigation
console.log('Suggested screen:', response.navigationSuggestion.screenName);
}
} catch (error) {
console.error('Error:', error);
}
}3. Access Conversation History
const sdk = getSDK();
const history = await sdk.getConversationHistory();
console.log('Messages:', history);🎯 Features
Hybrid AI Processing
The SDK uses a two-tier AI system:
Local AI (DistilBERT via ONNX Runtime)
- Handles simple intents locally (<150ms)
- Confidence threshold: 0.85
- Intents: Navigate, Search, Action, General
- Works offline
Backend AI (GPT-4 Turbo via API)
- Complex conversations
- Context-aware responses
- Navigation schema integration
- Fallback for low-confidence local results
// Example: High-confidence local handling
User: "Go to settings"
→ Local AI (confidence: 0.92) → Navigate to Settings
// Example: Low-confidence → backend fallback
User: "Show me products under $50 in electronics category"
→ Local AI (confidence: 0.65) → Backend API → Complex responseNavigation Intelligence
// User asks: "Show me my profile"
const response = await sdk.sendMessage("Show me my profile");
if (response.navigationSuggestion) {
// Automatically navigate
sdk.navigate(response.navigationSuggestion.screenName);
}Conversation Management
const sdk = getSDK();
// Get history
const history = await sdk.getConversationHistory();
// Clear conversation
await sdk.clearConversation();
// Get status
const status = sdk.getStatus(); // 'uninitialized' | 'initializing' | 'ready' | 'error'📚 API Reference
AIChatSDK.initialize(config)
Initialize the SDK with configuration.
interface SDKConfig {
apiKey: string; // Required: Your API key
apiUrl?: string; // Optional: Custom API URL
enableLocalAI?: boolean; // Optional: Enable local AI (default: true)
navigationRef?: NavigationContainerRef; // Optional: React Navigation ref
localAI?: {
confidenceThreshold?: number; // Default: 0.85
};
onStatusChange?: (status) => void; // Optional: Status callback
onNavigationSuggest?: (suggestion) => void; // Optional: Navigation callback
onError?: (error) => void; // Optional: Error callback
}sdk.sendMessage(message: string)
Send a chat message and get AI response.
const response = await sdk.sendMessage("Hello");
interface ChatResponse {
id: string;
message: string;
timestamp: Date;
handledBy: 'local' | 'backend';
confidence?: number;
tokensUsed?: number;
navigationSuggestion?: {
screenName: string;
confidence: number;
message: string;
};
}sdk.getConversationHistory()
Get conversation history.
const history = await sdk.getConversationHistory();
// Returns: ChatMessage[]sdk.clearConversation()
Clear conversation history and start new session.
await sdk.clearConversation();sdk.navigate(screenName: string, params?: any)
Programmatically navigate to a screen.
sdk.navigate('Profile', { userId: '123' });sdk.getStatus()
Get current SDK status.
const status = sdk.getStatus();
// Returns: 'uninitialized' | 'initializing' | 'ready' | 'error'🔧 Configuration Examples
Basic Setup
await sdk.initialize({
apiKey: 'aichat_test_pk_...',
});With Navigation
const navigationRef = useNavigationContainerRef();
await sdk.initialize({
apiKey: 'aichat_test_pk_...',
navigationRef,
onNavigationSuggest: (suggestion) => {
Alert.alert(
'Navigate?',
`Do you want to go to ${suggestion.screenName}?`,
[
{ text: 'Cancel', style: 'cancel' },
{ text: 'Go', onPress: () => sdk.navigate(suggestion.screenName) },
]
);
},
});Backend-Only Mode
await sdk.initialize({
apiKey: 'aichat_test_pk_...',
enableLocalAI: false, // Disable local AI, always use backend
});Custom API URL
// Default API URL: http://37.27.189.40:3001/api/v1
// You can override it with your own backend:
await sdk.initialize({
apiKey: 'aichat_test_pk_...',
apiUrl: 'https://your-custom-api.com/v1',
});💬 Usage Examples
Simple Chat
import React, { useState } from 'react';
import { View, TextInput, Button, Text } from 'react-native';
import { getSDK } from '@volkansuner/aichat-react-native';
function ChatScreen() {
const [message, setMessage] = useState('');
const [response, setResponse] = useState('');
const sendMessage = async () => {
const sdk = getSDK();
const result = await sdk.sendMessage(message);
setResponse(result.message);
setMessage('');
};
return (
<View>
<TextInput
value={message}
onChangeText={setMessage}
placeholder="Type a message..."
/>
<Button title="Send" onPress={sendMessage} />
<Text>{response}</Text>
</View>
);
}With History
import React, { useState, useEffect } from 'react';
import { FlatList, Text } from 'react-native';
import { getSDK } from '@volkansuner/aichat-react-native';
function ChatHistory() {
const [messages, setMessages] = useState([]);
useEffect(() => {
loadHistory();
}, []);
const loadHistory = async () => {
const sdk = getSDK();
const history = await sdk.getConversationHistory();
setMessages(history);
};
return (
<FlatList
data={messages}
keyExtractor={(item) => item.id}
renderItem={({ item }) => (
<Text>{item.role}: {item.text}</Text>
)}
/>
);
}Navigation Integration
const sdk = getSDK();
// User asks: "Take me to my orders"
const response = await sdk.sendMessage("Take me to my orders");
if (response.navigationSuggestion) {
// Option 1: Auto-navigate
sdk.navigate(response.navigationSuggestion.screenName);
// Option 2: Ask user first
Alert.alert(
'Navigation',
response.navigationSuggestion.message,
[
{ text: 'Cancel' },
{
text: 'Go',
onPress: () => sdk.navigate(response.navigationSuggestion.screenName)
},
]
);
}🎨 Best Practices
1. Initialize Early
Initialize SDK in your root component:
function App() {
useEffect(() => {
const init = async () => {
const sdk = AIChatSDK.getInstance();
await sdk.initialize({ apiKey: process.env.AICHAT_API_KEY });
};
init();
}, []);
}2. Handle Errors
try {
const response = await sdk.sendMessage(message);
} catch (error) {
if (error.message.includes('Invalid API key')) {
// Handle auth error
} else if (error.message.includes('Rate limit')) {
// Handle rate limit
} else {
// Handle other errors
}
}3. Provide Feedback
const [loading, setLoading] = useState(false);
const send = async () => {
setLoading(true);
try {
const response = await sdk.sendMessage(message);
// Handle response
} finally {
setLoading(false);
}
};4. Navigation Confirmation
Always ask user before navigating:
if (response.navigationSuggestion) {
// ✅ Good: Ask first
const confirmed = await showConfirmDialog(
`Go to ${response.navigationSuggestion.screenName}?`
);
if (confirmed) {
sdk.navigate(response.navigationSuggestion.screenName);
}
// ❌ Bad: Auto-navigate without confirmation
// sdk.navigate(response.navigationSuggestion.screenName);
}🔄 Hybrid AI Flow
User Message
↓
Local AI Classifier (DistilBERT)
↓
Confidence ≥ 0.85?
↓
YES → Handle Locally (fast, offline)
↓
NO → Send to Backend (GPT-4, context-aware)
↓
Navigation Suggestion?
↓
YES → Suggest screen navigation
↓
Return Response📊 Performance
- Local AI: < 150ms response time
- Backend API: < 2s response time
- Model Size: 20MB (DistilBERT quantized)
- Memory Usage: ~50MB additional
🛠️ Troubleshooting
SDK not initializing
// Check status
const status = sdk.getStatus();
console.log('Status:', status);
// Reinitialize if error
if (status === 'error') {
await sdk.destroy();
await sdk.initialize(config);
}Navigation not working
// Make sure navigationRef is passed
const navigationRef = useNavigationContainerRef();
await sdk.initialize({
apiKey: '...',
navigationRef, // ← Important!
});Local AI not loading
// Check if local AI is enabled
await sdk.initialize({
apiKey: '...',
enableLocalAI: true, // Make sure this is true
localAI: {
confidenceThreshold: 0.85,
},
});📝 TypeScript Support
Fully typed with TypeScript:
import type {
SDKConfig,
ChatMessage,
ChatResponse,
NavigationSuggestion,
} from '@volkansuner/aichat-react-native';🔗 Related
📄 License
MIT
