@smartlabormanagement/smartee
v0.1.1
Published
A standalone, dependency-free chat engine with streaming support for web and React Native
Downloads
4
Maintainers
Readme
@smartlabormanagement/smartee
A standalone, dependency-free AI chat engine with Server-Sent Events (SSE) streaming support for web and React Native applications.
Features
- 🚀 Zero dependencies
- 📱 React Native compatible
- 🔄 Real-time SSE streaming for AI responses
- 🤖 Built for AI assistant conversations (like ChatGPT/Claude)
- 🛠️ Tool execution support
- 📡 Event-driven architecture
- 💬 Text chunk buffering for smooth display
- 🔌 Abort/cancel support
- 📦 TypeScript support
- 🌐 Works in both browser and Node.js environments
Installation
npm install @smartlabormanagement/smarteeUsage
Basic Setup
import { ChatEngine } from '@smartlabormanagement/smartee';
const chatEngine = new ChatEngine({
apiUrl: 'https://api.example.com/v3',
authToken: 'your-auth-token',
debug: true,
onAuthError: () => {
// Handle authentication errors
console.log('Authentication failed');
},
});
// Create a conversation
const conversation = await chatEngine.createConversation('My Chat');
// Send a message
await chatEngine.sendMessage('Hello, AI assistant!');Handling Streaming Responses
// Listen for streaming events
chatEngine.on('stream:start', (data) => {
console.log('Stream started');
});
chatEngine.on('stream:userMessage', (message) => {
console.log('User said:', message.content);
});
chatEngine.on('stream:assistantStart', (message) => {
console.log('Assistant is typing...');
});
chatEngine.on('stream:textChunk', ({ messageId, text }) => {
// Update your UI with the streaming text
updateMessageInUI(messageId, text);
});
chatEngine.on('stream:complete', (data) => {
console.log('Response complete');
});
chatEngine.on('stream:error', (error) => {
console.error('Stream error:', error);
});Tool Execution
// Listen for tool execution events
chatEngine.on('stream:toolUse', (data) => {
console.log(`Tool ${data.name} invoked with:`, data.input);
});
chatEngine.on('stream:toolExecutionStart', (data) => {
console.log(`Executing tool: ${data.toolName}`);
});
chatEngine.on('stream:toolExecutionComplete', (data) => {
console.log(`Tool ${data.toolId} completed with result:`, data.result);
});
// Handle confirmation requests
chatEngine.on('stream:confirmationRequired', async (data) => {
const userConfirmed = await showConfirmationDialog(data.confirmationData);
await chatEngine.confirmToolExecution(data.confirmationData.id, userConfirmed);
});Aborting Streams
// Start a message
const messagePromise = chatEngine.sendMessage('Tell me a long story...');
// Abort if needed
chatEngine.abort();
// The promise will reject with an abort error
try {
await messagePromise;
} catch (error) {
if (error.name === 'AbortError') {
console.log('Stream was aborted');
}
}API Reference
ChatEngine
Constructor Options
interface ChatEngineConfig {
apiUrl: string; // Base API URL
authToken?: string | (() => string | Promise<string>); // Auth token or getter
conversationId?: string | number; // Initial conversation ID
onAuthError?: () => void; // Called on auth errors
debug?: boolean; // Enable debug logging
}Methods
createConversation(title?: string): Promise<Conversation>- Create a new conversationsendMessage(content: string, conversationId?: string | number): Promise<void>- Send a message and stream the responseconfirmToolExecution(confirmationId: string, confirmed: boolean, conversationId?: string | number): Promise<any>- Confirm or reject tool executionabort(): void- Abort the current streamgetMessages(): Message[]- Get all messages in memoryclearMessages(): void- Clear message historygetCurrentConversationId(): string | number | null- Get current conversation IDsetCurrentConversationId(id: string | number): void- Set current conversation IDdestroy(): void- Clean up resources
Events
stream:start- Stream startedstream:userMessage- User message addedstream:assistantStart- Assistant message startedstream:assistantContinuationStart- Assistant continuing previous messagestream:textChunk- Text chunk receivedstream:toolUse- Tool invokedstream:toolExecutionStart- Tool execution startedstream:toolExecutionComplete- Tool execution completedstream:confirmationRequired- Confirmation needed for toolstream:complete- Stream completed successfullystream:error- Stream error occurredstream:abort- Stream was aborted
Testing
Run Tests
# Run mock server (in one terminal)
npm run test:mock
# Run tests (in another terminal)
npm test
# Or test in browser
npm run test:browserUsing the Mock Server
The package includes a mock SSE server for testing:
npm run test:mockThis starts a server on http://localhost:3000 that simulates AI chat streaming responses.
React Native Support
The library uses only JavaScript standard APIs and has no DOM dependencies, making it fully compatible with React Native.
// In React Native
import { ChatEngine } from '@smartlabormanagement/smartee';
// Use exactly the same as in web
const chatEngine = new ChatEngine({
apiUrl: 'https://api.example.com/v3',
authToken: await getAuthToken(),
});License
MIT
