Configuration Overview
The NAVAI frontend SDK supports flexible configuration through:
- Hook Options: Direct parameters to
useWebVoiceAgent
- Environment Variables: Runtime configuration via env vars
- Module Loaders: Dynamic imports for routes and functions
- Backend Client: API connection settings
Backend Client Setup
createNavaiBackendClient
The backend client handles communication with your NAVAI API server.
import { createNavaiBackendClient } from '@navai/voice-frontend';
const client = createNavaiBackendClient({
apiBaseUrl: 'https://api.example.com',
env: {
NAVAI_API_URL: 'https://api.example.com'
}
});
// Client methods
await client.createClientSecret({ model: 'gpt-4o-realtime-preview' });
await client.listFunctions();
await client.executeFunction({ functionName: 'getUserData', payload: { userId: 123 } });
Type Signature
type CreateNavaiBackendClientOptions = {
apiBaseUrl?: string;
env?: Record<string, string | undefined>;
fetchImpl?: typeof fetch;
clientSecretPath?: string;
functionsListPath?: string;
functionsExecutePath?: string;
};
type NavaiBackendClient = {
createClientSecret: (input?: CreateClientSecretInput) => Promise<CreateClientSecretOutput>;
listFunctions: () => Promise<BackendFunctionsResult>;
executeFunction: ExecuteNavaiBackendFunction;
};
Client Options
apiBaseUrl
string
default:"http://localhost:3000"
Base URL for the NAVAI backend API. Overrides NAVAI_API_URL from env.apiBaseUrl: 'https://api.production.com'
env
Record<string, string | undefined>
Environment variables. The client reads NAVAI_API_URL if provided.
Custom fetch implementation. Useful for testing or adding interceptors.
clientSecretPath
string
default:"/navai/realtime/client-secret"
API endpoint path for requesting client secrets.
functionsListPath
string
default:"/navai/functions"
API endpoint path for listing backend functions.
functionsExecutePath
string
default:"/navai/functions/execute"
API endpoint path for executing backend functions.
Environment Variables
The SDK recognizes the following environment variables:
NAVAI_API_URL
Base URL for the NAVAI backend API.
NAVAI_API_URL=https://api.example.com
Pass to the hook via the env option:
const { start } = useWebVoiceAgent({
navigate,
defaultRoutes: ROUTES,
moduleLoaders,
env: {
NAVAI_API_URL: process.env.REACT_APP_NAVAI_API_URL
}
});
NAVAI_ROUTES_FILE
Path to custom routes module.
NAVAI_ROUTES_FILE=src/config/voice-routes.ts
The SDK will attempt to load routes from this file if it exists in moduleLoaders. Falls back to defaultRoutes if not found.
const { start } = useWebVoiceAgent({
navigate,
defaultRoutes: FALLBACK_ROUTES,
moduleLoaders: {
'src/config/voice-routes.ts': () => import('./config/voice-routes')
},
env: {
NAVAI_ROUTES_FILE: 'src/config/voice-routes.ts'
}
});
NAVAI_FUNCTIONS_FOLDERS
Comma-separated paths or globs for discovering function modules.
NAVAI_FUNCTIONS_FOLDERS=src/ai/functions,src/custom/functions
Supports multiple patterns:
# Multiple folders
NAVAI_FUNCTIONS_FOLDERS=src/ai/functions,src/custom/functions
# Recursive
NAVAI_FUNCTIONS_FOLDERS=src/ai/functions/...
# Glob patterns
NAVAI_FUNCTIONS_FOLDERS=src/*/functions
NAVAI_REALTIME_MODEL
Override the OpenAI Realtime model.
NAVAI_REALTIME_MODEL=gpt-4o-realtime-preview-2024-12-17
Usage:
const { start } = useWebVoiceAgent({
navigate,
defaultRoutes: ROUTES,
moduleLoaders,
env: {
NAVAI_REALTIME_MODEL: process.env.REACT_APP_REALTIME_MODEL
}
});
Runtime Configuration Resolution
The SDK resolves configuration in the following order (highest priority first):
Routes Resolution
- routesFile hook option
- NAVAI_ROUTES_FILE env var
- defaultRoutesFile hook option (default:
src/ai/routes.ts)
- defaultRoutes hook option (fallback)
Functions Resolution
- functionsFolders hook option
- NAVAI_FUNCTIONS_FOLDERS env var
- defaultFunctionsFolder hook option (default:
src/ai/functions-modules)
Model Resolution
- modelOverride hook option
- NAVAI_REALTIME_MODEL env var
- Backend default (if not specified)
API URL Resolution
- apiBaseUrl hook option
- NAVAI_API_URL env var
- Default:
http://localhost:3000
Module Loaders
Module loaders map file paths to dynamic import functions. They’re used to load routes and functions at runtime.
Basic Example
const moduleLoaders = {
'src/ai/routes.ts': () => import('./ai/routes'),
'src/ai/functions/greet.ts': () => import('./ai/functions/greet'),
'src/ai/functions/search.ts': () => import('./ai/functions/search')
};
const { start } = useWebVoiceAgent({
navigate,
defaultRoutes: [],
moduleLoaders
});
Auto-Generated Loaders
For Vite/Webpack projects, use glob imports:
// Vite
const modules = import.meta.glob('./ai/**/*.ts');
const moduleLoaders = Object.fromEntries(
Object.entries(modules).map(([path, loader]) => [
path.replace('./', 'src/'),
loader
])
);
// Webpack
const context = require.context('./ai', true, /\.ts$/);
const moduleLoaders = {};
for (const key of context.keys()) {
const path = `src/ai${key.slice(1)}`;
moduleLoaders[path] = () => context(key);
}
CLI Generator
The package includes a CLI tool to generate loaders:
npx navai-generate-web-loaders
This creates src/ai/navai-web-loaders.ts with all discoverable modules.
Example: Complete Configuration
import { useWebVoiceAgent } from '@navai/voice-frontend';
import { useNavigate } from 'react-router-dom';
// Import generated loaders
import { MODULE_LOADERS } from './ai/navai-web-loaders';
// Fallback routes if dynamic loading fails
const FALLBACK_ROUTES = [
{ name: 'home', path: '/', description: 'Home page' },
{ name: 'settings', path: '/settings', description: 'Settings' }
];
function App() {
const navigate = useNavigate();
const voiceAgent = useWebVoiceAgent({
// Required
navigate,
defaultRoutes: FALLBACK_ROUTES,
moduleLoaders: MODULE_LOADERS,
// Optional: Backend
apiBaseUrl: process.env.REACT_APP_NAVAI_API_URL,
// Optional: Routes
routesFile: 'src/config/custom-routes.ts',
defaultRoutesFile: 'src/ai/routes.ts',
// Optional: Functions
functionsFolders: 'src/ai/functions,src/custom/functions',
defaultFunctionsFolder: 'src/ai/functions-modules',
// Optional: Model
modelOverride: process.env.REACT_APP_REALTIME_MODEL,
// Optional: Environment
env: {
NAVAI_API_URL: process.env.REACT_APP_NAVAI_API_URL,
NAVAI_ROUTES_FILE: process.env.REACT_APP_ROUTES_FILE,
NAVAI_FUNCTIONS_FOLDERS: process.env.REACT_APP_FUNCTIONS_FOLDERS,
NAVAI_REALTIME_MODEL: process.env.REACT_APP_REALTIME_MODEL
}
});
return (
<div>
<button onClick={voiceAgent.start}>Start Voice</button>
<button onClick={voiceAgent.stop}>Stop Voice</button>
{voiceAgent.status === 'connected' && <p>🎤 Listening</p>}
</div>
);
}
Configuration Best Practices
Use Environment Variables for URLs
Store API URLs and model names in environment variables, not hardcoded.REACT_APP_NAVAI_API_URL=https://api.production.com
REACT_APP_REALTIME_MODEL=gpt-4o-realtime-preview
Provide Fallback Routes
Always specify defaultRoutes as a fallback if dynamic route loading fails.defaultRoutes: [
{ name: 'home', path: '/', description: 'Home' }
]
Generate Module Loaders at Build Time
Use the CLI tool or build-time glob imports to generate loaders automatically.npx navai-generate-web-loaders
Handle Connection Errors
Monitor the status and error fields to provide user feedback.if (status === 'error') {
console.error('Voice agent failed:', error);
}
Debugging Configuration
The SDK emits warnings to the console for configuration issues:
// Route file not found
[navai] Route module "src/custom-routes.ts" was not found. Falling back to "src/ai/routes.ts".
// Function folder mismatch
[navai] NAVAI_FUNCTIONS_FOLDERS did not match any module: "src/missing". Falling back to "src/ai/functions-modules".
// Backend function name conflict
[navai] Ignored backend function "getUserData": name conflicts with a frontend function.
// Invalid function name
[navai] Function "my function" is available only via execute_app_function because its name is not a valid tool id.
Enable verbose console logging during development to catch configuration issues early.