@smarthivelabs-devs/ai-nexus-expo
v2.3.5
Published
Expo / React Native SDK for SmartHive AI Nexus with audio recording and voice calls
Readme
@smarthivelabs-devs/ai-nexus-expo
Expo and React Native SDK for AI Nexus text, audio, LiveKit voice agents, reliable realtime events, and optional structured native vision observations.
Realtime agent configuration
{
"expo": {
"plugins": [
["@smarthivelabs-devs/ai-nexus-expo/app.plugin", {
"vision": { "detectors": ["face", "object", "pose", "hand"] }
}]
]
}
}const agent = useVoiceAgent({
client,
agentId: "interviewer-v1",
behavior: "interviewer",
vision: { preset: "interview" },
});
await agent.connect();Expo Go reports reduced vision capability explicitly. Native analysis requires a development or production build with compatible native processors; audio conversation continues when vision is unavailable.
What this package is: A complete React Native SDK that includes and re-exports the shared AI Nexus client. LiveKit and the selected Expo audio implementation remain platform peer dependencies installed with expo install.
Requirements
- React Native ≥ 0.73 or Expo SDK ≥ 50
- The shared AI Nexus client is included and re-exported automatically
livekit-clientand the LiveKit React Native packages for realtime roomsexpo-audioorexpo-avfor the selected audio implementation
Installation
npm install @smarthivelabs-devs/ai-nexus-expo
npx expo install livekit-client @livekit/react-native @livekit/react-native-webrtc expo-audio
# Add this when using camera-to-server vision:
npx expo install expo-cameraThese packages are peer dependencies so the application controls native versions compatible with its Expo/React Native release.
Expo plugin and permissions
Use the SDK config plugin. It adds camera/photo permission descriptions, Android camera permission, autolinking metadata, and the selected detector configuration:
{
"expo": {
"plugins": [
["@smarthivelabs-devs/ai-nexus-expo/app.plugin", {
"vision": { "detectors": ["face", "object", "pose", "hand"] }
}]
],
"ios": {
"infoPlist": {
"NSMicrophoneUsageDescription": "Used for voice conversations with AI agents"
}
},
"android": {
"permissions": ["android.permission.RECORD_AUDIO"]
}
}
}Then create a native build:
npx expo prebuild
eas build --profile developmentFull native vision is unavailable in Expo Go. Always inspect visionCapabilities instead of assuming that detectors are running.
Bare React Native permissions
For bare React Native (non-Expo), add to ios/YourApp/Info.plist:
<key>NSMicrophoneUsageDescription</key>
<string>Used for voice conversations with AI agents</string>For Android, add to android/app/src/main/AndroidManifest.xml:
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />Environment Setup
# Keep this value only in the backend that serves your mobile application.
AI_NEXUS_API_KEY=nexus_live_xxxxxxxxxxxxxxxxxxxx
# Optional — staging or self-hosted instance
AI_NEXUS_BASE_URL=https://api.smarthivelabs.devDo not ship a permanent API key in a mobile bundle, including internal builds that may be distributed to testers. Point the SDK at an authenticated application backend that injects the key. Realtime session responses then contain the short-lived, scoped LiveKit and resume credentials used by the call.
// The permanent AI_NEXUS_API_KEY exists only at yourapi.com.
const nexus = new AiNexus({ apiKey: 'mobile-client', baseUrl: 'https://yourapi.com/nexus' });Initialize LiveKit once
Call setupLiveKitGlobals() before rendering any realtime hook, normally in the root layout module:
// app/_layout.tsx
import { setupLiveKitGlobals } from "@smarthivelabs-devs/ai-nexus-expo";
setupLiveKitGlobals();
export default function RootLayout() {
return <Slot />;
}Quick Start
import { AiNexus, useChat } from '@smarthivelabs-devs/ai-nexus-expo';
const nexus = new AiNexus({
apiKey: 'mobile-client',
baseUrl: 'https://yourapi.com/nexus',
});
export function ChatScreen() {
const { messages, isLoading, append } = useChat({
client: nexus,
model: 'aeon',
});
return (
<View>
<FlatList
data={messages}
keyExtractor={(_, i) => String(i)}
renderItem={({ item }) => (
<Text>{item.role}: {String(item.content)}</Text>
)}
/>
{isLoading && <ActivityIndicator />}
<Button title="Send" onPress={() => append('Hello!')} />
</View>
);
}Hook: useChat
Streaming chat with real-time token-by-token rendering.
import { useChat } from '@smarthivelabs-devs/ai-nexus-expo';
function ChatScreen() {
const [input, setInput] = useState('');
const { messages, isLoading, error, append, stop, setMessages } = useChat({
client: nexus, // AiNexus instance
model: 'aeon',
// Optional — tried in order if 'aeon' fails
fallbackModels: ['solaris', 'prism'],
// Optional — prepended as the system message on every request
systemPrompt: 'You are a helpful mobile assistant. Keep answers concise.',
onFinish: (msg) => console.log('Response complete:', msg.content),
onError: (err) => console.error('Chat error:', err.message),
});
return (
<KeyboardAvoidingView behavior="padding">
<FlatList
data={messages}
keyExtractor={(_, i) => String(i)}
renderItem={({ item }) => (
<View style={item.role === 'user' ? styles.userBubble : styles.agentBubble}>
<Text>{String(item.content)}</Text>
</View>
)}
/>
{isLoading && <Text>Thinking...</Text>}
{error && <Text style={styles.error}>{error.message}</Text>}
<View style={styles.inputRow}>
<TextInput value={input} onChangeText={setInput} placeholder="Type a message..." />
<Button title="Send" onPress={() => { append(input); setInput(''); }} disabled={isLoading} />
<Button title="Stop" onPress={stop} disabled={!isLoading} />
</View>
</KeyboardAvoidingView>
);
}Options:
| Option | Type | Description |
|--------|------|-------------|
| client | AiNexus | Required. The AI Nexus client instance. |
| model | string | Required. Model profile slug to use. |
| fallbackModels | string[]? | Ordered fallback profile slugs tried if the primary model fails. |
| systemPrompt | string? | Prepended as a system message. |
| onFinish | (msg: ChatMessage) => void | Called when the assistant finishes streaming. |
| onError | (err: Error) => void | Called on any error. |
Returns: { messages, isLoading, error, append(content), stop(), setMessages }
Hook: useVoiceAgent (recommended)
useVoiceAgent owns the complete mobile voice experience: Nexus session creation, LiveKit connection, native voice audio routing, microphone state, client tools, realtime envelopes with replay recovery, recording, and camera-to-server or optional native vision context. You do not install the Node SDK separately; this package includes and re-exports the shared client.
import { useRef } from "react";
import { CameraView } from "expo-camera";
import { useVoiceAgent } from "@smarthivelabs-devs/ai-nexus-expo";
export function InterviewScreen() {
const camera = useRef<CameraView>(null);
const agent = useVoiceAgent({
client: nexus,
agentId: "interviewer-v1",
behavior: {
preset: "interviewer",
overrides: {
language: {
mode: "automatic",
allowed: ["en", "fr", "es"],
allowCodeSwitching: true,
},
},
},
vision: { preset: "interview" },
visionRuntime: "auto", // native only when real processors exist; otherwise server
visionConsent: true,
captureVisionFrame: async () => {
const picture = await camera.current!.takePictureAsync({ quality: 0.5 });
return { uri: picture!.uri, mimeType: "image/jpeg" };
},
tools: [{
type: "function",
function: {
name: "save_answer",
description: "Save the current interview answer after user confirmation",
parameters: { type: "object", properties: { answer: { type: "string" } }, required: ["answer"] },
},
execution: { mode: "client" },
}],
onTranscript: (entry) => console.log(entry.role, entry.text),
onVisionObservation: (observations) => console.log(observations),
onToolCall: {
save_answer: async (call) => {
await saveAnswerSecurely(call.arguments);
return { saved: true };
},
},
onError: (error) => Alert.alert("Realtime error", error.message),
});
return (
<View>
<CameraView ref={camera} style={{ width: 1, height: 1 }} />
<Text>State: {agent.state}</Text>
<Text>Speaking: {agent.speakingRole ?? "nobody"}</Text>
<Text>
Vision: {agent.visionReadiness.runtime} / {agent.visionReadiness.analysis}
</Text>
<Button title="Connect" onPress={() => void agent.connect()} />
<Button
title={agent.isMuted ? "Unmute" : "Mute"}
onPress={() => void agent.toggleMute()}
/>
<Button title="Speaker / earpiece" onPress={() => void agent.toggleSpeaker()} />
<Button title="Disconnect" onPress={() => void agent.disconnect()} />
</View>
);
}Important return fields:
| Field | Description |
|---|---|
| state | idle, connecting, active, ending, ended, or error |
| connect() / disconnect() | Complete Nexus and LiveKit lifecycle |
| isMuted / toggleMute() | Actual LiveKit microphone state |
| isAgentSpeaking | Whether a remote agent is an active speaker |
| speakingRole | agent, user, or null |
| volumeLevel | Current active-speaker level |
| transcript | Realtime envelope transcript with reliable replay recovery |
| visionCapabilities | Whether genuine native processors and bundled models are available |
| visionReadiness | Separate camera, upload, analysis, AI-context, and selected-runtime readiness |
| startRecording() / stopRecording() | Server-side recording controls |
Vision behavior on mobile
- Ordinary Expo camera access is enough for the default server path. Install
expo-camera, render aCameraView, and providecaptureVisionFrame; no AI Nexus native vision module is required. autoselects genuine native processing only whenavailable: true; otherwise it selects the server path.- The default server cadence is on-demand plus at most one frame every five seconds. Audio continues if camera permission, capture, upload, or inference fails.
- When native processors are available, structured observations are forwarded to the agent automatically.
- The agent receives compact counts, labels, and permitted visible text—not continuous raw frames.
- On an on-demand request, the latest structured observation is republished.
- When native processors are unavailable,
visionCapabilities.availableandmodelsBundledare false. This does not describe the separate server path. - Expo Go always reports reduced capability. Use a development or production build for native modules.
- The current package includes the native bridge and configuration surface; applications must link compatible MediaPipe/OCR processors for full native inference.
Never turn face, gaze, pose, or gesture data into claims about identity, emotion, honesty, confidence, mental state, health, or suitability.
Behavior and vision presets
Behavior presets: professional, interviewer, coach, support, tutor, concise, expressive.
Vision presets: interview, product-support, whiteboard, presentation, accessibility, document, camera-basic, none.
Hook: useVoiceCall (legacy credential-level API)
This compatibility hook requests microphone permission, creates the Nexus session, returns LiveKit credentials, polls transcripts, and manages recording. It does not own a LiveKit room. New applications should use useVoiceAgent.
toggleMute() in this lower-level hook updates SDK state only; wire that state to the Room.localParticipant you create. useVoiceAgent.toggleMute() controls the actual LiveKit microphone.
import { useVoiceCall } from '@smarthivelabs-devs/ai-nexus-expo';
import { useRef, useEffect } from 'react';
import { Room } from 'livekit-client';
function VoiceCallScreen() {
const roomRef = useRef<Room | null>(null);
const {
state, // 'idle' | 'connecting' | 'active' | 'ending' | 'ended' | 'error'
sessionId,
livekitUrl, // wss:// URL — connect your LiveKit Room here
livekitToken, // JWT — participant token for the LiveKit room
isMuted,
toggleMute,
transcript, // { role: 'user'|'agent', text: string, timestamp: string }[]
error,
start,
end,
startRecording,
stopRecording,
} = useVoiceCall({
client: nexus,
agentId: 'agent_abc123',
mode: 'voice', // 'voice' | 'text' | 'duplex'
features: ['transcription', 'tts', 'vad'],
// How often to poll for new transcript entries (ms). Default: 2000
pollIntervalMs: 2_000,
onTranscript: (entry) => {
console.log(`${entry.role}: ${entry.text}`);
},
onError: (err) => Alert.alert('Voice call error', err.message),
});
// Connect to LiveKit once the session starts
useEffect(() => {
if (state === 'active' && livekitUrl && livekitToken) {
const room = new Room();
roomRef.current = room;
room.connect(livekitUrl, livekitToken).catch(console.error);
return () => { void room.disconnect(); };
}
}, [state, livekitUrl, livekitToken]);
const handleStop = async () => {
const url = await stopRecording('mp4');
if (url) console.log('Recording saved at:', url);
};
return (
<View>
<Text>Status: {state}</Text>
{state === 'idle' && (
<TouchableOpacity onPress={start} style={styles.startBtn}>
<Text>Start Voice Call</Text>
</TouchableOpacity>
)}
{state === 'connecting' && <ActivityIndicator />}
{state === 'active' && (
<View>
<TouchableOpacity onPress={end} style={styles.endBtn}>
<Text>End Call</Text>
</TouchableOpacity>
<TouchableOpacity onPress={toggleMute}>
<Text>{isMuted ? '🔇 Unmute' : '🎤 Mute'}</Text>
</TouchableOpacity>
<TouchableOpacity onPress={startRecording}>
<Text>Record</Text>
</TouchableOpacity>
<TouchableOpacity onPress={handleStop}>
<Text>Stop Recording</Text>
</TouchableOpacity>
</View>
)}
{error && <Text style={styles.error}>{error.message}</Text>}
<ScrollView>
{transcript.map((t, i) => (
<View key={i} style={t.role === 'user' ? styles.userLine : styles.agentLine}>
<Text style={styles.role}>{t.role}</Text>
<Text>{t.text}</Text>
</View>
))}
</ScrollView>
</View>
);
}How it works:
start()— requests mic permission, configuresAVAudioSessionfor recording on iOS, callsnexus.realtime.sessions.create(), returnslivekitUrl+livekitToken- Your component connects to the LiveKit room using those credentials
- The hook polls
nexus.realtime.sessions.get()everypollIntervalMsms for new transcript entries end()— sends end request, resets iOS audio session, stops polling
VoiceCallState transitions:
idle → connecting → active → ending → ended
↘ errorOptions:
| Option | Type | Description |
|--------|------|-------------|
| client | AiNexus | Required. The AI Nexus client. |
| agentId | string | Required. Agent to connect to. |
| mode | RealtimeMode? | 'voice' (default), 'text', or 'duplex' |
| features | RealtimeFeature[]? | 'transcription', 'tts', 'vad', 'recording' |
| behavior | behavior preset/profile | Human-conversation behavior configuration |
| vision | vision preset/config | Session vision policy and capabilities |
| pollIntervalMs | number? | Transcript poll interval in ms. Default: 2000 |
| onTranscript | (entry) => void | Called for each new transcript entry |
| onError | (err: Error) => void | Called on any error |
Hook: useAudioRecording
Low-level hook for recording audio and sending it to Whisper for transcription.
import { useAudioRecording } from '@smarthivelabs-devs/ai-nexus-expo';
function VoiceNoteScreen() {
const {
isRecording,
uri, // local file path after recording
transcript, // transcribed text after calling transcribe()
isTranscribing,
error,
requestPermissions,
start,
stop,
transcribe,
} = useAudioRecording();
useEffect(() => {
// Request permissions on mount
requestPermissions();
}, []);
const handlePress = async () => {
if (isRecording) {
await stop();
// Now transcribe automatically
const result = await transcribe(nexus, 'whisper-large-v3');
console.log('Transcription:', result.text);
} else {
await start();
}
};
return (
<View>
<TouchableOpacity onPressIn={start} onPressOut={stop} style={styles.recordBtn}>
<Text>{isRecording ? '⏹ Recording...' : '🎙 Hold to record'}</Text>
</TouchableOpacity>
{isTranscribing && <Text>Transcribing...</Text>}
{transcript && <Text>{transcript}</Text>}
{uri && <Text style={styles.muted}>Saved: {uri}</Text>}
{error && <Text style={styles.error}>{error.message}</Text>}
</View>
);
}Returns:
| Field | Type | Description |
|-------|------|-------------|
| isRecording | boolean | true while recording is in progress |
| uri | string \| null | Local file path after stop() |
| transcript | string \| null | Transcribed text after transcribe() |
| isTranscribing | boolean | true while STT request is in flight |
| error | Error \| null | Last error |
| requestPermissions() | () => Promise<boolean> | Request mic permission, returns true if granted |
| start() | () => Promise<void> | Start recording |
| stop() | () => Promise<string \| null> | Stop recording, return local URI |
| transcribe(client, model?) | (AiNexus, string?) => Promise<AudioTranscribeResponse> | Upload and transcribe the last recording |
Class: ExpoAudioRecorder
Direct class API for recording — use when you need more control than the hook provides.
import { ExpoAudioRecorder } from '@smarthivelabs-devs/ai-nexus-expo';
const recorder = new ExpoAudioRecorder();
// Check/request microphone permission
const granted = await recorder.requestPermissions();
if (!granted) throw new Error('Mic permission denied');
// Start recording (configures AVAudioSession on iOS automatically)
await recorder.start();
// ... user speaks ...
// Stop and get local file URI
const uri = await recorder.stop();
console.log('Recorded to:', uri);
// Upload to SmartHive storage and transcribe
const transcript = await recorder.uploadAndTranscribe(nexus, {
model: 'whisper-large-v3',
language: 'en',
});
console.log(transcript.text);
// Helpers
recorder.isRecording(); // boolean
recorder.getUri(); // string | null — path of the last recordingDefault recording settings:
- iOS / Android:
.m4a, 44100 Hz, mono, 128 kbps AAC - Web: browser default
Class: ExpoAudioPlayer
Play TTS audio from an ArrayBuffer (returned by nexus.audio.speak()).
import { ExpoAudioPlayer } from '@smarthivelabs-devs/ai-nexus-expo';
const player = new ExpoAudioPlayer();
// Option A — play raw ArrayBuffer
const tts = await nexus.audio.speak({
text: 'Hello from SmartHive!',
model: 'tts-1-hd',
voiceProfile: 'nova',
response_format: 'mp3',
});
await player.play(tts.data);
// Option B — speak shortcut (fetches + plays in one call)
await player.speak(nexus, {
text: 'How can I help you today?',
voiceProfile: 'nova',
});
// Controls
await player.pause();
await player.resume();
await player.stop(); // unloads the sound
player.isPlaying(); // booleanClass: LiveKitSession
Direct wrapper around livekit-client's Room for cases where you want to manage the WebRTC session manually (instead of using the hook).
import { LiveKitSession } from '@smarthivelabs-devs/ai-nexus-expo';
// 1. Create a realtime session via the Nexus API
const session = await nexus.realtime.sessions.create({
agentId: 'agent_abc123',
mode: 'voice',
features: ['transcription', 'tts', 'vad'],
});
// 2. Connect LiveKit
const livekit = new LiveKitSession();
await livekit.connect({
url: session.livekitUrl,
token: session.livekitToken,
onConnected: () => console.log('Connected to LiveKit room'),
onDisconnected: () => console.log('Disconnected'),
onError: (err) => console.error('LiveKit error:', err),
onDataMessage: (type, payload) => {
// Includes transcript/state messages and nexus.rtc.v1 envelopes.
console.log(type, payload);
},
onToolCall: async (call) => {
return executeApprovedClientTool(call);
},
});
// 3. Mic control
await livekit.setMicrophoneEnabled(true); // start publishing audio
await livekit.setMicrophoneEnabled(false); // mute
// 4. Session state
console.log(livekit.getState());
// 'idle' | 'connecting' | 'connected' | 'disconnected' | 'error'
// 5. Disconnect
livekit.disconnect();
// 6. End the Nexus session
await nexus.realtime.sessions.end(session.sessionId);Application-to-agent controls can be sent with:
await livekit.publishData({ type: "nexus.control", action: "interrupt" });
await livekit.publishData({ type: "nexus.control", action: "request-vision-frame" });When implementing manual reconnection, persist the highest reliable event sequence and call nexus.realtime.sessions.resume() with the session's signed resumeToken.
Hook: useVisionAnalysis
Use the standalone hook for selected images, camera-to-server analysis, or native analysis that is not attached to useVoiceAgent:
const vision = useVisionAnalysis({
runtime: "server",
client: nexus,
sessionId,
consent: true,
captureFrame: async () => ({ uri: (await camera.current!.takePictureAsync({ quality: 0.5 }))!.uri }),
config: {
detectors: ["face", "object", "pose"],
sources: ["local-camera", "image"],
targetFps: 5,
confidenceThreshold: 0.6,
contextPolicy: { mode: "signals" },
},
onObservations: console.log,
});
await vision.startAnalysis();
const observations = await vision.analyzeImage(imageUri);
console.log(vision.runtime, observations);Aliases are exported for discoverability: useFacialAnalysis, useObjectDetection, usePoseAnalysis, useGestureRecognition, and useRealtimeVisionContext.
Complete Example: Voice-to-Text Note Taking
import React, { useState, useEffect } from 'react';
import { View, Text, TouchableOpacity, FlatList, StyleSheet } from 'react-native';
import { AiNexus, useAudioRecording } from '@smarthivelabs-devs/ai-nexus-expo';
// Use an application backend that injects the permanent key server-side.
const nexus = new AiNexus({ apiKey: 'mobile-proxy', baseUrl: 'https://yourapi.com/nexus' });
export function VoiceNotesScreen() {
const [notes, setNotes] = useState<string[]>([]);
const { isRecording, transcript, isTranscribing, error, requestPermissions, start, stop, transcribe } = useAudioRecording();
useEffect(() => {
requestPermissions();
}, []);
useEffect(() => {
if (transcript) setNotes(prev => [transcript, ...prev]);
}, [transcript]);
const handlePress = async () => {
if (isRecording) {
await stop();
await transcribe(nexus);
} else {
await start();
}
};
return (
<View style={styles.container}>
<TouchableOpacity style={[styles.btn, isRecording && styles.recording]} onPress={handlePress}>
<Text style={styles.btnText}>
{isRecording ? '⏹ Stop' : isTranscribing ? 'Transcribing...' : '🎙 Record'}
</Text>
</TouchableOpacity>
{error && <Text style={styles.error}>{error.message}</Text>}
<FlatList
data={notes}
keyExtractor={(_, i) => String(i)}
renderItem={({ item }) => <Text style={styles.note}>{item}</Text>}
/>
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1, padding: 16 },
btn: { backgroundColor: '#007AFF', padding: 16, borderRadius: 8, alignItems: 'center' },
recording: { backgroundColor: '#FF3B30' },
btnText: { color: 'white', fontWeight: 'bold', fontSize: 16 },
error: { color: 'red', marginTop: 8 },
note: { padding: 12, borderBottomWidth: 1, borderBottomColor: '#E5E5EA' },
});Translation & Video Understanding
These capabilities don't have dedicated Expo hooks — call the core client directly, which works fine in React Native:
import { AiNexus } from '@smarthivelabs-devs/ai-nexus-expo';
const nexus = new AiNexus({
apiKey: 'mobile-client',
baseUrl: 'https://yourapi.com/nexus',
});
// Translate text
const translation = await nexus.translate.create({
text: 'Hello from my app!',
targetLang: 'ES',
});
console.log(translation.translatedText); // "¡Hola desde mi aplicación!"
// Analyze a video (Twelve Labs — requires pre-indexed video ID)
const analysis = await nexus.videoUnderstanding.analyze({
videoId: 'video_abc123',
query: 'Describe what happens in this video.',
});
console.log(analysis.text);For use inside components, wrap in useState / useEffect or a simple async handler — no special hook needed since these are single-call operations.
TypeScript
All types are exported:
import type {
// Hooks
UseExpoChatOptions, UseExpoChatReturn,
UseExpoVoiceCallOptions, UseExpoVoiceCallReturn,
VoiceCallState, TranscriptEntry,
UseVoiceAgentOptions, UseVoiceAgentReturn, VoiceAgentState,
UseAudioRecordingReturn,
UseExpoVisionAnalysisOptions,
NativeVisionCapabilities,
// LiveKit
LiveKitSessionOptions, LiveKitSessionState,
NexusToolCall, NexusToolHandler,
} from '@smarthivelabs-devs/ai-nexus-expo';
import type {
ChatMessage,
AudioTranscribeResponse,
RealtimeMode,
RealtimeFeature,
RealtimeEnvelope,
ConversationBehaviorProfile,
ConversationBehaviorPreset,
VisionAnalysisConfig,
VisionConfigInput,
VisionObservation,
TranslateParams, TranslateResponse,
VideoUnderstandingParams, VideoUnderstandingResponse,
} from '@smarthivelabs-devs/ai-nexus-expo';License
MIT — © SmartHive Labs
