reactbridge-sdk
v0.1.21
Published
A flexible React SDK for building intelligent conversational interfaces with LLM-powered agents
Maintainers
Readme
ReactBridge 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
Installation
npm install reactbridge-sdk
# or
yarn add reactbridge-sdkQuick Start
1. Wrap your app with the Provider
import { ReactBridgeProvider } from 'reactbridge-sdk';
function App() {
return (
<ReactBridgeProvider apiKey="your-api-key">
<YourApp />
</ReactBridgeProvider>
);
}2. Use the Chatbox Component
import { ReactBridgeChatbox } from 'reactbridge-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 interfaceState = {
userId: 'user-123',
currentContext: {
currentPageName: 'Products',
viewingItems: products
}
};
return (
<ReactBridgeChatbox
onIntentDetected={handleAction}
currentContext={interfaceState}
/>
);
}API Reference
<ReactBridgeProvider />
Wraps your application and provides configuration.
Props:
| Prop | Type | Required | Description |
|------|------|----------|-------------|
| apiKey | string | Yes | Your ReactBridge 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:
<ReactBridgeProvider
apiKey="your-key"
config={{
baseURL: 'https://your-api.com',
timeout: 30000
}}
theme={darkTheme}
>
<App />
</ReactBridgeProvider><ReactBridgeChatbox />
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 |
<ReactBridgeSearch />
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 |
useReactBridge(options)
Core hook for building custom interfaces.
Parameters:
interface UseReactBridgeOptions {
onIntentDetected: (toolCall: ToolCall) => Promise<ToolResult>;
currentContext: InterfaceState;
onError?: (error: Error) => void;
}Returns:
interface UseReactBridgeReturn {
messages: ChatMessage[];
isLoading: boolean;
sendChatQuery: (query: string) => Promise<void>;
clearMessages: () => void;
error: Error | null;
}Example:
import { useReactBridge } from 'reactbridge-sdk';
function CustomChat() {
const { messages, isLoading, sendChatQuery } = useReactBridge({
onIntentDetected: handleAction,
currentContext: interfaceState
});
return (
<div>
{messages.map(msg => <Message key={msg.id} {...msg} />)}
<input onSubmit={(q) => sendChatQuery(q)} disabled={isLoading} />
</div>
);
}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 { ReactBridgeProvider, WebSpeechSTTProvider, WebSpeechTTSProvider } from 'reactbridge-sdk';
// Custom STT Provider
class MySTTProvider {
startRecognition() { /* ... */ }
stopRecognition() { /* ... */ }
onResult(callback: (text: string) => void) { /* ... */ }
}
// Custom TTS Provider
class MyTTSProvider {
speak(text: string) { /* ... */ }
}
<ReactBridgeProvider
apiKey="your-key"
sttProvider={new MySTTProvider()}
ttsProvider={new MyTTSProvider()}
>
<App />
</ReactBridgeProvider>Voice Events
const { startVoiceInput, stopVoiceInput, isListening } = useReactBridge({
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 ReactBridgeChatbox includes a microphone button next to the text input:
<ReactBridgeChatbox
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
Theming
Built-in Themes
import { lightTheme, darkTheme } from 'reactbridge-sdk';
<ReactBridgeProvider theme={darkTheme}>
<App />
</ReactBridgeProvider>Custom Theme
import { createCustomTheme, lightTheme } from 'reactbridge-sdk';
const myTheme = createCustomTheme(lightTheme, {
colors: {
primary: '#ff6b6b',
background: '#f8f9fa'
},
fontSizes: {
md: '18px',
lg: '22px'
},
spacing: {
md: '20px'
}
});
<ReactBridgeProvider theme={myTheme}>
<App />
</ReactBridgeProvider>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.tooName}`
};
}
};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,
ChatMessage,
Theme
} from 'reactbridge-sdk';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
License
MIT
Support
- Documentation: https://github.com/MrWest/react-bridge-sdk
- Issues: https://github.com/MrWest/react-bridge-sdk/issues
Built with ❤️ by the ReactBridge team
