directivsys-sdk
v1.0.2
Published
A flexible React SDK for building intelligent conversational interfaces with LLM-powered agents
Downloads
282
Maintainers
Readme
DirectivSys SDK
A flexible React SDK for building intelligent conversational interfaces with LLM-powered agents.
Features
✨ Easy Integration - Get started in minutes with high-level components
🎨 Customizable Theming - Light, dark, and custom themes with full control
🔧 Flexible Architecture - Use pre-built components or build your own with hooks
🤖 Intelligent Context - Automatic context diffing and injection
⚡ Two-Step Orchestration - Seamless action execution and feedback loop
📦 TypeScript First - Full type safety and IntelliSense support
📈 Analytics Admin UI - Widgets, reports, and dashboards for AI-generated insights
📊 Business Intelligence Reports - 5 comprehensive REST endpoints for analytics (Executive Dashboard, Supply Chain Risk, Execution Audit Trail, Portfolio Health, Data Quality & Automation)
Installation
npm install directivsys-sdk
# or
yarn add directivsys-sdkGetting Started
Prerequisites
- React 16.8+ (hooks support)
- DirectivSys API key (obtain from your DirectivSys account dashboard)
Setup Your API Key
- Sign up at console.directivsys.io
- Create a new API key in Settings → API Keys
- Copy your API key and store it securely (use environment variables in production)
# .env.local
REACT_APP_DIRECTIVSYS_API_KEY=your_api_key_hereQuick Start
1. Wrap your app with the Provider
import { DirectivSysProvider } from 'directivsys-sdk';
function App() {
return (
<DirectivSysProvider apiKey="your-api-key">
<YourApp />
</DirectivSysProvider>
);
}2. Use the Chatbox Component
import { DirectivSysChatbox } from 'directivsys-sdk';
function ChatPage() {
const handleAction = async (toolCall) => {
// Execute your business logic
const results = await yourAPI.search(toolCall.parameters);
return {
status: 'success',
summary: `Found ${results.length} items`,
detailed_data: results
};
};
const currentContext = {
userId: 'user-123',
interfaceState: {
currentPageName: 'Products',
viewingItems: products
}
};
return (
<DirectivSysChatbox
onIntentDetected={handleAction}
currentContext={currentContext}
/>
);
}API Reference
<DirectivSysProvider />
Wraps your application and provides configuration.
Props:
| Prop | Type | Required | Description |
|------|------|----------|-------------|
| apiKey | string | Yes | Your DirectivSys API key |
| config | object | No | Additional configuration (baseURL, timeout, headers) |
| theme | Theme | No | Custom theme object |
| sttProvider | STTProvider | No | Custom speech-to-text provider |
| ttsProvider | TTSProvider | No | Custom text-to-speech provider |
Example:
<DirectivSysProvider
apiKey="your-key"
config={{
baseURL: 'https://your-api.com',
timeout: 30000
}}
theme={darkTheme}
>
<App />
</DirectivSysProvider><DirectivSysChatbox />
Full-featured chat interface component.
Props:
| Prop | Type | Required | Description |
|------|------|----------|-------------|
| onIntentDetected | function | Yes | Callback when LLM detects an action |
| currentContext | InterfaceState | Yes | Current user and page context |
| placeholder | string | No | Input placeholder text |
| height | string | No | Component height (default: '500px') |
| width | string | No | Component width (default: '100%') |
| theme | Partial<Theme> | No | Theme overrides |
| renderMessage | function | No | Custom message renderer |
| onError | function | No | Error handler |
| onSpeechStart | function | No | Called when voice input starts |
| onSpeechEnd | function | No | Called when voice input ends |
| onTranscript | function | No | Called with transcribed text |
| onAgentResponse | function | No | Called with agent response text |
<DirectivSysSearch />
Compact search bar component.
Props:
| Prop | Type | Required | Description |
|------|------|----------|-------------|
| onIntentDetected | function | Yes | Callback when LLM detects an action |
| currentContext | InterfaceState | Yes | Current user and page context |
| placeholder | string | No | Input placeholder text |
| width | string | No | Component width (default: '100%') |
| maxResults | number | No | Maximum results to show (default: 5) |
| theme | Partial<Theme> | No | Theme overrides |
| onError | function | No | Error handler |
| onSpeechStart | function | No | Called when voice input starts |
| onSpeechEnd | function | No | Called when voice input ends |
| onTranscript | function | No | Called with transcribed text |
| onAgentResponse | function | No | Called with agent response text |
useDirectivSys(options)
Core hook for building custom interfaces.
Parameters:
interface UseDirectivSysOptions {
onIntentDetected: (toolCall: ToolCall) => Promise<ToolResult>;
currentContext: CurrentContext;
onError?: (error: Error) => void;
onSpeechStart?: () => void; // Called when voice input starts
onSpeechEnd?: () => void; // Called when voice input ends
onTranscript?: (text: string) => void; // Called with transcribed text
onAgentResponse?: (response: string) => void; // Called with agent response
}Returns:
interface UseDirectivSysReturn {
messages: ChatMessage[];
isLoading: boolean;
error: Error | null;
isListening: boolean;
sendChatQuery: (query: string | { image?: File; document?: File; query?: string }) => Promise<void>;
clearMessages: () => void;
startVoiceInput: () => void;
stopVoiceInput: () => void;
}Example with Text Input:
import { useDirectivSys } from 'directivsys-sdk';
function CustomChat() {
const { messages, isLoading, sendChatQuery, error } = useDirectivSys({
onIntentDetected: handleAction,
currentContext: currentContext,
onError: (err) => console.error('Chat error:', err)
});
return (
<div>
{messages.map(msg => <Message key={msg.id} {...msg} />)}
{error && <div style={{ color: 'red' }}>{error.message}</div>}
<input
onKeyPress={(e) => e.key === 'Enter' && sendChatQuery(e.target.value)}
disabled={isLoading}
placeholder="Type your message..."
/>
</div>
);
}Example with Voice and Multimodal:
function AdvancedChat() {
const {
messages,
isLoading,
isListening,
sendChatQuery,
startVoiceInput,
stopVoiceInput
} = useDirectivSys({
onIntentDetected: handleAction,
currentContext: currentContext,
onSpeechStart: () => console.log('🎤 Listening...'),
onSpeechEnd: () => console.log('✓ Recorded'),
onTranscript: (text) => console.log('Transcribed:', text)
});
const handleImageUpload = (file: File) => {
sendChatQuery({ image: file, query: 'Analyze this image' });
};
return (
<div>
{messages.map(msg => <Message key={msg.id} {...msg} />)}
<button onClick={() => isListening ? stopVoiceInput() : startVoiceInput()}>
{isListening ? '⏹️ Stop' : '🎤 Voice'}
</button>
<ImageUpload onUpload={handleImageUpload} />
</div>
);
}How It Works
The SDK implements a two-step orchestration pattern:
- Intent Detection - Your query is analyzed to detect actions needed
- Action Execution - Your
onIntentDetectedcallback executes business logic - Response Generation - The LLM generates a natural language response
Context Diffing: The SDK automatically detects currentContext changes and injects them as system messages, allowing the LLM to adapt to UI state changes.
Analytics Suite
The SDK ships with DirectivSys analytics components for visualizing AI-generated metrics, observations, and directives and for executing recommended actions.
Components
AnalyticsWidget— Floating entry point that opens a drawer of analytics configs; best for adding analytics everywhere in your admin UI.AnalyticsReport— Full report view for a singleanalyticsType(metrics, observations, directives) with optional back/close controls.AnalyticsDashboard— Full-width dashboard that lists all analytics configs on the left and shows the selected report on the right. Supports manual refresh, optionalautoRefreshInterval, and directive status filtering.
import {
DirectivSysProvider,
AnalyticsWidget,
AnalyticsReport,
AnalyticsDashboard,
} from 'directivsys-sdk';
const handleDirectiveAction = async (directive, action) => {
if (action === 'decline') return { success: true };
// Execute the directive in your system
const result = await api.executeDirective(directive);
return { success: result.ok, error: result.error };
};
function Admin() {
return (
<DirectivSysProvider apiKey="your-api-key">
<AnalyticsWidget onDirectiveAction={handleDirectiveAction} />
<AnalyticsReport
analyticsType="InventoryHealth"
onDirectiveAction={handleDirectiveAction}
/>
<AnalyticsDashboard
onDirectiveAction={handleDirectiveAction}
autoRefreshInterval={300}
/>
</DirectivSysProvider>
);
}Directive actions: The callback receives the directive plus the requested action (execute or decline) and should return { success: boolean, error?: string }. On success, directive status becomes executed; failures become failed; declines become declined. Directive statuses are proposed, executed, declined, and failed. Priorities are numeric (higher = more urgent).
Analytics Hooks
useAnalyticsConfigs()— Fetches all analytics configs (configs,isLoading,error,refetch).useAnalyticsResult(analyticsType)— Fetches the latest result for a given analytics type (result,isLoading,error,refetch).useDirectiveAction(onDirectiveAction?)— Wraps your handler, updates directive status in the backend, and exposeshandleAction,isProcessing, anderror.
import { useAnalyticsConfigs, useAnalyticsResult, useDirectiveAction } from 'directivsys-sdk';
const { configs } = useAnalyticsConfigs();
const { result, refetch } = useAnalyticsResult('InventoryHealth');
const { handleAction, isProcessing } = useDirectiveAction(handleDirectiveAction);Analytics API Client
import { AnalyticsAPI } from 'directivsys-sdk';
const api = new AnalyticsAPI({ apiKey: 'your-api-key' });
const configs = await api.getConfigs();
const result = await api.getLatestResult('InventoryHealth');
await api.updateDirectiveStatus(directiveId, 'executed');More Docs
- Detailed components and hooks: ANALYTICS_README.md
- Full dashboard guide: ANALYTICS_DASHBOARD_README.md
Business Intelligence Reports
The SDK includes 5 comprehensive REST endpoints for investor-ready analytics with date range filtering and 1-hour caching.
Available Reports
import {
DirectivSysProvider,
ExecutiveDashboard,
SupplyChainRisk,
ExecutionAuditTrail,
PortfolioHealth,
DataQualityAutomation
} from 'directivsys-sdk';
function ReportsPage() {
return (
<DirectivSysProvider apiKey="your-api-key">
{/* High-level metrics and trends */}
<ExecutiveDashboard />
{/* Supply chain risk analysis */}
<SupplyChainRisk />
{/* Execution history and audit */}
<ExecutionAuditTrail />
{/* Portfolio metric health */}
<PortfolioHealth />
{/* Data quality & automation opportunities */}
<DataQualityAutomation />
</DirectivSysProvider>
);
}Reports via Hooks
import { useDirectivSysContext } from 'directivsys-sdk';
function CustomReport() {
const { api } = useDirectivSysContext();
// Fetch Executive Dashboard
const dashboard = await api.getExecutiveDashboard({
startDate: '2026-01-06',
endDate: '2026-02-05'
});
// Fetch Supply Chain Risk
const risk = await api.getSupplyChainRisk();
// Fetch Execution Audit with filter
const audit = await api.getExecutionAuditTrail({
directiveType: 'inventory-rebalance'
});
// Fetch Portfolio Health
const health = await api.getPortfolioHealth();
// Fetch Data Quality Assessment
const quality = await api.getDataQualityAutomation();
}Reports Documentation
- Full API reference: REPORTS_API.md
- Provider pattern guide: REPORTS_PROVIDER_PATTERN.md
Authentication
All reports use X-API-Key header authentication. Simply pass your API key to DirectivSysProvider and it's automatically used by all endpoints:
<DirectivSysProvider apiKey="your-api-key-here">
<YourReportsApp />
</DirectivSysProvider>Voice Input/Output
The SDK supports voice input (Speech-to-Text) and voice output (Text-to-Speech) for a fully conversational experience.
Default Providers
By default, the SDK uses browser Web Speech APIs:
- STT:
WebSpeechSTTProvider(SpeechRecognition) - TTS:
WebSpeechTTSProvider(speechSynthesis)
Custom Providers
You can swap providers for advanced implementations:
import { DirectivSysProvider, WebSpeechSTTProvider, WebSpeechTTSProvider } from 'directivsys-sdk';
// Custom STT Provider
class MySTTProvider {
startRecognition() { /* ... */ }
stopRecognition() { /* ... */ }
onResult(callback: (text: string) => void) { /* ... */ }
}
// Custom TTS Provider
class MyTTSProvider {
speak(text: string) { /* ... */ }
}
<DirectivSysProvider
apiKey="your-key"
sttProvider={new MySTTProvider()}
ttsProvider={new MyTTSProvider()}
>
<App />
</DirectivSysProvider>Voice Events
const { startVoiceInput, stopVoiceInput, isListening } = useDirectivSys({
onIntentDetected: handleAction,
currentContext: context,
onSpeechStart: () => console.log('Voice input started'),
onSpeechEnd: () => console.log('Voice input ended'),
onTranscript: (text) => console.log('Transcribed:', text),
onAgentResponse: (response) => console.log('Agent responded:', response),
});Chatbox with Voice
The DirectivSysChatbox includes a microphone button next to the text input:
<DirectivSysChatbox
onIntentDetected={handleAction}
currentContext={context}
/>- Click the mic button to start/stop voice recording
- Transcribed text is automatically sent to the API
- Agent responses are spoken aloud
Common Patterns & Best Practices
Error Handling
Always implement error handlers to gracefully manage failures:
const { error, sendChatQuery } = useDirectivSys({
onIntentDetected: async (toolCall) => {
try {
const result = await executeYourBusinessLogic(toolCall);
return { status: 'success', summary: `Completed: ${result.count} items` };
} catch (err) {
console.error('Tool execution failed:', err);
return {
status: 'error',
summary: `Failed to process request: ${err.message}`
};
}
},
currentContext: currentContext,
onError: (error) => {
// Handle SDK-level errors (network, API, etc)
showErrorNotification(error.message);
}
});Multimodal Input Pattern
Combine text, voice, images, and documents:
function MultimodalChat() {
const { sendChatQuery, isLoading } = useDirectivSys({...});
return (
<div>
{/* Text input */}
<input
onSubmit={(q) => sendChatQuery(q)}
disabled={isLoading}
/>
{/* Voice input */}
<VoiceButton onVoice={() => startVoiceInput()} />
{/* File uploads */}
<FileInput
onFile={(file) => {
if (file.type.startsWith('image/')) {
sendChatQuery({ image: file, query: 'Analyze this' });
} else {
sendChatQuery({ document: file, query: 'Process this' });
}
}}
/>
</div>
);
}Session Persistence
Sessions are maintained automatically. Clear when needed:
const { clearMessages } = useDirectivSys({...});
// Start fresh conversation
<button onClick={clearMessages}>New Conversation</button>Understanding Key Concepts
InterfaceState vs CurrentContext
interfaceState- Describes your application UI (current page, items being viewed)CurrentContext- Wraps all user and interface information for the LLM
const currentContext: CurrentContext = {
userId: 'user-123',
userName: 'John Seller', // Optional
userPreferences: 'Prefers bulk operations', // Optional
userRecentActivity: 'Uploaded 50 products', // Optional
interfaceState: {
currentPageName: 'ProductList',
currentPageUrl: '/products/list',
viewingItems: [{ id: 'P1', name: 'Widget', type: 'product', price: 29.99 }]
}
};Tool Call Execution Contract
The onIntentDetected callback is the bridge between the LLM and your business logic:
// What you receive
type ToolCall = {
toolName: string; // e.g., "searchProducts" or "addToCart"
parameters: Record<string, any>; // LLM-detected parameters
isSequential?: boolean; // True for chained tool calls
};
// What you must return
type ToolResult = {
status: 'success' | 'error' | 'partial';
summary: string; // Brief natural language summary for LLM
detailed_data?: any; // Extra data for context (previews, stats)
};Example:
const handleAction = async (toolCall) => {
if (toolCall.toolName === 'searchProducts') {
try {
const results = await executeYourBusinessLogic(toolCall);
return {
status: 'success',
summary: `Found ${results.length} matching products`,
detailed_data: { total: results.length, items: results.slice(0, 3) }
};
} catch (error) {
return {
status: 'error',
summary: `Search failed: ${error.message}`
};
}
}
return { status: 'error', summary: 'Unknown tool' };
};Theming
Built-in Themes
import { lightTheme, darkTheme } from 'directivsys-sdk';
<DirectivSysProvider theme={darkTheme}>
<App />
</DirectivSysProvider>Custom Theme
import { lightTheme } from 'directivsys-sdk';
import type { Theme } from 'directivsys-sdk';
const myTheme: Theme = {
...lightTheme,
colors: {
...lightTheme.colors,
primary: '#ff6b6b',
background: '#f8f9fa'
},
fontSizes: {
...lightTheme.fontSizes,
md: '18px',
lg: '22px'
},
spacing: {
...lightTheme.spacing,
md: '20px'
}
};
<DirectivSysProvider theme={myTheme}>
<App />
</DirectivSysProvider>Theme Structure
interface Theme {
name: string;
colors: {
primary: string;
secondary: string;
background: string;
surface: string;
text: string;
textSecondary: string;
border: string;
error: string;
success: string;
};
spacing: {
xs: string;
sm: string;
md: string;
lg: string;
xl: string;
};
fontSizes: {
xs: string;
sm: string;
md: string;
lg: string;
xl: string;
};
borderRadius: string;
boxShadow: string;
}Action Execution Contract
The onIntentDetected callback is where you implement your business logic.
Input: ToolCall
interface ToolCall {
toolName: string; // e.g., "searchProducts"
parameters: Record<string, any>; // e.g., { category: "t-shirts" }
}Output: ToolResult
interface ToolResult {
status: 'success' | 'error' | 'partial';
summary: string; // Natural language summary for LLM
detailed_data?: any; // Optional data preview
}Example Implementation
const onIntentDetected = async (toolCall) => {
switch (toolCall.toolName) {
case 'searchProducts':
try {
const results = await api.searchProducts(toolCall.parameters);
return {
status: 'success',
summary: `Found ${results.length} products`,
detailed_data: { total: results.length, preview: results.slice(0, 3) }
};
} catch (error) {
return {
status: 'error',
summary: `Search failed: ${error.message}`
};
}
case 'addToCart':
const cart = await api.addToCart(
toolCall.parameters.productId,
toolCall.parameters.quantity
);
return {
status: 'success',
summary: `Added to cart. Total: $${cart.total}`
};
default:
return {
status: 'error',
summary: `Unknown action: ${toolCall.toolName}`
};
}
};Context Management
The SDK automatically manages context changes and injects them as system messages.
interface CurrentContext {
userId: string;
userName?: string;
userPreferences?: string;
userRecentActivity?: string;
interfaceState: {
currentPageName: string;
currentPageUrl?: string;
currentPageDescription?: string;
viewingItems?: Array<{
id: string;
name: string;
type: string;
price: number;
description?: string;
characteristics?: string;
}>;
};
}Example:
const currentContext = {
userId: 'user-123',
userName: 'John Doe',
userPreferences: 'Prefers eco-friendly products',
interfaceState: {
currentPageName: 'Products',
currentPageUrl: '/products/t-shirts',
viewingItems: [
{
id: 'SKU-001',
name: 'Organic Cotton Tee',
type: 't-shirt',
price: 15.99,
description: '100% organic cotton'
}
]
}
};TypeScript Support
The SDK is written in TypeScript and provides full type definitions.
import type {
ToolCall,
ToolResult,
InterfaceState,
CurrentContext,
ChatMessage,
Theme,
UseDirectivSysOptions,
UseDirectivSysReturn,
DirectivSysConfig
} from 'directivsys-sdk';Troubleshooting
Common Issues
| Issue | Solution |
|-------|----------|
| "useDirectivSys must be used within DirectivSysProvider" | Ensure your component is wrapped by <DirectivSysProvider> in a parent component |
| Voice input not working | Check browser notification permissions and ensure HTTPS is enabled (required by Web Speech API) |
| Tool calls not executing | Verify onIntentDetected is implemented and properly returns a ToolResult object |
| Context not updating | Ensure you're passing a new currentContext object (not mutating existing one) |
| Slow responses | Check network tab for API latency; consider increasing timeout in config |
| Multimodal inputs failing | Ensure sendChatQuery is called with correct file type and optional query text |
Debug Mode
Enable console logging for debugging:
<DirectivSysProvider
apiKey={apiKey}
config={{
timeout: 60000, // Increase timeout for slow networks
baseURL: process.env.REACT_APP_API_URL // Use custom API endpoint if needed
}}
>
{/* Your app */}
</DirectivSysProvider>Monitor SDK state in your custom hook:
const { messages, error, isLoading, isListening } = useDirectivSys({...});
useEffect(() => {
console.log('Messages:', messages);
console.log('Loading:', isLoading);
console.log('Error:', error);
console.log('Listening:', isListening);
}, [messages, isLoading, error, isListening]);Examples
See the /examples directory for complete implementations:
- E-commerce Demo - Full shopping experience with product search, filtering, and cart management
- Custom UI - Building your own interface using the core hook
- Theming - Examples of custom themes and styling
- Voice Chat - Implementing voice input/output
- Multimodal - Processing images and documents alongside text
- Advanced Analytics - Integrating analytics and reports
Performance Tips
- Memoize callbacks - Use
useCallbackforonIntentDetectedand other handlers - Batch context updates - Don't update context on every keystroke; batch updates
- Optimize re-renders - Use
React.memofor message components - Lazy load components - Load analytics/report components only when needed
- Enable caching - Reports auto-cache for 1 hour; leverage this in UX
const onIntentDetected = useCallback(async (toolCall) => {
// Your implementation
}, [dependencies]); // Include all external dependenciesLicense
MIT
Support
- Documentation: https://github.com/MrWest/directivsys-sdk
- Issues: https://github.com/MrWest/directivsys-sdk/issues
Built with ❤️ by the DirectivSys team
